[英]Problem with changing NaN values to 0 in a column of a pandas dataframe
I am trying to understand how this works..我试图了解这是如何工作的..
I have this df.我有这个df。
ticket_id address grafitti_status
0 284932 10041 roseberry, Detroit MI NaN
1 285362 18520 evergreen, Detroit MI NaN
2 285361 18520 evergreen, Detroit MI NaN
3 285338 1835 central, Detroit MI NaN
4 285346 1700 central, Detroit MI NaN
5 285345 1700 central, Detroit MI NaN
where在哪里
In: df.grafitti_status.unique()
Out: array([nan, 'GRAFFITI TICKET'], dtype=object)
So I am trying to change NaN to 0 and 'GRAFFITI TICKET' to 1.所以我试图将 NaN 更改为 0 并将 'GRAFFITI TICKET' 更改为 1。
I used我用了
df.loc[df['grafitti_status'] == 'GRAFFITI TICKET', 'grafitti_status'] = 1
which works fine, but the same for '0'效果很好,但对于“0”也是如此
df.loc[df['grafitti_status'] == np.nan, 'grafitti_status'] = 0
Out: array([nan, 1], dtype=object)
does not work because NaN values still remain..不起作用,因为 NaN 值仍然存在..
and和
df['grafitti_status'] = df['grafitti_status'].replace({np.nan:0,'GRAFFITI TICKET':1},inplace=True)
does not work either, replacing everything with None.也不起作用,用 None 替换所有内容。
ticket_id address grafitti_status
0 284932 10041 roseberry, Detroit MI None
1 285362 18520 evergreen, Detroit MI None
2 285361 18520 evergreen, Detroit MI None
3 285338 1835 central, Detroit MI None
4 285346 1700 central, Detroit MI None
5 285345 1700 central, Detroit MI None
6 285347 1700 central, Detroit MI None
Can anybody provide me any insight why it works this way?任何人都可以告诉我为什么它会这样工作吗?
I have finally found that I can achieve the desired result with我终于发现我可以达到预期的结果
df.loc[df['grafitti_status'] == 'GRAFFITI TICKET', 'grafitti_status'] = 1
df['grafitti_status'] = df['grafitti_status'].fillna(0)
Out: array([0, 1], dtype=int64)
which leads to the following warning message.这会导致以下警告消息。
C:\Users\Maria\Anaconda3\lib\site-packages\pandas\core\indexing.py:543: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item] = s
C:\Users\Maria\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
So I am still not sure what would be the correct way to do it?所以我仍然不确定正确的方法是什么?
Since自从
np.nan==np.nan
will return False np.nan==np.nan
将返回 False
We have function isna
我们有 function
isna
df.loc[df['grafitti_status'].isna(), 'grafitti_status'] = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.