提取另一列中列出的 pandas 中特定列名称的值 [英] Extract value of a particular column name in pandas as listed in another column

查看:50
本文介绍了提取另一列中列出的 pandas 中特定列名称的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题不太清楚,但这是一个示例.假设我有:

The title wasn't too clear but here's an example. Suppose I have:

person  apple  orange  type
Alice   11     23      apple
Bob     14     20      orange

我想获得此列

person new_col
Alice  11
Bob    20

因此,对于行"Alice",我们获得了苹果"列,对于鲍勃"行,得到了橙色"列.

so we get the column 'apple' for row 'Alice' and 'orange' for row 'Bob'.

我在想迭代,但是那会很慢.有更快的方法可以做到这一点吗?

I'm thinking iterrows, but that would be slow. Are there faster ways to do this?

推荐答案

使用 DataFrame.lookup :

df['new_col'] = df.lookup(df.index, df['type'])
print (df)
  person  apple  orange    type  new_col
0  Alice     11      23   apple       11
1    Bob     14      20  orange       20

如果仅需要2列DataFrame,请使用 分配 DataFrame 构造函数:

If want only 2 column DataFrame use assign or DataFrame contructor:

df1 = df[['person']].assign(new_col=df.lookup(df.index, df['type']))
print (df1)
  person  new_col
0  Alice       11
1    Bob       20


df1 = pd.DataFrame({
        'person':df['person'].values,
        'new_col':df.lookup(df.index, df['type'])},
         columns=['person','new_col'])
print (df1)
  person  new_col
0  Alice       11
1    Bob       20

这篇关于提取另一列中列出的 pandas 中特定列名称的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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