简体   繁体   English

如何将 a.fillna() 应用于过滤后的 dataframe?

[英]How to apply a .fillna() to a filtered dataframe?

I am learning pandas using a dataset of players from the womans world cup.我正在使用女子世界杯球员数据集学习 pandas。

I want to apply a.fillna() on the results of the following filter of the main dataframe:我想在主 dataframe 的以下过滤器的结果上应用 a.fillna():

df[(df["pos"] == "GK") & (df["goals"].isnull())]

How can I apply:我该如何申请:

fillna(0, inplace=True)

To the above filter, , on the 'goals' column.对于上述过滤器,“目标”列中的 。

I did use the below code but when I apply it, it runs but doesn't seem to work:我确实使用了下面的代码,但是当我应用它时,它运行但似乎不起作用:

df.loc[df["pos"] == "GK"].loc[df["goals"].isnull()].loc[:,"goals"].fillna(0, inplace=True)

The first line selects the index and you know the column, so just use one loc and it should be fine:第一行选择索引并且您知道该列,因此只需使用一个loc就可以了:

df.loc[(df["pos"] == "GK") & (df["goals"].isnull()), 'goals'].fillna(0, inplace=True)

update:更新:

So it seems pandas returns a copy and inplace doesn't really do anything there.因此,似乎 pandas 返回了一个副本,并且inplace在那里并没有真正做任何事情。 However, you don't want to assign it to all of your dataframe.但是,您不想将其分配给您的所有 dataframe。 Since you are already filtering for nan values, an easier way is to just assign the value directly.由于您已经在过滤 nan 值,因此更简单的方法是直接分配值。 df.loc[(df["pos"] == "GK") & (df["goals"].isnull()), 'goals'] = 0 This worked fine on my computer, hope it solves your problem. df.loc[(df["pos"] == "GK") & (df["goals"].isnull()), 'goals'] = 0这在我的电脑上运行良好,希望它能解决你的问题。

df[(df["pos"] == "GK") & (df["goals"].isnull()), 'goals']=0

That will solve your problem.这将解决你的问题。

You already masked using a boolean select.您已经使用 boolean select 进行了屏蔽。 So just .fillna(0)所以只需.fillna(0)

df[(df["pos"] == "GK") & (df["goals"].isnull())].fillna(0)

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

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