How to get the index of row itself

Viewed 39

Here is a DF for example

index  A     B     C      D(new Column)
   0   1     2     3      ?
   1   11    22    33     ?
   2   111   222   333    ?

Now, i want to apply a new(D) column to this DF depends on A column

if A column=1 apply B column's value(NOT LIST JUST VALUE) as new col if A column=11 apply C column's value(NOT LIST JUST VALUE) as new col....

Firstly, I tried but it return me a LIST(Series) not the value; So i tried to locate it by index, but i need to get the index of each row, and use it to locate the value(may be I wrong)

So, what is the easiest way to do it?

1 Answers

IIUC, you need numpy.select:

df['D'] = np.select([df['A'].eq(1), df['A'].eq(11)], # list of conditions
                    [df['B'], df['C']],              # list of replacements
                    -1)                              # fallback value

output:

index    A    B    C   D
    0    1    2    3   2
    1   11   22   33  33
    2  111  222  333  -1

Alternative with a mapping dictionary and lookup indexing:

mapper = {1: 'B', 11: 'C'}

import numpy as np
idx, cols = pd.factorize(df['A'].map(mapper).fillna('missing'))
df['D'] = df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)), idx]

output:

   index    A    B    C     D
0      0    1    2    3   2.0
1      1   11   22   33  33.0
2      2  111  222  333   NaN
Related