Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Columns in Pandas Dataframe

I have a data frame with three columns

Col1    Col2    Col3  Col4  Col 5
---------------------------------
Apple   None    192    abc   None
Banana  Banana  89     None  bcd
None    Cake    892    aaa   aaa

I wanna combine two columns i.e. Col1 and Col2 and col1 and col5 If one column in none and other has value then use the value if both have values then use that value.
Is it possible to merge columns like this.

Col1    Col3     Col4
----------------------
Apple   192      abc
Banana  89       bcd
Cake    892      aaa
like image 267
Constantine1991 Avatar asked Sep 15 '25 15:09

Constantine1991


1 Answers

Use (if None is a string first replace with np.nan : df=df.replace('None',np.nan)):

df_new=df.ffill().bfill()[['Col1','Col3']]
print(df_new)

     Col1  Col3
0   Apple   192
1  Banana    89
2  Banana   892

Based on the update:

df.bfill(axis=1)[['Col1','Col3','Col4']]

     Col1 Col3 Col4
0   Apple  192  abc
1  Banana   89  bcd
2    Cake  892  aaa
like image 90
anky Avatar answered Sep 17 '25 05:09

anky