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