Python 根据数据库中其他列中的值动态访问列

Python 根据数据库中其他列中的值动态访问列,python,pandas,Python,Pandas,假设我有以下数据框: idx | X1 | X2 | X3 | Z ----------------------- 1 | 5 | 8 | 4 | 1 2 | 3 | 2 | 6 | 2 3 | 6 | 3 | 2 | 1 对于每一行,我现在想要访问由Z中的值指示的列,即我想要的结果是: idx | X -------- 1 | 5 # from X1 2 | 2 # from X2 3 | 6 # from X1 如何在

假设我有以下数据框:

idx | X1 | X2 | X3 |  Z
-----------------------
  1 |  5 |  8 |  4 |  1
  2 |  3 |  2 |  6 |  2
  3 |  6 |  3 |  2 |  1
对于每一行,我现在想要访问由
Z
中的值指示的列,即我想要的结果是:

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

如何在熊猫中实现这一点?

使用
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

使用
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

注意:按照零,当标签顺序不正确时,下面的标签不工作

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

注意:按照零,当标签顺序不正确时,下面的标签不工作

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

X%s
lean a new thing~:)
X%s
lean a new thing~:)如果标签未排序,这可能不起作用我怀疑?如果标签未排序,这可能不起作用我怀疑?