Reputation: 168
I have the following information in a DataFrame in Python:
## 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
and I need to generate a new column depending on the value that contains the colum column, in the following way:
## 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
I do not know if I am clear in my request, I thank who can help me.
Upvotes: 0
Views: 112
Reputation: 862671
Use 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
Upvotes: 0
Reputation: 164673
Using pd.DataFrame.lookup
and mapping integers to your column labels:
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
Upvotes: 1