Pandas.DataFrame.str.replace函数将浮点数替换为NaN [英] Pandas.DataFrame.str.replace function replaces floats to NaN

查看:614
本文介绍了Pandas.DataFrame.str.replace函数将浮点数替换为NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas DataFrame,假设: df = pd.DataFrame({'Column name':['0,5',600,700]})

I have a Pandas DataFrame, suppose: df = pd.DataFrame({'Column name':['0,5',600,700]})

我需要删除,.代码是: df_mod = df.stack().str.replace(',','').unstack()

I need to remove ,. The code is: df_mod = df.stack().str.replace(',','').unstack()

结果是:[05, NaN, NaN]

您是否知道我的表达式为何用NaN替换数字以及如何避免呢?非常感谢!

Do you have any ideas why my expression replaces numbers with NaN and how to avoid it? Thanks a lot!

推荐答案

那些数字被视为没有str.replace方法的数字值,您可以将列转换为字符串,删除逗号,然后转换数据类型返回:

Those numbers are treated as numeric values, which don't have str.replace methods, you can convert the column to string, remove the comma, and then convert the data type back:

df['Column name'].astype(str).str.replace(",", "").astype(int)

#0      5
#1    600
#2    700
#Name: Column name, dtype: int64

这篇关于Pandas.DataFrame.str.replace函数将浮点数替换为NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆