我想把一个字符串'6,105.00'中的','去掉,方便后面转化为浮点数,
但是使用了.replace(',', '')后并没有效果,系统还是报错?求解原因,谢谢!
代码:
import pandas as pd
import sys
# input_file = sys.argv[1]
# output_file = sys.argv[2]
input_file = input()
output_file = input()
data_frame = pd.read_csv(input_file)
data_frame['Cost'] = data_frame['Cost'].str.strip('$').replace(',', '').astype(float)
data_frame_value_meets_condition = data_frame.loc[(data_frame['Supplier Name'].str.contains('Z')) | (data_frame['Cost'] > 600.0), :]
报错:
return arr.astype(dtype, copy=True)
ValueError: could not convert string to float: '6,015.00 '
replace 是字符串函数,结果也是字符串
astype好像是不同数据类型的转换,比如int 转float
直接用float('6105.00')应该就可以了
已找到解决方法:分成两行代码完成转换
原:
data_frame['Cost'] = data_frame['Cost'].str.strip('$').replace(',', '').astype(float)
换成:
data_frame['Cost'] = data_frame['Cost'].str.strip('$')
data_frame['Cost'] = data_frame['Cost'].str.replace(',', '').astype(float)
即可