假設這是我的資料框
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],
})

我如何在最后獲得一列,其值是該行其他列的值串列
IE
新列的第一行將包含 [-23,-30,-4??0,-45],第二行將包含 [12,20,25,34],依此類推。
uj5u.com熱心網友回復:
用:
#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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311487.html
