Fetch row data from known index in pandas

Viewed 72

df1:

   col1   col2
0   a     5
1   b     2
2   c     1
 

df2:

   col1
0   qa0
1   qa1
2   qa2
3   qa3
4   qa4
5   qa5

final output:

   col1   col2  col3
0   a     5     qa5
1   b     2     qa2
2   c     1     qa1

Basically , in df1, I have index stored for another df data. I have to fetch data from df2 and append it in df1.
I don't know how to fetch data via index number.

2 Answers

Use Series.map by another Series:

df1['col3'] = df1['col2'].map(df2['col1'])

Or use DataFrame.join with rename column:

df1 = df1.join(df2.rename(columns={'col1':'col3'})['col3'], on='col2')

print (df1)
  col1  col2 col3
0    a     5  qa5
1    b     2  qa2
2    c     1  qa1

You can use iloc to get data and then to_numpy for values

df1["col3"] = df2.iloc[df1.col2].to_numpy()

df1
  col1  col2 col3
0    a     5  qa5
1    b     2  qa2
2    c     1  qa1
Related