gpt4 book ai didi

python - 使用其他列的值列表创建一个列

转载 作者:行者123 更新时间:2023-12-05 02:38:31 26 4
gpt4 key购买 nike

假设这是我的数据框

import pandas as pd
import numpy as np

import pandas as pd
df = pd.DataFrame({'30': [-23, 12, -12, 10, -23, 12, -32, 15, -20, 10],
'40': [-30, 20, -21, 15, -33, 22, -40, 25, -22, 12],
'50': [-40, 25, -26, 19, -39, 32, -45, 35, -32, 18],
'60': [-45, 34, -29, 25, -53, 67, -55, 45, -42, 19],
})

enter image description here

如何在末尾获取一列,其值是该行其他列的值列表

新列的第一行将包含 [-23,-30,-4​​0,-45],第二行将包含 [12,20,25,34] 等等。

最佳答案

使用:

#if need all columns to lists
df['new'] = df.to_numpy().tolist()

#if need specify columns by list
cols = [30,40,50,60]
df['new'] = df[cols].to_numpy().tolist()
print (df)
30 40 50 60 new
0 -23 -30 -40 -45 [-23, -30, -40, -45]
1 12 20 25 34 [12, 20, 25, 34]
2 -12 -21 -26 -29 [-12, -21, -26, -29]
3 10 15 19 25 [10, 15, 19, 25]
4 -23 -33 -39 -53 [-23, -33, -39, -53]
5 12 22 32 67 [12, 22, 32, 67]
6 -32 -40 -45 -55 [-32, -40, -45, -55]
7 15 25 35 45 [15, 25, 35, 45]
8 -20 -22 -32 -42 [-20, -22, -32, -42]
9 10 12 18 19 [10, 12, 18, 19]

关于python - 使用其他列的值列表创建一个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69526914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com