Amit Kumar
Amit Kumar

Reputation: 633

fill missing value Pandas

I want to fill the column of a dataframe as shown in example.

df=pd.DataFrame({'A':['a','','','a','','b','b','','b','']})

current df

i want to replace the empty values between two rows having same value: output:

enter image description here

Can we do it without iterrows?

Upvotes: 1

Views: 43

Answers (1)

jezrael
jezrael

Reputation: 862481

First replace empty strings to missing values and then compare forward and backfilling values and use only matched values:

df=pd.DataFrame({'A':['a','','','a','','b','b','','b','']})

s = df.A.replace('', np.nan)

s1 = s.ffill()
s2 = s.bfill()

df.A = s1.where(s1.eq(s2), '')
print (df)
   A
0  a
1  a
2  a
3  a
4   
5  b
6  b
7  b
8  b
9   

Upvotes: 3

Related Questions