【问题标题】:df.fillna(0) command won't replace NaN values with 0df.fillna(0) 命令不会用 0 替换 NaN 值
【发布时间】:2018-03-16 09:36:57
【问题描述】:

我正在尝试将下面代码中生成的 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  

【问题讨论】:

  • 你需要df_pubs = df_pubs.fillna(0)fillna 不会修改原始 DataFrame。
  • 大部分pandas操作默认返回一个副本,有些有参数inplace=True

标签: python-2.7 pandas dataframe nan


【解决方案1】:

你需要分配fillna的结果:

df_pubs = df_pubs.fillna(0)

或传递参数inplace=True:

df_pubs.fillna(0, inplace=True)

docs

您可以将代码修改为:

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

这可行,但 fillna 在此处是否可读仍有待商榷。

【讨论】:

  • 我尝试将 df 保存为 sql 表,使用:df_pubs.to_sql('conferences_pubs', db, flavor='sqlite', if_exists='replace', index=True) index=False,它可以工作,但我需要将会议名称(即索引)添加为列,所以当我把 index=True 它给了我一个错误:ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str)。强烈建议您将应用程序切换为 Unicode 字符串。任何想法为什么会这样?
  • 不知道,但听起来你的数据库的编码没有设置为接受 utf-8,你能改变这个吗?老实说,我对这个话题了解不多,所以如果你仍然被卡住,我会发布一个新问题
猜你喜欢
  • 2021-07-16
  • 2018-04-17
  • 2021-06-27
  • 2013-03-12
  • 2016-07-18
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
相关资源
最近更新 更多