【问题标题】:Python: convert CSV columns into arrays, except 1st and last rowPython:将CSV列转换为数组,除了第一行和最后一行
【发布时间】:2017-11-02 12:00:13
【问题描述】:

我有一个名为 results_date.csv 的 CSV 文件,如下所示:

Header1 ; Header2 ; Header3
string1=0,1 ; string2=0,2 ; string3=0,3
string4=0,4 ; string5=0,5 ; string6=0,6
..............................
stringX=0,x ; stringY=0,y ; stringZ=0,z
some other big string at the end

我想解析这个文件,并将文本保存到 2 个数组中,用于第 1 列和第 2 列,但没有相等和后面的数字、标题和末尾的另一个大字符串。例如:

array_for_column1 = ["string1", "string4", ..., "stringX"]
array_for_column2 = ["string2", "string5", ..., "stringY"]

这些数组将用于混淆矩阵。

我试着这样做:

#!/usr/bin/python3

import csv

data = csv.reader(open('results_date.csv', 'r'), delimiter=";", quotechar='|')

column1 = []
column2 = []

for row in data:
    column1.append(row[0])
    column2.append(row[1])

print (column1)
print (column2)

但它不起作用。此代码仅打印第一列,并为第二列引发错误。

提前感谢您的帮助!

【问题讨论】:

  • 可能文件中的最后一行不包含';'。在您的循环中,您可以检查 len(row) >= 2

标签: python arrays csv


【解决方案1】:

可能最后一行不包含;。您可以执行以下操作:

with open('results_date.csv', 'r') as f:
    data = csv.reader(f, delimiter=";", quotechar='|')
    next(data)  # skip headers

    # transpose rows to columns while safe-checking row length
    columns = list(zip(*(row for row in data if len(row) >= 2)))[:2]

    # process cells: strip, split on '=', take first part
    column1, column2 = [[s.strip().split('=')[0] for s in c] for c in columns]

【讨论】:

  • 作为一个魅力!非常感谢!
猜你喜欢
  • 2014-01-25
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
相关资源
最近更新 更多