合并两个具有不同索引的数据框,同时使用单行代码保留主数据框的索引 [英] Merge two dataframes with different indices while preserving the main dataframe's index using a one-line code

查看:70
本文介绍了合并两个具有不同索引的数据框,同时使用单行代码保留主数据框的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框;第一个(df1)是:

I have two dataframes; the first one(df1) is:

df1 = pd.DataFrame({'col1': [0,1], 'col2': [0,1]})
df1 = df1.rename(index = {k:v for k,v in zip([0,1],['zero','one'])})
print(df1)
      col1  col2
zero    0   0
one     1   1

第二个(df2)是:

df2 = pd.DataFrame({k:v for k,v in zip(['col'+str(i) for i in range(3,10)],
                            [[2,3]]*7)
                            })
print(df2)
   col3  col4  col5  col6  col7  col8  col9
0     2     2     2     2     2     2     2
1     3     3     3     3     3     3     3

最终产品(df3)应该看起来像这样:

the final product(df3) should look exactly like:

      col1  col2  col3  col4  col5  col6  col7  col8  col9
zero     0     0     2     2     2     2     2     2     2
one      1     1     3     3     3     3     3     3     3

这是我的操作方式,这对我的口味有点反常:

This is the way I do it, which is a bit unpythonic to my taste:

df3 = df1.reset_index(drop = True)
df3 = df3.join(df2.reset_index(drop = True))
df3 = df3.rename(index = {k:v for k,v in zip(df3.index,df1.index)})
print(df3)

是否有任何一行代码可以完成这项工作?谢谢你们

Is there any one-line code that can do the job? Thank you guys

推荐答案

您可以通过或者:

df = pd.concat([df1, df2.set_index(df1.index)], axis=1)
print (df)
      col1  col2  col3  col4  col5  col6  col7  col8  col9
zero     0     0     2     2     2     2     2     2     2
one      1     1     3     3     3     3     3     3     3

如果具有与两个DataFrames传递嵌套列表相同的列表长度,以区分您想要传递的列表,而不是列名列表( df2.set_index(L) df2.set_index(['a','b'])):

If have list same length like both DataFrames pass nested list for distinguish you want pass list, not list of column names (df2.set_index(L) or df2.set_index(['a','b'])):

L = ['a','b']
df = pd.concat([df1.set_index([L]), df2.set_index([L])], axis=1)
print (df)
   col1  col2  col3  col4  col5  col6  col7  col8  col9
a     0     0     2     2     2     2     2     2     2
b     1     1     3     3     3     3     3     3     3

这篇关于合并两个具有不同索引的数据框,同时使用单行代码保留主数据框的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆