熊猫的前向填充,但仅在相等的值之间
我有两个数据帧:主和辅助。我正在将辅助辅助与主要的辅助。它导致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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解,您想要这样做的事情。您想填充回填和前填充给出相同值的NAN。
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.