[英]Pandas - How to replace string with zero values in a DataFrame series?
我正在將一些 csv 數據導入 Pandas DataFrame(在 Python 中)。 一個系列意味着所有數值。 但是,它還包含一些以字符串表示的虛假“$-”元素。 這些是從以前的格式中遺留下來的。 如果我只是導入該系列,Pandas 會將其報告為一系列“對象”。
用零替換這些“$-”字符串的最佳方法是什么? 或者更一般地說,如何用數值替換系列中的所有字符串(主要是數字),並將系列轉換為浮點類型?
您可以使用DataFrame
的convert_objects
方法,使用convert_numeric=True
將字符串更改為NaNs
從文檔:
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
最后,如果要將這些NaNs
轉換為0
,可以使用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
使用Series.str.replace
和Series.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
使用.to_numeric
將字符串轉換為數字(使用錯誤選項 'coerce' 將字符串設置為NaN
):
df = pd.to_numeric(df, errors='coerce')
然后使用替換將NaN
值轉換為零:
df.replace('NaN',0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.