0

I have two dataframes:

df1=     subj_id overall_id   A B C 
             1       29       . . .
             2       30       . . .
             3       31       . . .

df2 = id D E F 
      29 1 2 3
      29 4 5 6
      29 7 8 9
      30 1 2 3
      30 4 5 6
      31 1 2 3

I want to join them and create:

df = subj_id id D E F 
         1   29 1 2 3
         1   29 4 5 6
         1   29 7 8 9
         2   30 1 2 3
         2   30 4 5 6
         3   31 1 2 3

What is the best way to do so?

Cranjis
  • 1,590
  • 8
  • 31
  • 64

1 Answers1

0

You can do with either merge or map. For example, with map:

df = df2.copy()
df['subj_id'] = df['id'].map(df1.set_index('overall_id')['subj_id'])

Output:

   id  D  E  F  subj_id
0  29  1  2  3        1
1  29  4  5  6        1
2  29  7  8  9        1
3  30  1  2  3        2
4  30  4  5  6        2
5  31  1  2  3        3
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74