I have a DataFrame like this:
day value
1 HSE
2 HSE
3
4
5
6 LSE
7 LSE
8
9
10
Now, I want to fill the empty slots with values by checking the value before. So, I want 3,4,5 set to "fromHSE"and 8,9,10 "fromLSE".
I tried it like this:
e = "HSE"
for line in df:
if df['value'] == "":
if e == "HSE":
df['value'] = "fromHSE"
elif e == "LSE":
df['value'] = "fromLSE"
elif df['value'] == "HSE":
e = "HSE"
elif df['value'] == "LSE":
e = "LSE"
But then i get the error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I hope you can help me.
You can first replace
empty string to NaN
, create mask with isnull
and create new Series
with ffill
. Last add string from
with mask
:
df.value.replace('',np.NaN, inplace=True)
mask = df.value.isnull()
new = df.value.ffill()
print (new.mask(mask, 'from' + new))
0 HSE
1 HSE
2 fromHSE
3 fromHSE
4 fromHSE
5 LSE
6 LSE
7 fromLSE
8 fromLSE
9 fromLSE
Name: value, dtype: object