ZakS
ZakS

Reputation: 1131

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.

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=

A Z

B Y

C X

D U

DF2 =

Z 2000

Y 2300

X 1300

U 900

One possible solution might be:

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

But what would I use to reference the column in DF2?

Also, would setting the DF's up as a series make any difference?

Upvotes: 1

Views: 1734

Answers (1)

jezrael
jezrael

Reputation: 862701

If working with 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

Upvotes: 2

Related Questions