加入两个Pandas Dataframe

时间:2017-11-06 18:49:05

标签: python pandas dataframe

请给出两个数据帧:

DF1:

Building file 'C:\Users\philip\git\foo\Installer\Debug\Installer.msi'...
Building file 'C:\Users\philip\git\foo\Installer\Debug\Installer.msi'...
ERROR: File 'foo.Core.dll' targeting 'AMD64' is not compatible with the project's target platform 'x86'
ERROR: File 'foo.Core.dll' targeting 'AMD64' is not compatible with the project's target platform 'x86'
WARNING: File 'foo.Core.dll' targeting 'x64' is not compatible with the project's target platform 'x86'
WARNING: File 'foo.Core.dll' targeting 'x64' is not compatible with the project's target platform 'x86'

DF2:

A       B                    
a1      b1          
a2      b2          
a3      b3    

我想做以下DF1 + DF2,产生以下内容:

C1      C2   C3  
 0      0     1  

我不清楚我应该如何使用Merge,Join或concatenate。请帮助,非常感谢。

3 个答案:

答案 0 :(得分:5)

让我们使用一些解包和转发填充nas:

DF1.assign(**DF2).ffill()

或者,让我们创建一个虚拟键来进行笛卡尔连接,然后删除虚拟键。

DF1.assign(key=1).merge(DF2.assign(key=1), on='key').drop('key',axis=1)

输出:

    A   B   C1   C2   C3
0  a1  b1  0.0  0.0  1.0
1  a2  b2  0.0  0.0  1.0
2  a3  b3  0.0  0.0  1.0

答案 1 :(得分:4)

pd.concat + ffill

pd.concat([df1,df2],1).ffill()
Out[1188]: 
    A   B   C1   C2   C3
0  a1  b1  0.0  0.0  1.0
1  a2  b2  0.0  0.0  1.0
2  a3  b3  0.0  0.0  1.0

答案 2 :(得分:1)

如果df2只包含一行,我们可以这样做:

In [30]: df1.assign(**df2.iloc[0].to_dict())
Out[30]:
    A   B  C1  C2  C3
0  a1  b1   0   0   1
1  a2  b2   0   0   1
2  a3  b3   0   0   1