1

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?

6
  • hi @jezrael is this q ok to open pls? Commented Apr 18, 2018 at 8:30
  • If columns have no name it means it is series, so need DF2 = DF2.to_frame('col') Commented Apr 18, 2018 at 8:30
  • I already have DF1 and DF2 as dataframes, can I reference column 1 of DF2 by number, in the "right_on=" argument? Commented Apr 18, 2018 at 8:35
  • No, it is not possible. Commented Apr 18, 2018 at 8:37
  • If DF1 and DF2 were set up originally as dataframes with 1 column, would it have been correct to set them up as Series, in order to enable the merge? Commented Apr 18, 2018 at 8:44

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.