df.fillna(0)命令不会将NaN值替换为0

时间:2015-05-15 20:03:29

标签: python-2.7 pandas dataframe nan

我试图将下面代码中生成的NaN值替换为0.我不明白下面的内容是什么工作。它仍然保持NaN值。

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这个:

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 个答案:

答案 0 :(得分:5)

您需要指定fillna的结果:

df_pubs = df_pubs.fillna(0)

或传递param inplace=True

df_pubs.fillna(0, inplace=True)

请参阅docs

您可以将代码修改为:

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

这可行,但是fillna在这里是否可读是值得商榷的。