Stack Overflow 社区您好!
使用 Python,我想构建一个函数,该函数接受一行,然后返回一个新列,其中包含一个列表,其中包含该行中每列的值。这是我的例子--
+--------+--------+-------+
| first | second | third |
+--------+--------+-------+
| monkey | banana | time |
| banana | monkey | time |
| time | monkey | time |
+--------+--------+-------+
我想返回的是:
+--------+--------+-------+----------------------------+
| first | second | third | list |
+--------+--------+-------+----------------------------+
| monkey | banana | time | ['monkey','banana','time'] |
| banana | monkey | time | ['banana','monkey','time'] |
| time | monkey | time | ['time','monkey','time'] |
+--------+--------+-------+----------------------------+
我尝试过这个函数(对于具有 14 列的数据框),但它不起作用:
def return_list_for_importance_rank(row):
row_list = []
my_list = [row.first, row.second, row.third, row.fourth, row.fifth, row.sixth, row.seventh, row.eighth, row.ninth, row.tenth, row.eleventh, row.twelfth, row.thirteenth, row.fourteenth]
row_list.append(my_list)
return row_list
importance_rank["full"] = df.apply(lambda x: return_list_for_importance_rank(x),axis=1)
返回了这个:
<bound method NDFrame.first of first None\nsecond None\nthird None\nfourth None\nfifth None\nsixth None\nseventh None\neighth None\nninth None\ntenth None\neleventh None\ntwelfth None\nthirteenth None\nfourteenth None\nfull None\n
在每行的“完整”列中。
最佳答案
尝试:
df['list'] = df.to_numpy().tolist()
输出:
first second third list
0 monkey banana time [monkey, banana, time]
1 banana monkey time [banana, monkey, time]
2 time monkey time [time, monkey, time]
关于python - 从数据框中的列值返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62433199/