ursteiner
ursteiner

Reputation: 149

Python Pandas: iloc with flexible column position

I have the following df

w1 w2 w3 w4 w5 w6 w7 w8 w9 B
2  5  8  4  2  3  1  2  8  3
5  1  4  3  8  3  1  2  3  5

I want to add column C. The value for C depends on the value in B and the corresponding column position (the "B-th" column). Result should look like this:

w1 w2 w3 w4 w5 w6 w7 w8 w9 B C
2  5  8  4  2  3  1  2  8  3 4
5  1  4  3  8  3  1  2  3  5 3

Upvotes: 1

Views: 77

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61910

Do:

df['C'] = df.values[np.arange(len(df)), df.B.values]
print(df)

Output

   w1  w2  w3  w4  w5  w6  w7  w8  w9  B  C
0   2   5   8   4   2   3   1   2   8  3  4
1   5   1   4   3   8   3   1   2   3  5  3

Upvotes: 3

jezrael
jezrael

Reputation: 862511

If want match only w columns add DataFrame.filter first, convert to numpy array and use indexing:

df['C'] = df.filter(like='w').values[np.arange(len(df)), df['B'].values]
print (df)
   w1  w2  w3  w4  w5  w6  w7  w8  w9  B  C
0   2   5   8   4   2   3   1   2   8  3  4
1   5   1   4   3   8   3   1   2   3  5  3

Or if want match by numbers after w use DataFrame.lookup, but is necessary change B values with add 1, convert to strings and prepend w:

df['C'] = df.lookup(df.index, df['B'].add(1).astype(str).radd('w'))
print (df)
   w1  w2  w3  w4  w5  w6  w7  w8  w9  B  C
0   2   5   8   4   2   3   1   2   8  3  4
1   5   1   4   3   8   3   1   2   3  5  3

Upvotes: 1

Related Questions