如何使用 pandas 中其他数据帧的值提取一个数据帧的值? [英] How to extract values of one dataframe with values of other dataframe in pandas?

查看:50
本文介绍了如何使用 pandas 中其他数据帧的值提取一个数据帧的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您创建了下一个 python 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   

如何使用下一个值创建框架 df_ids_to_values:

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

换句话说,我想用 df1 中的相应值替换 df2 的 id.我曾尝试通过执行 for 循环来执行此操作,但速度非常慢,而且我希望 Pandas 中有一个函数可以让我非常有效地执行此操作.

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.

感谢您的帮助...

推荐答案

从在 df1 上设置索引开始

Start by setting an index on df1

df1 = df1.set_index('ID')

然后加入两列

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'})

结果:

> 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]

(您可以使用 df[['value_a','value_b']] 获得预期的输出)

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

这篇关于如何使用 pandas 中其他数据帧的值提取一个数据帧的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆