python pandas右填充值

时间:2016-12-29 19:31:12

标签: python pandas

我正在尝试复制一个“正确填充”类似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"]) \
})

1 个答案:

答案 0 :(得分:2)

在第2行创建一个布尔掩码。

  • 测试它是否为空(Nonenp.nan
  • 测试它是否等于空字符串''

分配

  • 使用loc分配
  • replace默认情况下向前填充空值。
cond = have.loc[1].isnull() | have.loc[1].ne('')
have.loc[0, cond] = have.loc[0, cond].replace('', None)
have

enter image description here

如果空白''是空格' ',我们可以使用strip

cond = have.loc[1].isnull() | have.loc[1].ne('')
have.loc[0, cond] = have.loc[0, cond].str.strip().replace('', None)
have