如何根据B列熊猫获取C列对应值?

时间:2019-12-14 11:11:59

标签: pandas

我有这张桌子:

enter image description here

如何根据B列获取C列的对应值?

比方说,现在我有red,如何获得bear的价值?我有dog,如何获得snake? 我想要一个内置的方法,而不是计数。

1 个答案:

答案 0 :(得分:0)

创建以下系列

s = pd.Series(df.c.tolist(), index=df.b)

对于您的情况是:

b
dog      snake
grape     pear
bear       red
dtype: object

如您所见

  • 索引来自 b 列,
  • 值来自 c 列。

然后,当您运行例如s['dog']时,结果为'snake'

您从此系列中检索一个值(包含来自 c 列的值), 用 b 列中的值索引它。

或者,如果您需要更通用的机制,请创建一个 DataFrame b 列获取的索引:

df2 = df.set_index('b')

对于您的数据,结果是:

           a      c
b                  
dog      cat  snake
grape  apple   pear
bear   panda    red

然后您可以使用 loc ,例如致电df2.loc['dog', 'c'] 将获得'snake'(但您也可以传递其他列名)。

相关问题