3

Want to merge two columns into one column in certain condition.
My data is like below

idx    A    B
0      0.5  1.2
1      1.1  0.7
2      0.1  0.3
3      2.0  0.9

With Pandas dataframe, I want to make column C in the condition.

  1. if column A > column B, column C gets the value of column A.
  2. if column B > column A, column C gets the value of column B.

In result, I expect like this.

idx    A    B    C
0      0.5  1.2  1.2(B data)
1      1.1  0.7  1.1(A data)
2      0.1  0.3  0.3(B data)
3      2.0  0.9  2.0(A data)

I tried .loc function like:
df['C'] = df.loc[df['A'] > df['B'], 'A']

But I cannot replace or modify Nan value in column C.

Thank you.

Ingyun Son
  • 33
  • 1
  • 4

2 Answers2

6

Perhaps you can use:

df['C'] = df[['A', 'B']].max(axis=1)
KenHBS
  • 6,756
  • 6
  • 37
  • 52
2
import numpy as np
df['C'] = np.where(df['A']>df['B'], df['A'], df['B'])
ycx
  • 3,155
  • 3
  • 14
  • 26