[英]How to join two dataframes using index in pandas?
I have the following dataframe df1 我有以下数据框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
and another dataframe df2 和另一个数据框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
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. 通过联接两个数据框,我希望通过从df2中删除列0和1,使df2中的索引成为联接数据框中的id列。 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
I tried 我试过了
df3 = pd.concat([df2, df1], ignore_index=True)
Output of the joined dataframe with pd.concat 使用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
If length of both DataFrames are same only assign one index to new column: 如果两个DataFrame的长度相同,则仅将一个索引分配给新列:
df1['id'] = df2.index
print (df1)
Or: 要么:
df1 = df1.assign(id = df2.index)
print (df1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.