Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.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_Pandas Groupby - Fatal编程技术网

Python 将中的映射列合并到数据帧中的单个列

Python 将中的映射列合并到数据帧中的单个列,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我正在尝试将pandas数据框中包含dictionary的行合并为一行。输出应具有该列的最新键值和所有键 这是输入数据框 df = pd.DataFrame([[{'a': 1, 'c': 2}, {'a': 3, 'b': 4}], [{'a': 5, 'b': 6}, {'a': 7, 'b': 8}]], columns=list('AB')) 期望 A B 0 {'a': 5, 'b': 6, 'c': 2} {'

我正在尝试将pandas数据框中包含dictionary的行合并为一行。输出应具有该列的最新键值和所有键

这是输入数据框

df = pd.DataFrame([[{'a': 1, 'c': 2}, {'a': 3, 'b': 4}], [{'a': 5, 'b': 6}, {'a': 7, 'b': 8}]], columns=list('AB'))
期望

           A                     B
0   {'a': 5, 'b': 6, 'c': 2}    {'a': 7, 'b': 8}

谢谢

您可以尝试在听写理解中减少:

from functools import reduce

d = {c: reduce(lambda x, y:  {**x, **y}, df[c]) for c in df}
d = pd.DataFrame([d.values()], columns=d.keys())

这将为您提供预期的df:

def consolidate_dicts(input_df):
    # Create consolidated dicts
    dicts = []
    for col in input_df.columns:
        dicts.append({k: v for d in input_df[col] for k, v in d.items()})

    # Replicate original DataFrame with 1 row
    return_df= pd.DataFrame([dicts], columns=input_df.columns)
    return return_df

编辑:来自的答案比我的答案简单得多

您必须返回一个数据帧还是一本字典可以?
print(d)
                          A                 B
0  {'a': 5, 'c': 2, 'b': 6}  {'a': 7, 'b': 8}
def consolidate_dicts(input_df):
    # Create consolidated dicts
    dicts = []
    for col in input_df.columns:
        dicts.append({k: v for d in input_df[col] for k, v in d.items()})

    # Replicate original DataFrame with 1 row
    return_df= pd.DataFrame([dicts], columns=input_df.columns)
    return return_df