熊猫的前向填充,但仅在相等的值之间

发布于 2025-01-31 02:15:49 字数 1032 浏览 4 评论 0原文

我有两个数据帧:主和辅助。我正在将辅助辅助与主要的辅助。它导致Nan分几行,我想填充它们,而不是全部。 代码:

df1 = pd.DataFrame({'Main':[00,10,20,30,40,50,60,70,80]})
df1 = 
   Main
0     0
1    10
2    20
3    30
4    40
5    50
6    60
7    70
8    80
df2 = pd.DataFrame({'aux':['aa','aa','bb','bb']},index=[0,2,5,7])
df2 = 
  aux
0   aa  
2   aa
5   bb
7   bb
df = pd.concat([df1,df2],axis=1)
# After concating, in the aux column, I want to fill the NaN rows in between 
# the rows with same value. Example, fill rows between 0 and 2 with 'aa', 2 and 5 NaN, 5 and 7 with 'bb'
df = pd.concat([df1,df2],axis=1).fillna(method='ffill')
print(df)

目前的结果:

  Main aux
0    0   aa
1   10   aa
2   20   aa
3   30   aa # Wrong, here it should be NaN
4   40   aa # Wrong, here it should be NaN
5   50   bb 
6   60   bb
7   70   bb
8   80   bb # Wrong, here it should be NaN

预期结果:

  Main aux
0    0   aa
1   10   aa
2   20   aa
3   30  NaN
4   40  NaN
5   50   bb
6   60   bb
7   70   bb
8   80  NaN

I have two data frames: main and auxiliary. I am concatenating auxiliary to the main. It results in NaN in a few rows and I want to fill them, not all.
Code:

df1 = pd.DataFrame({'Main':[00,10,20,30,40,50,60,70,80]})
df1 = 
   Main
0     0
1    10
2    20
3    30
4    40
5    50
6    60
7    70
8    80
df2 = pd.DataFrame({'aux':['aa','aa','bb','bb']},index=[0,2,5,7])
df2 = 
  aux
0   aa  
2   aa
5   bb
7   bb
df = pd.concat([df1,df2],axis=1)
# After concating, in the aux column, I want to fill the NaN rows in between 
# the rows with same value. Example, fill rows between 0 and 2 with 'aa', 2 and 5 NaN, 5 and 7 with 'bb'
df = pd.concat([df1,df2],axis=1).fillna(method='ffill')
print(df)

Present result:

  Main aux
0    0   aa
1   10   aa
2   20   aa
3   30   aa # Wrong, here it should be NaN
4   40   aa # Wrong, here it should be NaN
5   50   bb 
6   60   bb
7   70   bb
8   80   bb # Wrong, here it should be NaN

Expected result:

  Main aux
0    0   aa
1   10   aa
2   20   aa
3   30  NaN
4   40  NaN
5   50   bb
6   60   bb
7   70   bb
8   80  NaN

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

待天淡蓝洁白时 2025-02-07 02:15:49

如果我正确理解,您想要这样做的事情。您想填充回填和前填充给出相同值的NAN。

ff = df.aux.ffill()
bf = df.aux.bfill()
df.aux = ff[ff == bf]

If I understand correctly, what you want can be done like this. You want to fill the NaNs where backfill and forward fill give the same value.

ff = df.aux.ffill()
bf = df.aux.bfill()
df.aux = ff[ff == bf]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文