简体   繁体   English

熊猫填充 DataFrame 部分

[英]Pandas ffill on section of DataFrame

I am attempting to forward fill a filtered section of a DataFrame but it is not working the way I hoped.我正在尝试转发填充 DataFrame 的过滤部分,但它没有按我希望的方式工作。

I have df that look like this:我的 df 看起来像这样:

    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.但是我的代码根本没有改变 df 。 Any feedback is greatly appreciated非常感谢任何反馈

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我不确定我是否理解您的问题,但如果您想填写 NAN 值或任何值,您应该使用 Simple imputer

from sklearn.impute import SimpleImputer

Then you can define an imputer that fills these missing values/NAN with a specific strategy.然后,您可以定义一个用特定策略填充这些缺失值/NAN 的 imputer。 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或者,如果您将 NaN 作为字符串,则可以这样写

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"]])

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我们可以使用布尔索引来过滤Col2 = 'string'Col部分,然后向前填充并仅更新该部分中的值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM