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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With