Extract value of a particular column name in pandas as listed in another column

て烟熏妆下的殇ゞ 提交于 2021-02-16 15:08:22

问题


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

and I want to get this column

person new_col
Alice  11
Bob    20

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?


回答1:


Use 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

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


来源:https://stackoverflow.com/questions/50315700/extract-value-of-a-particular-column-name-in-pandas-as-listed-in-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!