熊猫read_csv解析数字时忽略美元符号

nwl*_*wly 1 python numpy pandas

我有一个csv文件,其中包含一些带有美元符号的单元格(例如$46.5)。我强迫所有类型都numpy.float64在函数中pandas.read_csv()。它抱怨ValueError: could not convert string to float: $46.5。有没有办法干净地处理这个问题?

Ale*_*der 5

您可以为相关列添加一个转换器:

pd.DataFrame({'col1': ['$46.51', '$38.00', 40], 
              'col2': [1, 2, 3]}).to_csv('test_df.csv', index=False)

>>> pd.read_csv('test_df.csv', converters={'col1': lambda s: float(s.replace('$', ''))})
    col1  col2
0  46.51     1
1  38.00     2
2  40.00     3
Run Code Online (Sandbox Code Playgroud)

  • 您可能需要为逗号添加相同的逻辑,否则它将尝试替换$ 1,437.22而炸弹 (3认同)
  • @flyingmeatball 使用 `thousands=','` kwarg。 (2认同)