0

I have two dataframes

df1:

ID  col2 col3 type
123  1.   2.   T
132  3.   1.   N
111  2.   1.   U

df2

ID   A    B   
123  0.   3.   
111  2.   3.   
132  1.   2.   

df2 contains different information about the same ID but in different order

I wanted to create a new column in df2 named (type) and match the type column in df1. If it's the same ID to the one in df1, it should copy the same type (T, N or U) from df1. In another word, I need it to look like

ID   A    B  type
123  0.   3.   T
111  2.   3.   U
132  1.   2.   N

I tried

df2['Type'] = df2[df2.ID.isin(df1.ID)]
Sam
  • 309
  • 2
  • 10
  • This is something like `pd.merge(df1, df2, on='ID')[['ID', 'A', 'B', 'type']]`. – Ami Tavory Apr 28 '18 at 17:08
  • I did try pd.merge(df1, df2, on='ID')[['ID', 'A', 'B', 'type']], it didn't work. I also don't want to merge the data or join them. I only need to add one column from the df2. Both data are huge and have more than a hundred column in each. I can't specify 'A', 'B' in the code because they are many of them. Do you have any other suggestions, please? – Sam Apr 28 '18 at 17:30
  • I just tried it by me and it *does* seem to work. Also, why does it matter how many columns the DataFrames have? Use `pd.merge(df1[relevant_columns1]), df2[relevant_columns2], ...)`, no? Finally my vote to close reflects your question as you wrote it. If you tried something and it didn't work, or it works and it seems the performance is too high, perhaps explain so in a new question? – Ami Tavory Apr 28 '18 at 17:37

0 Answers0