CSV File with minus sign after number. "ValueError: could not convert string to float:"
CSV File with minus sign after number. "ValueError: could not convert string to float:"
我有几个 CSV 文件,其中负数显示在数字后面带有减号(30.50- 而不是 -30.50)。如果我尝试将列转换为整数,Python returns 一个 ValueError (ValueError: could not convert string to float: '30.50-'
)
有人知道如何处理吗?
提前致谢!
最好的,
莫里茨
由于您的 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
像这样:
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
我有几个 CSV 文件,其中负数显示在数字后面带有减号(30.50- 而不是 -30.50)。如果我尝试将列转换为整数,Python returns 一个 ValueError (ValueError: could not convert string to float: '30.50-'
)
有人知道如何处理吗?
提前致谢!
最好的, 莫里茨
由于您的 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
像这样:
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