and*_*ler 9 python concat pandas
我有两个数据帧,我想按列连接(轴= 1)与内连接.其中一个数据帧有一些重复的索引,但行不是重复的,我不想丢失那些数据:
df1 = pd.DataFrame([{'a':1,'b':2},{'a':1,'b':3},{'a':2,'b':4}],
columns = ['a','b']).set_index('a')
df2 = pd.DataFrame([{'a':1,'c':5},{'a':2,'c':6}],columns = ['a','c']).set_index('a')
>>> df1
b
a
1 2
1 3
2 4
8 9
>>> df2
c
a
1 5
2 6
Run Code Online (Sandbox Code Playgroud)
默认concat
行为是使用NaN填充缺失值:
>>> pd.concat([df1,df2])
b c
a
1 2 NaN
1 3 NaN
2 4 NaN
1 NaN 5
2 NaN 6
Run Code Online (Sandbox Code Playgroud)
我想保留df1中的重复索引并用df2中的重复值填充它们,但是在pandas 0.13.1中,列上的内连接会产生错误.在更新版本的pandas concat做我想要的:
>>> pd.concat([df1, df2], axis=1, join='inner')
b c
a
1 2 5
1 3 5
2 4 6
Run Code Online (Sandbox Code Playgroud)
达到我想要的结果的最佳方法是什么?有没有groupby解决方案?或者也许我根本不应该使用concat
?
您可以执行合并并设置参数以使用lhs和rhs中的索引:
In [4]:
df1.merge(df2, left_index=True, right_index=True)
Out[4]:
b c
a
1 2 5
1 3 5
2 4 6
[3 rows x 2 columns]
Run Code Online (Sandbox Code Playgroud)
Concat应该工作,它对我有用:
In [5]:
pd.concat([df1,df2], join='inner', axis=1)
Out[5]:
b c
a
1 2 5
1 3 5
2 4 6
[3 rows x 2 columns]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7442 次 |
最近记录: |