Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two columns into one in pandas dataframe [duplicate]

Tags:

python

pandas

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.

like image 517
Ingyun Son Avatar asked Jan 31 '26 23:01

Ingyun Son


1 Answers

Perhaps you can use:

df['C'] = df[['A', 'B']].max(axis=1)
like image 127
KenHBS Avatar answered Feb 03 '26 11:02

KenHBS