1

I have 2 DataFrames:

df1 
    names            1       2       3       4       5
0   abcdefg       43.9  32.875  34.025  51.625   74.025
1   efgh          42.775     23.975 40.675  41.375        2.695
2   ijk            2.29 23.6530000  68.175  68.875  2.29
3   lmn            23.504   26.503  36.425  36.65   10.742
4   opq             6.98    7.515   6.98    7.515   

df 2
         Numbers
54174    42.775
54175    43.900000
54176    35.550000
54177    35.550000
54178    43.900000

Is there anyway to check if the df2.Numbers is at all in df1, and if so extract the relevant df1.names into a separate dataframe? Expected output:

         Numbers     Revised
54174    42.775       efgh
54175    43.900000    abcdefg
54176    35.550000    NA
54177    35.550000    NA
54178    43.900000    abcdefg

Any help will be greatly appreciated.

3
  • And what is the expected output? Commented Apr 29, 2020 at 18:01
  • 2
    Be careful when comparing float values, there might be small non-visible representation errors. Commented Apr 29, 2020 at 18:02
  • Hi, updated now @yatu Commented Apr 29, 2020 at 18:09

1 Answer 1

1

IIUC, using set_index and stack then merge onto df2.

You should also take Quang's advice into consideration.

s = df1.set_index('names').stack().reset_index(0).rename({0 : 'Numbers'},axis=1)


df3 = pd.merge(df2,s,on='Numbers',how='left')

print(df3)

     idx  Numbers    names
0  54174   42.775     efgh
1  54175   43.900  abcdefg
2  54176   35.550      NaN
3  54177   35.550      NaN
4  54178   43.900  abcdefg
Sign up to request clarification or add additional context in comments.

3 Comments

No problem @Nic don't forget to accept this answer if it answered your question
Hi, I would if I could but I do not have enough reputation points yet. If I wanted to append df3.names to another dataframe, how would I do that?
@Nic that's an upvote, green tick is below that have a read of this For your question you can use either .join or pd.concat depends on your use-case I'd ask a new question or see if there is something that matches your use case

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.