Python函数用于识别数据框中数值列中的0作为缺失值。

huangapple go评论72阅读模式
英文:

Python function to identify 0 as a missing value in numerical columns of a dataframe

问题

我需要编写一个函数在其中将数字列中的零标识为缺失值使用Python有人可以帮我了解如何做吗

```python
# 在df数据框中选择数值列
df_num = df.select_dtypes(exclude='object')

之后,我需要一个函数将df_num中的所有零转换为缺失值。

这是我尝试过的:

df_num.replace(0, np.nan)

但数据集没有发生变化。

我还有其他方法可以尝试吗?


<details>
<summary>英文:</summary>

I need to write a function where zero in a numeric column is identified as missing value in python. Can anyone help me with how to do that?


#numerical columns in df dataframe
df_num = df.select_dtypes(exclude='object')

After this I need a function to convert all zeroes in df_num to be picked as missing values.

This is what I tried

df_num.replace(0,np.nan)

But the dataset is not being changed.

Is there any other way I can do it?

</details>


# 答案1
**得分**: 2

以下是要翻译的内容:

你会错过的是将其分配给期望将0转换为缺失值的列或列。
```python
df_num['numeric_column'] = df_num['numeric_column'].replace(0, np.nan)

最后,显示数据框以查看更改:print(df_num)
希望能帮助,问候!

英文:

What you would be missing there is to assign it to the column or columns from which it is expected to convert the 0s into missing values

df_num[&#39;numeric_column&#39;] = df_num[&#39;numeric_column&#39;].replace(0, np.nan)

And finally, display the dataframe to see the changes with print(df_num).
I hope it helps, greetings!

huangapple
  • 本文由 发表于 2023年4月17日 18:13:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定