[英]Change row value dynamically in python
我在Python的DataFrame中有以下信息:
## x1 x2 x3 x4 x5 colum
##0 206 214 021 122 554 2
##1 226 234 123 456 789 4
##2 245 253 558 855 123 5
##3 265 272 000 111 222 4
##4 283 291 214 589 996 1
並且我需要按照包含colum列的值生成新列,方法如下:
## x1 x2 x3 x4 x5 colum newColum
##0 206 214 021 122 554 2 214
##1 226 234 123 456 789 4 456
##2 245 253 558 855 123 5 123
##3 265 272 000 111 222 4 111
##4 283 291 214 589 996 1 283
我不知道我的要求是否明確,我感謝誰能幫助我。
使用pd.DataFrame.lookup
並將整數映射到列標簽:
df['new'] = df.lookup(df.index, 'x' + df['colum'].astype(str))
print(df)
x1 x2 x3 x4 x5 colum new
0 206 214 21 122 554 2 214
1 226 234 123 456 789 4 456
2 245 253 558 855 123 5 123
3 265 272 0 111 222 4 111
4 283 291 214 589 996 1 283
使用numpy indexing
:
df['new'] = df.values[np.arange(len(df)), df['colum'] - 1]
print (df)
x1 x2 x3 x4 x5 colum new
0 206 214 21 122 554 2 214
1 226 234 123 456 789 4 456
2 245 253 558 855 123 5 123
3 265 272 0 111 222 4 111
4 283 291 214 589 996 1 283
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.