重复一列中的值以填充该列中的空单元格

repeats the value in one column to fill the empty cells in that column

我有一个这样的数据框:

A  B
a
a  
a  b
a
a  
a  B

我想用“B”中的现有值填充“B”列中的空单元格。这样最终结果将是:

A  B
a  b
a  b
a  b
a  B
a  B
a  B

我已经尝试过在 pandas 系列中获取“B”列并删除空单元格的想法。

tmp=df['B']
tmp.dropna(axis=0, inplace=True, how=None)

然后我想将tmp系列中的每个项目重复三次,然后将其放回原始数据框。但是失败了。

我的解决方案可能不是很好。任何建议都会有所帮助!

提前致谢。

需要将空字符串替换为replace,然后使用bfill,向后填充:

>>> df.replace('', np.nan).bfill()
   A  B
0  a  b
1  a  b
2  a  b
3  a  B
4  a  B
5  a  B
>>> 

我找不到重复项,因此仅当空值在某些列中缺少值时才使用 bfill

df["B"] = df["B"].replace('', np.nan).bfill()