通过检查之前的行用值填充空槽

Fill empty slot with value by checking the line before

我有一个这样的 DataFrame:

day  value  
1 HSE  
2 HSE   
3  
4  
5  
6 LSE  
7 LSE  
8  
9  
10  

现在,我想通过检查之前的值来用值填充空槽。所以,我想将 3、4、5 设置为 "fromHSE" 和 8、9、10 "fromLSE"。

我这样试过:

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"

但是我得到了错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

希望你能帮帮我。

你可以先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