通过Python将特定列转换为列表中的浮点
我有这样一个清单:通过Python将特定列转换为列表中的浮点,python,string,list,converter,Python,String,List,Converter,我有这样一个清单: [['1', '6', '192.168.4.118', '1605', '', '115.85.145.5', '80', '', '60', '0.000000000', '0x0010', 'Jun 15, 2010 18:27:57.490835000', '0.000000000'], ['2', '6','115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.002365000', '
[['1', '6', '192.168.4.118', '1605', '', '115.85.145.5', '80', '', '60', '0.000000000', '0x0010', 'Jun 15, 2010 18:27:57.490835000', '0.000000000'],
['2', '6','115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.002365000', '0x0010', 'Jun 15, 2010 18:27:57.493200000', '0.002365000'],
['3', '6', '115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.003513000', '0x0018', 'Jun 15, 2010 18:27:57.496713000', '0.005878000']]
我想将特定列转换为float,但我得到了错误(例如第四列)
在这里,我尝试了以下代码:
for x in data:
try:
yield float(x)
except ValueError:
yield x
我得到了这个错误:
File "read csv file.py", line 17
except ValueError:
^
IndentationError: unindent does not match any outer indentation level
或者当我使用这个简单的代码时:
float (data [:][3])
只转换第3列(第四列),这给了我一个错误
请建议我如何将所有数据存储在变量中,该变量可以包含浮点和字符串。按照上述建议修复缩进错误后 转换单个列
data = [['1', '6', '192.168.4.118', '1605', '', '115.85.145.5', '80', '',
'60', '0.000000000', '0x0010', 'Jun 15, 2010 18:27:57.490835000', '0.000000000'],
['2', '6','115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514',
'0.002365000', '0x0010', 'Jun 15, 2010 18:27:57.493200000', '0.002365000'],
['3', '6', '115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514',
'0.003513000', '0x0018', 'Jun 15, 2010 18:27:57.496713000', '0.005878000']]
for thing in data:
thing[3] = float(thing[3])
将所有数字转换为浮点数
def convert(sequence):
for item in sequence:
try:
yield float(item)
except ValueError as e:
yield item
new = [list(convert(sublist)) for sublist in data]
# or
new = [[item for item in convert(sublist)] for sublist in data]
我相信您可以使用numpy.astypes这些是Python列表还是numpy数组?您在代码中同时使用空格和制表符。请只使用一个(最好是4个空格)。我相信这将解决您的缩进错误问题。您只想更改每个子列表中的第四个元素吗?