CSV文件,数字后面有减号。"ValueError: could not convert string to float:"

问题描述 投票:2回答:1

我有几个CSV文件,其中负数显示在数字后面有减号(30.50-而不是-30.50)。如果我尝试将列转换为整数,Python 返回一个 ValueError (ValueError: could not convert string to float: '30.50-')

有谁知道如何处理?

先谢谢你

最好的,莫里茨

python pandas csv valueerror
1个回答
1
投票

就像这样。

In [141]: df = pd.DataFrame({'A':['30.50-', '20', '-10.01','22.10-']})
In [142]: df 
Out[142]: 
        A
0  30.50-
1      20
2  -10.01
3  22.10-

In [143]: df['A'] = df['A'].apply(lambda x: '-'+ (x.rstrip('-')) if x.endswith('-') else x).astype(float) 

In [145]: df 
Out[145]: 
       A
0 -30.50
1  20.00
2 -10.01
3 -22.10

In [144]: df.dtypes 
Out[144]: 
A    float64
dtype: object

1
投票

就像你的... string 不是有效的格式,无法转换为 float 你首先要把它纠正过来,删除 - 从右 rstrip 并将其添加到前面。例如:

df = pd.DataFrame({'a':['1.5-','1.7','2.0','4.1-']})
df.a.apply(lambda x: '-'+(x.rstrip('-')) if x[-1] =='-' else x).astype(float)
0   -1.5
1    1.7
2    2.0
3   -4.1
Name: a, dtype: float64
© www.soinside.com 2019 - 2024. All rights reserved.