可能是因为存在NaN值,可以采用以下代码:
my_df["Float Values"] = my_df["Value"].str[1:].str.replace(',', '').astype('float').fillna(0)
下面是一个可复现的例子:
import pandas as pd
s = pd.Series(['$200', '$3,000', float('nan')])
此时s
的内容如下:
0 $200
1 $3,000
2 NaN
dtype: object
运行你提供的代码:
s.apply(lambda x: float(x[1:].replace(',', '')) if x != "None" else 0)
将会出现如下错误:
TypeError: 'float' 对象不可被索引
而应采用以下代码:
s.str[1:].str.replace(',', '').astype('float').fillna(0)
执行后得到的结果:
0 200.0
1 3000.0
2 0.0
dtype: float64