pandas ffill在数据框架部分

发布于 2025-02-05 14:30:05 字数 447 浏览 3 评论 0原文

我试图将数据框架的过滤部分转发,但它无法按照我希望的方式工作。

我的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 技术交流群。

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

发布评论

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

评论(2

段念尘 2025-02-12 14:30:06

我们可以使用布尔索引来过滤col其中col2 ='string'然后向前填充并仅在该部分中更新值

m = df['Col2'].eq('string')
df.loc[m, 'Col'] = df.loc[m, 'Col'].ffill()

   Col    Col2
0  1.0     NaN
1  NaN     NaN
2  3.0  string
3  3.0  string

We can use boolean indexing to filter the section of Col where Col2 = 'string' then forward fill and update the values only in that section

m = df['Col2'].eq('string')
df.loc[m, 'Col'] = df.loc[m, 'Col'].ffill()

   Col    Col2
0  1.0     NaN
1  NaN     NaN
2  3.0  string
3  3.0  string
書生途 2025-02-12 14:30:06

我不确定我理解您的问题,但是如果您想填写NAN值或任何值应该使用简单的螺旋桨

from sklearn.impute import SimpleImputer

,那么您可以定义一个以特定策略填充这些缺失值/NAN的螺旋桨。例如,如果您想用所有列的均值填充这些值,则可以按以下方式编写:

imputer=SimpleImputer(missing_values=np.nan, strategy= 'mean')

或者,如果您将NAN作为字符串,则可以这样写

imputer=SimpleImputer(missing_values="NaN", strategy= 'mean')

,并且如果您想用特定值填充它,则可以这样做:

imputer=SimpleImputer(missing_values=np.nan, strategy= 'constant', fill_value = "YOUR VALUE")

然后您可以这样使用

df[["Col"]]=imputer.fit_transform(df[["Col"]])

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

from sklearn.impute import SimpleImputer

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:

imputer=SimpleImputer(missing_values=np.nan, strategy= 'mean')

Or you can write it like this if you have the NaN as string

imputer=SimpleImputer(missing_values="NaN", strategy= 'mean')

and if you want to fill it with a specific values you can do this:

imputer=SimpleImputer(missing_values=np.nan, strategy= 'constant', fill_value = "YOUR VALUE")

Then you can use it like that

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