1

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 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.