数据帧上的向量化查找

数据帧上的向量化查找

本文介绍了在 pandas 数据帧上的向量化查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个DataFrames. . .

I have two DataFrames . . .

df1是一个表,我需要从使用索引的值中提取值,这些索引是从df2中的多个列中检索到的.

df1 is a table I need to pull values from using index, column pairs retrieved from multiple columns in df2.

我看到有一个函数get_value在给定索引和列值时可以完美地工作,但是当尝试向量化此函数以创建新列时,我无法实现...

I see there is a function get_value which works perfectly when given an index and column value, but when trying to vectorize this function to create a new column I am failing...

df1 = pd.DataFrame(np.arange(20).reshape((4, 5)))

df1.columns = list('abcde')

df1.index = ['cat', 'dog', 'fish', 'bird']

        a   b   c   d   e
cat     0   1   2   3   4
dog     5   6   7   8   9
fish    10  11  12  13  14
bird    15  16  17  18  19

df1.get_value('bird, 'c')

17

现在我需要做的是在df2上创建一个全新的列-当基于索引对df1进行索引时,df2中指定的animalletter列中的列对可以有效地向量化上面的pd.get_value函数.

Now what I need to do is to create an entire new column on df2 -- when indexing df1 based on index, column pairs from the animal, letter columns specified in df2 effectively vectorizing the pd.get_value function above.

df2 = pd.DataFrame(np.arange(20).reshape((4, 5)))

df2['animal'] = ['cat', 'dog', 'fish', 'bird']

df2['letter'] = list('abcd')

    0   1   2   3   4   animal  letter
0   0   1   2   3   4   cat     a
1   5   6   7   8   9   dog     b
2   10  11  12  13  14  fish    c
3   15  16  17  18  19  bird    d

导致. . .

    0   1   2   3   4   animal  letter   looked_up
0   0   1   2   3   4   cat     a        0
1   5   6   7   8   9   dog     b        6
2   10  11  12  13  14  fish    c        12
3   15  16  17  18  19  bird    d        18

推荐答案

有一个恰如其分地名为lookup的函数.

There's a function aptly named lookup that does exactly this.

df2['looked_up'] = df1.lookup(df2.animal, df2.letter)

df2

    0   1   2   3   4 animal letter  looked_up
0   0   1   2   3   4    cat      a          0
1   5   6   7   8   9    dog      b          6
2  10  11  12  13  14   fish      c         12
3  15  16  17  18  19   bird      d         18

这篇关于在 pandas 数据帧上的向量化查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:30