df.fillna(0) command won't replace NaN values with 0

风格不统一 提交于 2019-12-19 09:26:40

问题


I'm trying to replace the NaN values generated in the code below to 0. I don't understand what the below won't work. It still keeps the NaN values.

df_pubs=pd.read_sql("select Conference, Year, count(*) as totalPubs from publications where year>=1991 group by conference, year", db)

df_pubs['Conference'] = df_pubs['Conference'].str.encode('utf-8')

df_pubs = df_pubs.pivot(index='Conference', columns='Year', values='totalPubs')
df_pubs.fillna(0)

print df_pubs

print df produces this:

Year                                                                                       1991  \
Conference                                                                                        
                                                                                            223   
10th Anniversary Colloquium of UNU/IIST                                                     NaN   
15. WLP                                                                                     NaN   
1999 ACM SIGMOD Workshop on Research Issues in Data Mining and Knowledge Discovery          NaN   
25 Years CSP                                                                                NaN  

回答1:


You need to assign the result of fillna:

df_pubs = df_pubs.fillna(0)

or pass param inplace=True:

df_pubs.fillna(0, inplace=True)

See the docs

You could modify your code to this:

df_pubs = df_pubs.pivot(index='Conference', columns='Year', values='totalPubs').fillna(0)

which would work but it's debatable whether the fillna is readable here.



来源:https://stackoverflow.com/questions/30267834/df-fillna0-command-wont-replace-nan-values-with-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!