how to replace a value based on conditions?

Viewed 51

I'm looking for a way to replace '-' with the value in the same row.

This is my original df:

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':['1','-','-','4','5'], 'B': [5, 6, 7, 8, 9]})
df

But then how do I get to the result df:

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':['1','6','7','4','5'], 'B': [5, 6, 7, 8, 9]})
df

1 Answers

You can use replace() for converting - to NaN and bfill() on axis=1:

df=df.replace('-',float('NaN')).bfill(axis=1)
#df.replace('-',float('NaN')).bfill(axis=1).ffill(axis=1)

OR

via replace() and Transpose(T) attribute

df=df.T.replace('-',method='bfill').T

output of df:

    A   B
0   1   5
1   6   6
2   7   7
3   4   8
4   5   9
Related