Python 将两列字典连接在一起
我有一个有两列的数据框。每一列都有一个词汇表,例如:Python 将两列字典连接在一起,python,pandas,dataframe,dictionary,Python,Pandas,Dataframe,Dictionary,我有一个有两列的数据框。每一列都有一个词汇表,例如: 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')) 其中:
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'}
这里有一种方法使用:
或使用链图
:
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
通过循环,您可以通过以下方式完成:
for i in range(len(df)):
df.A.iloc[i].update(df.B.iloc[i])
result=df.A
也许还有一些更具python风格的方法,但是有没有好的理由避免使用字典键作为列?这将更符合数据帧的预期用途
>>> for letter in ("a", "b"):
df[letter] = [i[letter] for i in df.A]
>>> for letter in ("c", "d"):
df[letter] = [i[letter] for i in df.B]
>>> df = df.drop(["A", "B"], axis=1)
>>> df
a b c d
0 one two three four
1 five six seven eight
第一个已经对我有用了,非常感谢!对于具有两列以上数据帧的任何人,您只需使用以下命令指定要加入的列:
df[['a','b']]。to_numpy().tolist())
>>> for letter in ("a", "b"):
df[letter] = [i[letter] for i in df.A]
>>> for letter in ("c", "d"):
df[letter] = [i[letter] for i in df.B]
>>> df = df.drop(["A", "B"], axis=1)
>>> df
a b c d
0 one two three four
1 five six seven eight