基于值的 Pandas 查找 [英] Pandas lookup based on value

查看:26
本文介绍了基于值的 Pandas 查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据帧:

Date    best    a    b    c    d
1990    a       5    4    7    2
1991    c       10   1    2    0
1992    d       2    1    4    12
1993    a       5    8    11   6

我想制作一个如下的数据框:

I would like to make a dataframe as follows:

Date    best    value   
1990    a       5
1991    c       2
1992    d       12
1993    a       5

所以我希望通过使用列名来查找基于另一个行值的值.例如,第二个 df 中的 1990 值应该从第一个 df 中查找a",第二行应该从第一个 df 中查找c"(=2).

So I am looking to find a value based on another row value by using column names. For instance, the value for 1990 in the second df should lookup "a" from the first df and the second row should lookup "c" (=2) from the first df.

有什么想法吗?

推荐答案

有一个内置的 lookup 函数可以处理这种情况(按行/列查找).我不知道它是如何优化的,但可能比应用解决方案更快.

There is a built in lookup function that can handle this type of situation (looks up by row/column). I don't know how optimized it is, but may be faster than the apply solution.

In [9]: df['value'] = df.lookup(df.index, df['best'])

In [10]: df
Out[10]: 
   Date best   a  b   c   d  value
0  1990    a   5  4   7   2      5
1  1991    c  10  1   2   0      2
2  1992    d   2  1   4  12     12
3  1993    a   5  8  11   6      5

这篇关于基于值的 Pandas 查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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