在Python中使用两个数据框进行简单查找

时间:2019-02-08 18:28:25

标签: python pandas dataframe

我正在与熊猫一起工作,我的目的是将数据从一张桌子带到另一张桌子。假设我有两个名为df1和df2的数据框:

df1就是这样:

<algorithm>

df2就是这样:

Name    Age    Height
Marcus  18     170
Dan     21     172
Phill   30     165
Paty    24     160
Linda   25     158

我想找到一种方法来选择df1中的年龄并将其带到df2中,从而得到一个这样的表:

Name    Score1    Score2     Score3
Dan          A         C          C
Paty         B         A          B
Marcus       C         D          B
Zoe          A         A          B

在Excel中,我们在df2至df1中使用VLOOKUP函数。但是我在Python中找不到类似的东西。

1 个答案:

答案 0 :(得分:2)

您可以使用地图或合并,地图会更快

选项1:使用地图

passenger-config was invoked through the following Ruby interpreter:
  Command: /home/work/.rbenv/versions/2.5.1/bin/ruby
  Version: ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
  To use in Apache: PassengerRuby /home/work/.rbenv/versions/2.5.1/bin/ruby
  To use in Nginx : passenger_ruby /home/work/.rbenv/versions/2.5.1/bin/ruby
  To use with Standalone: /home/work/.rbenv/versions/2.5.1/bin/ruby /usr/bin/passenger start

The following Ruby interpreter was found first in $PATH:
  Command: /home/work/.rbenv/versions/2.5.1/bin/ruby
  Version: ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
  To use in Apache: PassengerRuby /home/work/.rbenv/versions/2.5.1/bin/ruby
  To use in Nginx : passenger_ruby /home/work/.rbenv/versions/2.5.1/bin/ruby
  To use with Standalone: /home/work/.rbenv/versions/2.5.1/bin/ruby /usr/bin/passenger start

选项2:使用合并

df2['Age'] = df2['Name'].map(df1.set_index('Name')['Age'])

无论哪种方式

df2.merge(df1[['Name', 'Age']], 'left')