简体   繁体   English

合并熊猫中的数据框(无列名)

[英]Merge Dataframes in Pandas (without column names)

This question is closely related to Using Merge on a column and Index in Pandas but I have edited in some different points. 这个问题与在列上使用合并和在Pandas中建立索引密切相关,但是我在一些不同的地方进行了编辑。

I have two dataframes, the index of the second one is exactly the same as the first column of the other. 我有两个数据框,第二个数据框的索引与另一个的第一列完全相同。 Both data frame's only have one column (and index) and the column does not have a name. 两个数据框都只有一个列(和索引),并且该列没有名称。

I want to join the two dataframes along the values that match between the column of DF1 and the index of DF2, and maintain the index of DF1. 我想沿着DF1的列和DF2的索引之间匹配的值来连接两个数据框,并保持DF1的索引。

DF1= DF1 =

AZ AZ

BY 通过

CX CX

DU

DF2 = DF2 =

Z 2000 Z 2000

Y 2300 Y 2300

X 1300 X 1300

U 900 U 900

One possible solution might be: 一种可能的解决方案可能是:

merged = pd.merge(DF1, DF2, left_index=True, right_on=??) 合并= pd.merge(DF1,DF2,left_index = True,right_on = ??)

But what would I use to reference the column in DF2? 但是,我将用什么来引用DF2中的列?

Also, would setting the DF's up as a series make any difference? 另外,将DF设置为一系列会有所不同吗?

If working with Series : 如果使用Series

DF1 = pd.Series({'C': 'X', 'A': 'Z', 'B': 'Y', 'D': 'U'})
DF2 = pd.Series({'U': 900, 'X': 1300, 'Y': 2300, 'Z': 2000})
print (DF1)
A    Z
B    Y
C    X
D    U
dtype: object

print (DF2)
U     900
X    1300
Y    2300
Z    2000
dtype: int64

merged = DF1.to_frame('A').join(DF2.rename('B'), on='A')
print (merged)
   A     B
A  Z  2000
B  Y  2300
C  X  1300
D  U   900

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM