Pandas - 如何在DataFrame系列中用零值替换字符串?

Ste*_*han 3 python dataframe pandas

我正在将一些csv数据导入Pandas DataFrame(在Python中).一个系列意味着所有数值.但是,它还包含一些虚假的"$ - "元素,表示为字符串.这些都是以前的格式化遗留下来的.如果我只导入该系列,Pandas会将其报告为一系列"对象".

用零替换这些"$ - "字符串的最佳方法是什么?或者更一般地说,如何用数值替换一系列中的所有字符串(主要是数字),并将系列转换为浮点类型?

  • 史蒂夫

tmd*_*son 8

您可以使用with 的convert_objects方法将字符串更改为DataFrameconvert_numeric=TrueNaNs

来自文档:

convert_numeric:如果为True,则尝试强制转换为数字(包括字符串),不可转换的值变为NaN.

In [17]: df
Out[17]: 
    a   b  c
0  1.  2.  4
1  sd  2.  4
2  1.  fg  5

In [18]: df2 = df.convert_objects(convert_numeric=True)

In [19]: df2
Out[19]: 
    a   b  c
0   1   2  4
1 NaN   2  4
2   1 NaN  5
Run Code Online (Sandbox Code Playgroud)

最后,如果你想将它们转换NaNs0's,你可以使用df.replace

In [20]: df2.replace('NaN',0)
Out[20]: 
   a  b  c
0  1  2  4
1  0  2  4
2  1  0  5
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`pd.to_numeric` 是新的热点;`convert_objects` 已被弃用。 (3认同)

hel*_*err 3

使用Series.str.replaceSeries.astype

df = pd.Series(['2$-32$-4','123$-12','00123','44'])
df.str.replace(r'\$-','0').astype(float)

0    203204
1    123012
2       123
3        44
dtype: float64
Run Code Online (Sandbox Code Playgroud)