2017-09-25 86 views
0

比方說,我有以下的數據幀:接入列動態地基於價值的其他列大熊貓

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 

我該如何在熊貓中實現這一目標?

回答

2

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

'X%s'瘦了新的東西〜:) – Wen

+0

或者,' 'X {}'。格式(x.Z)' – Zero

2

注意:按零,當標籤不正確的順序,下面是不行的。

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

如果標籤沒有下令我懷疑這可能不工作? – Zero

+0

@零,是的,你說得對〜 – Wen