pandas ffill在数据框架部分
我试图将数据框架的过滤部分转发,但它无法按照我希望的方式工作。
我的DF看起来像这样:
Col Col2
0 1 NaN
1 NaN NaN
2 3 string
3 NaN string
我希望它看起来像这样:
Col Col2
0 1 NaN
1 NaN NaN
2 3 string
3 3 string
这是我当前的代码:
filter = (df["col2"] == "string")
df.loc[filter, "col"].fillna(method="ffill", inplace=True)
但是我的代码根本不会更改DF。任何反馈都非常感谢
I am attempting to forward fill a filtered section of a DataFrame but it is not working the way I hoped.
I have df that look like this:
Col Col2
0 1 NaN
1 NaN NaN
2 3 string
3 NaN string
I want it to look like this:
Col Col2
0 1 NaN
1 NaN NaN
2 3 string
3 3 string
This my current code:
filter = (df["col2"] == "string")
df.loc[filter, "col"].fillna(method="ffill", inplace=True)
But my code does not change the df at all. Any feedback is greatly appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们可以使用布尔索引来过滤
col
其中col2 ='string'
然后向前填充并仅在该部分中更新值We can use boolean indexing to filter the section of
Col
whereCol2 = 'string'
then forward fill and update the values only in that section我不确定我理解您的问题,但是如果您想填写NAN值或任何值应该使用简单的螺旋桨
,那么您可以定义一个以特定策略填充这些缺失值/NAN的螺旋桨。例如,如果您想用所有列的均值填充这些值,则可以按以下方式编写:
或者,如果您将NAN作为字符串,则可以这样写
,并且如果您想用特定值填充它,则可以这样做:
然后您可以这样使用
I am not sure I understand your question but if you want to fill the NAN values or any values you should use the Simple imputer
Then you can define an imputer that fills these missing values/NAN with a specific strategy. For example if you want to fill these values with the mean of all the column you can write it as follows:
Or you can write it like this if you have the NaN as string
and if you want to fill it with a specific values you can do this:
Then you can use it like that