首页 > 解决方案 > 在 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'}

标签: pythonpandasdataframedictionary

解决方案


这是使用字典解包的一种方法:

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

推荐阅读