Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将表的每一行转换为列表并添加到表中_Python_List_Pandas_Dataframe - Fatal编程技术网

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
相比有效?