英文:
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['numeric_column'] = df_num['numeric_column'].replace(0, np.nan)
And finally, display the dataframe to see the changes with print(df_num)
.
I hope it helps, greetings!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论