0

Is is possible to fetch column containing values corresponding to an id column? Example:-

df1

|   ID     | Value   | Salary |
|:---------:--------:|:------:|   
|    1     |   amr   | 34     |
|    1     |   ith   | 67     |
|    2     |   oaa   | 45     |
|    1     |   eea   | 78     |
|    3     |   anik  | 56     |
|    4     |   mmkk  | 99     |
|    5     |   sh_s  | 98     |
|    5     |   ahhi  | 77     |
df2

|   ID     | Dept    |
|:---------:--------:|
|    1     |   hrs   |
|    1     |   cse   |
|    2     |   me    |
|    1     |   ece   |
|    3     |   eee   |

Expected Output
|   ID     | Dept    | Value     |
|:---------:--------:|----------:|
|    1     |   hrs   | amr       |
|    1     |   cse   | ith       |
|    2     |   me    | oaa       |
|    1     |   ece   | eea       |
|    3     |   eee   | anik      |

I want to fetch each values in the 'Value' column corresponding to values in df2's ID column. And create column containing 'Values' in df2. The number of rows in the two dfs are not the same. I have tried

this

Not worked

Ammu07
  • 25
  • 5

3 Answers3

2

IIUC , you can try df.merge after assigning a helper column by doing groupby+cumcount on ID:

out = (df1.assign(k=df1.groupby("ID").cumcount())
       .merge(df2.assign(k=df2.groupby("ID").cumcount()),on=['ID','k'])
       .drop("k",1))

print(out)

   ID Value Dept
0   1   Amr  hrs
1   1   ith  cse
2   2   oaa   me
3   1   eea  ece
4   3  anik  eee
anky
  • 74,114
  • 11
  • 41
  • 70
0

is this what you want to do?

df1.merge(df2, how='inner',on ='ID')
eshirvana
  • 23,227
  • 3
  • 22
  • 38
0

Since you have duplicated IDs in both dfs, but these are ordered, try:

df1 = df1.drop(columns="ID")
df3 = df2.merge(df1, left_index=True, right_index=True)
Laurent
  • 12,287
  • 7
  • 21
  • 37