如何在 pandas 中使用索引连接两个数据框? [英] How to join two dataframes using index in pandas?

查看:66
本文介绍了如何在 pandas 中使用索引连接两个数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框df1

I have the following dataframe df1

         value
0     0.164560
1     0.000000
2     0.350000
3     0.700000
    ...
3778  0.350000
3779  0.000000
3780  0.137500
3781  0.253333

和另一个数据框df2

and another dataframe df2

                 0             1
2669  1.744478e-05  2.323815e-05
5417  2.274561e-06  5.808474e-04
6102  2.220705e-06  1.605110e-04
4033  2.018643e-04  2.867235e-05
4877  4.549740e-07  6.233500e-04
             ...
4470  2.761791e-06  6.504309e-05
5071  1.261781e-06  8.010408e-05
3635  4.810822e-05  3.325764e-05
5378  1.133819e-04  4.934986e-05

通过合并两个数据帧,我希望通过从df2中删除列0和1,使df2中的索引成为已连接数据帧中的id列。因此所需的输出如下所示:

by joining the two dataframes I want the index from df2 to be an id column in the joined dataframe by removing columns 0 and 1 from df2. So the desired output looks like

  id         value
2669     0.164560
5417     0.000000
6102     0.350000
4033     0.700000
    ...
4470     0.350000
5071     0.000000
3635     0.137500
5378     0.253333

我尝试了

df3 = pd.concat([df2, df1], ignore_index=True)

带有pd.concat的联接数据帧的输出

Output of the joined dataframe with pd.concat

         value             0             1
0     0.164560           NaN           NaN
1     0.000000           NaN           NaN
2     0.350000           NaN           NaN
3     0.700000           NaN           NaN
          ....
7382       NaN  4.165176e-05  2.615312e-05
7383       NaN  2.357132e-05  5.779454e-05
7384       NaN  1.761602e-06  7.960426e-05
7385       NaN  9.162049e-11  1.627316e-04


推荐答案

如果两个DataFrame的长度相同,则仅将一个索引分配给新列:

If length of both DataFrames are same only assign one index to new column:

df1['id'] = df2.index
print (df1)

或:

df1 = df1.assign(id = df2.index)
print (df1)

这篇关于如何在 pandas 中使用索引连接两个数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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