首页 > 解决方案 > 将 2 个 Pandas 列表填充列连接成 1 个大列表?

问题描述

我有一个看起来像这样的 Pandas DataFrame:

     NAME      total           total_temp
ID                                      
1     CVS     [abc1]       [cba, xyzzy01]
2  Costco     [bcd2, 22]   [dcb, xyzzy02]
3   Apple     [cde3]       [edc, xyzzy03]

我想添加创建一个新列 total_temp_2 以便数据如下所示:

     NAME      total       total_temp                   total_temp_2
ID                                                  
1     CVS     [abc1]       [cba, xyzzy01]       [abc1, cba, xyzzy01]
2  Costco     [bcd2, 22]   [dcb, xyzzy02]   [bcd2, 22, dcb, xyzzy02]
3   Apple     [cde3]       [edc, xyzzy03]       [cde3, edc, xyzzy03]

我觉得我可以通过非常低效的方式来连接列表,但我怀疑我错过了一些我不知道的关于 Pandas 的东西。

如何使用 pandas 实现此操作?

标签: pythonpandas

解决方案


在处理混合类型时,我通常建议使用诸如列表推导之类的东西,它具有最小的内存和性能开销。

df['total_temp_2'] = [x + y for x, y in zip(df['total'], df['total_temp'])]
df

      NAME       total      total_temp              total_temp_2
ID                                                              
1      CVS      [abc1]  [cba, xyzzy01]      [abc1, cba, xyzzy01]
2   Costco  [bcd2, 22]  [dcb, xyzzy02]  [bcd2, 22, dcb, xyzzy02]
3    Apple      [cde3]  [edc, xyzzy03]      [cde3, edc, xyzzy03]

如果这些是字符串列,您可以使用ast.literal_eval它们来解析它们:

import ast

c = df.select_dtypes(include=[object]).columns
df[c] = df[c].applymap(ast.literal_eval)

如果上面的解决方案抛出ValueError: malformed node or string:,请尝试改用该yaml包。

import yaml
df = df.applymap(yaml.load)

有趣的是,简单的加法在 0.24 上对我有用。

df['total'] + df['total_temp']

ID
1        [abc1, cba, xyzzy01]
2    [bcd2, 22, dcb, xyzzy02]
3        [cde3, edc, xyzzy03]
dtype: object

这些也有效,

df['total'].add(df['total_temp'])

ID
1        [abc1, cba, xyzzy01]
2    [bcd2, 22, dcb, xyzzy02]
3        [cde3, edc, xyzzy03]
dtype: object

df['total_temp'].radd(df['total'])

ID
1        [abc1, cba, xyzzy01]
2    [bcd2, 22, dcb, xyzzy02]
3        [cde3, edc, xyzzy03]
dtype: object

这些在简单性方面很棒,但本质上是循环的,因为混合类型的操作更难向量化。


推荐阅读