python - 将 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 实现此操作?
解决方案
在处理混合类型时,我通常建议使用诸如列表推导之类的东西,它具有最小的内存和性能开销。
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
这些在简单性方面很棒,但本质上是循环的,因为混合类型的操作更难向量化。
推荐阅读
- django - 结合 __startswith 和 __in 不起作用
- sql - 向“日期”列添加值的错误导致溢出
- javascript - 向 mongoDB 中的多个文档添加属性
- antlr4 - 用 antlr4 处理平面文件
- python - Python 正则表达式无法按预期在我的脚本中工作
- c++ - 错误:无法获取“void”类型的右值的地址
- android - BottomsheetdialogFragment 内的 Viewpager 不显示片段
- python - 按日期切片多索引熊猫数据帧
- javascript - 在反应中读取excel文件
- r - 如何从 density.lpp 绘制特定段