Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将两列字典连接在一起_Python_Pandas_Dataframe_Dictionary - Fatal编程技术网

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