我在pandas中进行数据转换时遇到了一些问题。我使用的数据来自.csv文件,数据形状如下:
In[1]: df1.head(5)
Out[1]:
Min Avg Max
0 -23863,708361909 -48934,4147351092 -74207,2942236209
1 -13713,0154545259 -35353,7123879251 -54097,3098488292
2 -13713,0154545259 -34380,9550139847 -54460,3415715344
3 -13576,928997833 -29763,4415556726 -64341,8134999719
4 -13576,928997833 -28261,296700531 -54086,0282965991
对于我的情况,我需要绘制名为'Min'的列,为此我需要将字符串转换为float。 但是,我无法将数据转换为浮点型数据,所以它一直在引发错误。
错误消息:
invalid literal for float(): -2888,46956828262
尝试使用convert_numeric
,to_numeric
,float(value)
等等,但我无法让它发挥作用。
dtype转换的正确sintax是什么?如何将字符串数据正确转换为浮点数据?
谢谢!
答案 0 :(得分:1)
你有逗号","在你的号码里面,这就是为什么它没有将它转换成浮点数。
value = "-2888,46956828262"
value= value.replace(",",".")
x = float(value)
print x
答案 1 :(得分:1)
适用于python2和python3
s = "-2888,46956828262"
f = float(s.replace(',','.'))
print (f)
答案 2 :(得分:1)
您期望的数字似乎是在使用逗号作为小数分隔符的区域设置中格式化的。要解析这样的数字,首先确定语言环境(例如,在法国,这将是“fr_FR”)并相应地设置它。
from locale import delocalize, setlocale, format, LC_NUMERIC
setlocale(LC_NUMERIC, 'fr_FR.UTF-8')
parse_this = '-2888,46956828262'
>>> print(delocalize(parse_this))
'-2888.46956828262'
>>> my_float = float(delocalize(parse_this))
>>> print(my_float)
-2888.46956828262
# Then, if you need to print this number elsewhere:
>>> print(format('%f', my_float))
-2888,4695682826
# You might also need to adjust padding
>>> print(format('%16f', my_float))
-2888,469568
必须始终验证外部输入;这包括确定正确的数据区域。如果需要解析CSV,则必须使系统与区域设置兼容,并确定要解析的数据的区域设置。
如果您希望代码在不同的语言环境中保持可移植性,请避免使用字符串替换和正则表达式的方法,因为它们往往很脆弱,需要大量的哄骗才能适应不同的语言环境组合:
CSV代表以逗号分隔的值。如上所述,值用逗号分隔,因此人们提出了在CSV文件中编码数字的其他方法:
MyNumber,OtherColumn
"-412,932459",The other column
"-401,999999",And another one
虽然这允许在文件中编码原始系统的语言环境,但是不希望事物在双引号内的解析器可能会将此值解释为文字字符串而不是可能是数字表达式,显然,解析器是不知道locales可能无法将此表达式解析为十进制数字。