如何在pandas数据框中查找最近的顶部填充条目来填充缺失条目?

huangapple go评论111阅读模式
英文:

How to fill in missing entries by looking at nearest top filled entry in a pandas dataframe?

问题

我有以下的Dataframe

index col1
1     "a"
2
3     "b"
4
5

从中,我想生成以下的Dataframe

index col1
1     "a"
2     "a"
3     "b"
4     "b"
5     "b"

我尝试复制Dataframe并进行查找,但没有成功。

英文:

I have the following Dataframe:

index col1
1     "a"
2
3     "b"
4
5

And from that I want to produce the following Dataframe:

index col1
1     "a"
2     "a"
3     "b"
4     "b"
5     "b"

I tried duplicating the dataframe and doing lookup, but didn't work.

答案1

得分: 3

使用 Series.replace 来处理缺失值并向前填充顶部的值:

df['col1'] = df['col1'].replace('', np.nan).ffill()
英文:

Use Series.replace for missing values and forward filling top values:

df['col1'] = df['col1'].replace('', np.nan).ffill()

huangapple
  • 本文由 发表于 2023年8月10日 17:40:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定