我正在尝试复制一个“正确填充”类似excel的函数,该函数将值填充到下一个值不为null / nan / empty。只有当紧接的后续行中的值不为空或“nan”时,才会执行此“右填”练习。 我有以下pandas数据帧数据集。我当前的输入表是“have”。我的输出表是“想要”。
import pandas as pd
have = pd.DataFrame({ \
"0": pd.Series(["abc","1","something here"]) \
,"1": pd.Series(["","2","something here"]) \
,"2": pd.Series(["","3","something here"]) \
,"3": pd.Series(["something","1","something here"]) \
,"4": pd.Series(["","2","something here"]) \
,"5": pd.Series(["","","something here"]) \
,"6": pd.Series(["","","something here"]) \
,"7": pd.Series(["cdf","5","something here"]) \
,"8": pd.Series(["","6","something here"]) \
,"9": pd.Series(["xyz","1","something here"]) \
})
want = pd.DataFrame({ \
"0": pd.Series(["abc","1","something here"]) \
,"1": pd.Series(["abc","2","something here"]) \
,"2": pd.Series(["abc","3","something here"]) \
,"3": pd.Series(["something","1","something here"]) \
,"4": pd.Series(["something","2","something here"]) \
,"5": pd.Series(["","","something here"]) \
,"6": pd.Series(["","","something here"]) \
,"7": pd.Series(["cdf","5","something here"]) \
,"8": pd.Series(["cdf","6","something here"]) \
,"9": pd.Series(["xyz","1","something here"]) \
})
答案 0 :(得分:2)
在第2行创建一个布尔掩码。
None
或np.nan
)''
分配
loc
分配replace
默认情况下向前填充空值。cond = have.loc[1].isnull() | have.loc[1].ne('')
have.loc[0, cond] = have.loc[0, cond].replace('', None)
have
如果空白''
是空格' '
,我们可以使用strip
cond = have.loc[1].isnull() | have.loc[1].ne('')
have.loc[0, cond] = have.loc[0, cond].str.strip().replace('', None)
have