1

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.