0

I have a dataframe that looks like this:

idx  group  valA  valB 
-----------------------
0    A      10    5
1    A      22    7
2    B      9     0
3    B      6     1

I want to add a new column 'val' that takes 'valA' if group = 'A' and takes 'valB' if group = 'B'.

idx  group  valA  valB  val
---------------------------
0    A      10    5     10
1    A      22    7     22
2    B      9     0     0 
3    B      6     1     1

How can I do this?

mrstinky
  • 3
  • 2
  • 1
    there are myriads of available answers to your question, here's one: https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column – sophocles Apr 16 '21 at 15:00
  • I disagree with my question being a duplicate. In the linked question, the output depends only on the value of the conditional column. In my question, the output is conditioned on one column, but the value of the output depends on other columns. – mrstinky Apr 18 '21 at 16:28

1 Answers1

1

This should do the trick

df['val'] = df.apply(lambda x: x['valA'] if x['group'] == 'A' else x['valB'], axis=1)
89f3a1c
  • 1,430
  • 1
  • 14
  • 24
  • Thanks! How might I modify it if there are more than two groups? (without doing nested if statements) – mrstinky Apr 18 '21 at 16:34