knub
knub

Reputation: 4032

Access column dynamically based on value in other column in pandas

Let's say I have the following data frame:

idx | X1 | X2 | X3 |  Z
-----------------------
  1 |  5 |  8 |  4 |  1
  2 |  3 |  2 |  6 |  2
  3 |  6 |  3 |  2 |  1

For each row, I now want to access the column indicated by the value in Z, i.e. the result I want is:

idx |  X
--------
  1 |  5   # from X1
  2 |  2   # from X2
  3 |  6   # from X1

How can I achieve this in pandas?

Upvotes: 0

Views: 46

Answers (2)

BENY
BENY

Reputation: 323306

Notice: as per Zero , when the label is not order correctly , below are not work.

df.set_index('idx').apply(lambda x : x[x['Z']-1],axis=1)
Out[959]: 
idx
1    5
2    2
3    6
dtype: int64

Upvotes: 2

Zero
Zero

Reputation: 76927

Using apply

In [3703]: df.apply(lambda x: x['X%s' % x.Z], axis=1)
Out[3703]:
0    5
1    2
2    6
dtype: int64

In [3706]: df[['idx']].assign(X=df.apply(lambda x: x['X%s' % x.Z], axis=1))
Out[3706]:
   idx  X
0    1  5
1    2  2
2    3  6

Upvotes: 2

Related Questions