简体   繁体   中英

How to extract values of one dataframe with values of other dataframe in pandas?

Suppose that you create the next python pandas data frames:

In[1]: print df1.to_string()
    ID value
0   1     a
1   2     b
2   3     c
3   4     d


In[2]: print df2.to_string()
      Id_a Id_b
0     1    2        
1     4    2        
2     2    1        
3     3    3        
4     4    4        
5     2    2   

How can I create a frame df_ids_to_values with the next values:

In[2]: print df_ids_to_values.to_string()
      value_a value_b
0     a       b       
1     d       b       
2     b       a       
3     c       c       
4     d       d       
5     b       b

In other words, I would like to replace the id's of df2 with the corresponding values in df1 . I have tried doing this by performing a for loop but it is very slow and I am hopping that there is a function in pandas that allow me to do this operation very efficiently.

Thanks for your help...

Start by setting an index on df1

df1 = df1.set_index('ID')

then join the two columns

df = df2.join(df1, on='Id_a')
df = df.rename(columns = {'value' : 'value_a'})

df = df.join(df1, on='Id_b')
df = df.rename(columns = {'value' : 'value_b'})

result:

> df

  Id_a Id_b value_a value_b
0    1    2       a       b
1    4    2       d       b
2    2    1       b       a
3    3    3       c       c
4    4    4       d       d
5    2    2       b       b

[6 rows x 4 columns]

(and you get to your expected output with df[['value_a','value_b']] )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM