python - 在 Pandas 中加入两列字典
问题描述
我有一个包含两列的数据框。每列都有一个字典,例如:
import pandas as pd
df = pd.DataFrame([[{'a': 'one', 'b': 'two'}, {'c': 'three', 'd': 'four'}],
[{'a': 'five', 'b': 'six'}, {'c': 'seven', 'd': 'eight'}]],
columns=list('AB'))
这使:
A B
0 {'a': 'one', 'b': 'two'} {'c': 'three', 'd': 'four'}
1 {'a': 'five', 'b': 'six'} {'c': 'seven', 'd': 'eight'}
考虑到在我的数据中某些条目可能为空,我想加入两列的字典,以便最终输出如下所示:
A
0 {'a': 'one', 'b': 'two', 'c': 'three', 'd': 'four'}
1 {'a': 'five', 'b': 'six', 'c': 'seven', 'd': 'eight'}
解决方案
这是使用字典解包的一种方法:
pd.Series(({**a,**b} for a,b in df.to_numpy().tolist()), name='A')
0 {'a': 'one', 'b': 'two', 'c': 'three', 'd': 'f...
1 {'a': 'five', 'b': 'six', 'c': 'seven', 'd': '...
Name: A, dtype: object
或与ChainMap
:
from collections import ChainMap
pd.Series((dict(ChainMap(*i)) for i in df.to_numpy().tolist()), name='A')
0 {'c': 'three', 'd': 'four', 'a': 'one', 'b': '...
1 {'c': 'seven', 'd': 'eight', 'a': 'five', 'b':...
Name: A, dtype: object
推荐阅读
- ruby-on-rails - 如何使用 gsub 删除 . 在红宝石字符串的末尾?
- laravel - Laravel + Vue 循环一次特定 ID
- user-interface - 小米的 Unity3d UI 问题
- python - 测试列表 A 是否包含在列表 B 中
- python - 是否可以将 lazarus 表单和 python 程序结合到可交付的应用程序中?
- docker - 在 Docker 中为当前用户启用 root
- javascript - 类 - 通过等待返回数据?
- php - 如何在 PHP 中制作单个 $format 元素
- django - 如何使用结构或其他方式将我的 conda env 部署到 VPS?
- python - 执行 `pip install mod_wsgi` 时`无法打开包含文件:'apr_perms_set.h'`