虽然我认为这个问题应该重复,但我找不到合适的答案.

我在按顺序合并多个数据帧时遇到一些问题.

例如,我有以下四个数据帧:

df1 = pd.DataFrame({'source': ['A', 'A', 'A', 'B', 'B', 'C', 'C'],
       'target': ['1', '2', '3', '4', '5', '6', '7']})
df2 = pd.DataFrame({'source': ['A', 'A'],
       'temp': ['a', 'b']})
df3 = pd.DataFrame({'source': ['B', 'B'],
       'temp': ['c', 'd']})
df4 = pd.DataFrame({'source': ['C'],
       'temp': ['e']})

我想将数据帧合并如下:

#   source  target  temp
#0  A   1   a
#1  A   1   b
#2  A   2   a
#3  A   2   b
#4  A   3   a
#5  A   3   b
#6  B   4   c
#7  B   4   d
#8  B   5   c
#9  B   5   d
#10 C   6   e
#11 C   7   e

为此,我try 运行代码,但它返回了意外的结果.

#Trial 1
dfs = pd.merge(df1, df2, on='source', how='left')
dfs = pd.merge(dfs, df3, on='source', how='left') # new column was created with prefix, but I want to keep the three columns; source, target, temp

#Trial 2
dfs = pd.merge(df1, df2, on='source', how='left')
dfs['temp']=dfs.set_index('source')['temp'].fillna(df3.set_index('source')['temp'].to_dict()).values # it only fills the fixed number of NaN value, but there are some exception; one NaN in dfs, multiple values in other df3 or df4

#Trial 3
dfs = pd.merge(df1, df2, on='source', how='left')
dfs[dfs['source']=='B']['temp']=pd.merge(df1, df3, on='source', how='left')['temp'].dropna() # it didn't change the dfs

推荐答案

这不是一次简单的合并.您希望合并df2、df3、df4,然后与df1合并:

df1.merge(pd.concat([df2,df3,df4]).drop_duplicates(), on='source')

输出:

   source target temp
0       A      1    a
1       A      1    b
2       A      2    a
3       A      2    b
4       A      3    a
5       A      3    b
6       B      4    c
7       B      4    d
8       B      5    c
9       B      5    d
10      C      6    e
11      C      7    e

Python相关问答推荐

单击cookie按钮,但结果不一致

当变量也可以是无或真时,判断是否为假

从Python调用GMP C函数时的分段错误和内存泄漏

Python如何让代码在一个程序中工作而不在其他程序中工作

将嵌套列表的字典转换为数据框中的行

模型序列化器中未调用现场验证器

不允许AMBIMA API请求方法

通过仅导入pandas来在for循环中进行多情节

如何调整spaCy token 化器,以便在德国模型中将数字拆分为行末端的点

使用SciPy进行曲线匹配未能给出正确的匹配

抓取rotowire MLB球员新闻并使用Python形成表格

如何避免Chained when/then分配中的Mypy不兼容类型警告?

将数据框架与导入的Excel文件一起使用

利用Selenium和Beautiful Soup实现Web抓取JavaScript表

海上重叠直方图

在单个对象中解析多个Python数据帧

基于另一列的GROUP-BY聚合将列添加到Polars LazyFrame

干燥化与列姆化的比较

如何从pandas DataFrame中获取. groupby()和. agg()之后的子列?

为什么t sns.barplot图例不显示所有值?'