删除python中的列

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

有一个逗号分隔的文件,大约有50列和几行,我需要删除所有始终为0的列(即该列中的所有值都为零)。

使用以下代码读取文件:

with open('data.txt', 'rb') as f:
    reader.csv.reader(f, delimiter=',')
    for row in reader:
        print row


0 0.1 0.3 0.4 0
0 0.2 0.5 0.3 0
0 0.7 0.9 0.2 0

如何从这个内存结构中精确删除列(即0)。如果没有重写并重新读取另一个临时csv文件来实现这一点,那会更好。

python csv
1个回答
1
投票

读入所有行(将所有值映射到浮点数),使用zip(*rows)转换为列,仅使用any()保留任何具有非零值的值,使用zip(*columns)转换回行:

with open('data.txt', 'rb') as f:
    rows = list(map(float, row) for row in csv.reader(f, delimiter=','))

rows = zip(*[col for col in zip(*rows) if any(col)])

后一步作为示范:

>>> rows = [[0, 0.1, 0.3, 0.4, 0], [0, 0.2, 0.5, 0.3, 0], [0, 0.7, 0.9, 0.2, 0]]
>>> zip(*[col for col in zip(*rows) if any(col)])
[(0.1, 0.3, 0.4), (0.2, 0.5, 0.3), (0.7, 0.9, 0.2)]
© www.soinside.com 2019 - 2024. All rights reserved.