【问题标题】:Convert specific column to float in list by Python通过Python将特定列转换为浮动列表
【发布时间】:2014-08-27 21:30:25
【问题描述】:

我有一个类似的列表:

[['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 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 列(第四列),这给了我错误。

请建议我将所有数据存储在可以同时包含浮点数和字符串的变量中。

【问题讨论】:

  • 相信你可以使用numpy.astype
  • 这些是 Python 列表还是 numpy 数组?
  • 您在代码中同时使用了空格和制表符。请只使用一个(根据PEP8,最好是 4 个空格)。我相信这会解决您的 IndentationError 问题。
  • 您只想更改每个子列表中的第四个元素?

标签: python string list converter


【解决方案1】:

按照上述建议修复缩进错误后;

转换单个列

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]

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 2021-05-19
    • 1970-01-01
    • 2015-11-27
    • 2022-07-20
    • 2023-01-02
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多