python - Pandas:将数据帧的内容合并到单个列中(作为 dict/json 列表)

标签 python pandas dataframe numpy data-manipulation

我想将一个 df 的内容介绍给另一个 df,但作为基于 ID 的列表。我知道根据 ID 进行合并,但我不希望新数据框中的 ID 重复行。我该如何完成这件事?

data1 = {'ID': ['AB01','AB02'], 
    'Name': ["toyota", "honda"],
    'Age':[21,22]
   }
df1 = pd.DataFrame.from_dict(data1)
data2 = {'ID': ['AB01','AB01','AB03','AB03'], 
    'Type': ["C",np.nan,"X","S"],
    'Score':[87,98,45,82]
   }
df2 = pd.DataFrame.from_dict(data2)

Input dataframes

结果应该是这样的

enter image description here

最佳答案

您可以通过.apply()df2的行上创建dict ,然后按 ID 分组,并将相同 ID 的字典聚合到列表中 .groupby() + .agg() .

然后,将 df1.merge() 合并通过左连接以 ID 作为匹配键,如下:

df2_info = (df2.apply(dict, axis=1)
               .groupby(df2['ID'])
               .agg(list)
               .reset_index(name='Info')
           )

df_out = df1.merge(df2_info, on='ID', how='left')

结果

print(df_out)

     ID    Name  Age                                                                                  Info
0  AB01  toyota   21  [{'ID': 'AB01', 'Type': 'C', 'Score': 87}, {'ID': 'AB01', 'Type': nan, 'Score': 98}]
1  AB02   honda   22                                                                                   NaN

df2_info的临时结果仅供引用:

     ID                                                                                  Info
0  AB01  [{'ID': 'AB01', 'Type': 'C', 'Score': 87}, {'ID': 'AB01', 'Type': nan, 'Score': 98}]
1  AB03  [{'ID': 'AB03', 'Type': 'X', 'Score': 45}, {'ID': 'AB03', 'Type': 'S', 'Score': 82}]

关于python - Pandas:将数据帧的内容合并到单个列中(作为 dict/json 列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69333574/

相关文章:

python - 循环遍历 python 字典并操作每个值

R 合并 data.frames asof join

python - 根据条件打乱数据帧的行

python - 如何使用 .loc 通过 groupby pandas 标记新列

python - 提取另一列中列出的 pandas 中特定列名的值

python - 如何将一个列表插入另一个列表?

python - pandas dataframe 分组依据与排列

python - 将元组的一部分解包为元组

python - django admin更改 View 不显示图像缩略图

python - 为什么 numpy.where 不适用于 'double' 切片数组?