Python 将表的每一行转换为列表并添加到表中
我想将每一行转换成一个列表,并作为一个新列插入。 例如,我从下表开始:Python 将表的每一行转换为列表并添加到表中,python,list,pandas,dataframe,Python,List,Pandas,Dataframe,我想将每一行转换成一个列表,并作为一个新列插入。 例如,我从下表开始: 0 1 2 3 4 0 0 8 3 2 5 1 1 1 2 2 4 2 0 8 9 6 4 3 2 7 6 1 9 4 8 9 1 5 6 并希望获得: 0 1 2 3 4 test 0 0 8 3 2 5 [0, 8, 3, 2, 5] 1 1 1 2 2 4 [1, 1, 2, 2, 4] 2 0 8 9 6
0 1 2 3 4
0 0 8 3 2 5
1 1 1 2 2 4
2 0 8 9 6 4
3 2 7 6 1 9
4 8 9 1 5 6
并希望获得:
0 1 2 3 4 test
0 0 8 3 2 5 [0, 8, 3, 2, 5]
1 1 1 2 2 4 [1, 1, 2, 2, 4]
2 0 8 9 6 4 [0, 8, 9, 6, 4]
3 2 7 6 1 9 [2, 7, 6, 1, 9]
4 8 9 1 5 6 [8, 9, 1, 5, 6]
这是我的代码片段,我希望它能实现这一点,但它没有实现
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)))
df['list'] = df.apply(lambda x: x.tolist(), axis=1)
print(df)
您可以使用:
In [127]: df['test'] = df.values.tolist()
In [128]: df
Out[128]:
0 1 2 3 4 test
0 0 8 3 2 5 [0, 8, 3, 2, 5]
1 1 1 2 2 4 [1, 1, 2, 2, 4]
2 0 8 9 6 4 [0, 8, 9, 6, 4]
3 2 7 6 1 9 [2, 7, 6, 1, 9]
4 8 9 1 5 6 [8, 9, 1, 5, 6]
您可以使用:
In [127]: df['test'] = df.values.tolist()
In [128]: df
Out[128]:
0 1 2 3 4 test
0 0 8 3 2 5 [0, 8, 3, 2, 5]
1 1 1 2 2 4 [1, 1, 2, 2, 4]
2 0 8 9 6 4 [0, 8, 9, 6, 4]
3 2 7 6 1 9 [2, 7, 6, 1, 9]
4 8 9 1 5 6 [8, 9, 1, 5, 6]
+一个正确的答案。但我认为我们有必要评论一下,在数据帧中存储列表通常是一个糟糕的设计选择。您放弃了所有矢量化功能。为什么分配
df.values.tolist()
与df.values
相比会产生ValueError
?+1以获得正确答案。但我认为我们有必要评论一下,在数据帧中存储列表通常是一个糟糕的设计选择。您放弃了所有矢量化功能。为什么分配df.values.tolist()
与引发ValueError
的df.values
相比有效?