python - 从数据框中的列值返回列表

标签 python pandas

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/

相关文章:

python - Re-factoring To MVC pattern——view与controller分离的疑惑

python - 如何执行多个系列的按元素求和,保留 NaN

pandas - 将 Pandas DataFrame 转换为类似字节的对象

python-3.x - pandas groupby 并转换为中位数给出 NaN

python - 错误 : Unsupported format, 或损坏的文件:预期的 BOF 记录;发现 b'<## NASC'

python - 如何迭代股票代码的 DataFrame 列并添加包含股票价格的列?

分组后对多列进行python操作

python - Google Analytics(分析)Python脚本-HelloAnalytics

python - appium ios python "an error occured while executing user supplied javascript"

python - 在python中打印出两个列表的组合