Using a python function to replace characters in specific column then throws TypeError: cannot convert the series to <class 'float'>

Using a python function to replace characters in specific column then throws TypeError: cannot convert the series to <class 'float'>

我想使用下面的 clean_currency 方法从 Savings ($) 列中删除逗号和美元符号并放入名为 'Savings_Clean' 的新列中。

def clean_currency(curr):
    return float(curr.replace(",", "").replace("$", ""))

clean_currency(",000")#The output is proof that function is working

Output: 60000.0

如何清理 Savings ($) 列,因为当我输入 clean_currency(df.Savings) 时出现以下错误:TypeError: cannot convert the series to <class 'float'>

要使其与普通字符串以及包含字符串的 pd.Series 一起使用,可以使用 if 保护:

def clean_currency(curr):
    if isinstance(curr, str):
        return float(curr.replace(",", "").replace("$", ""))
    return curr.str.replace(",", "").str.replace("$", "").astype(float)

现在它将查找传递给 curr 的参数,如果它是 string,则使用 float 进行转换,否则假设它是一个系列并使用 astype . (请注意,我们使用 str 访问器来替换系列)。

>>> clean_currency(",000")
60000.0

>>> clean_currency(pd.Series([",000", "0,000", ",000,000"]))
0      60000.0
1     120000.0
2    1000000.0
dtype: float64