python - 将 2 个 Pandas 列表填充的列连接成 1 个大列表?

标签 python pandas

我有一个 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 实现此操作?

最佳答案

处理混合类型时,I usually recommend using something like a list comprehension其内存和性能开销最小。

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

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

关于python - 将 2 个 Pandas 列表填充的列连接成 1 个大列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54634602/

相关文章:

python - 在固定宽度文本文件中的多个位置添加分隔符时出现问题

python - 在 Python 3 中将 CSV 文件附加到新的 CSV 文件时,单词之间出现不需要的 ""

python - 按正确的顺序对间隔进行排序

python - 将数据与其他数据框合并时如何避免数据框中的列很少?

python - 从 Python 到 Excel 的 Excel 公式格式

python - OpenERP名称错误: name '_date_of_q_created' is not defined

python - Django 教程 NoReverseMatch

python - python中的prolog fact词法分析器

Python pandas 数据框限制

python - 在附加条件下与 pd.NamedAgg 聚合