Py学习  »  Python

python:如何将csv数据转换为数组

Grace Li • 4 年前 • 902 次点击  

我想把一个csv文件转换成数组。 testdata here

我在csv文件中的内容如下

11,10,8,12,13,11 0,1,0,2,3,0 5,15,13,11,18,18

我想把它变成数组,如下所示,

[[[11],
  [10],
  [8],
  [12],
  [13],
  [11]],

 [[0],
  [1],
  [0],
  [2],
  [3],
  [0]],

 [[5],
  [15],
  [13],
  [11],
  [18],
  [18]]]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38385
 
902 次点击  
文章 [ 3 ]  |  最新文章 4 年前
davedwards
Reply   •   1 楼
davedwards    5 年前
import csv

output = []

with open('test1.csv', 'r') as f:
    content = csv.reader(f, delimiter=',')

    for line in content:
        clean_line = filter(None, line)  # remove extra spaces
        output.append([[int(i)] for i in clean_line])

>>> print output
[[[11], [10], [8], [12], [13], [11]], [[0], [1], [0], [2], [3], [0]], [[5], [15], [13], [11], [18], [18]]]  

测试结果与预期输出相符:

desired = [ [[11],[10],[8],[12],[13],[11]], 
            [[0],[1],[0],[2],[3],[0]], 
            [[5],[15],[13],[11],[18],[18]] ]

# print output == desired   # True
Andre Araujo
Reply   •   2 楼
Andre Araujo    5 年前
  1. 首先,您可以将文件读取到数组中。
  2. 之后,可以使用map函数将每个字符串列表转换为整数列表

解决方案:

import csv
with open('input.csv', 'rb') as f:
    reader = csv.reader(f)
    lines = [row for row in reader]

array = [map(int,l) for l in lines]

array
[[11, 10, 8, 12, 13, 11], [0, 1, 0, 2, 3, 0], [5, 15, 13, 11, 18, 18]]
BernardL
Reply   •   3 楼
BernardL    5 年前

读取文件并从中获取项目列表:

import csv

results = []

with open('some_array.csv','r') as f:
    lines = csv.reader(f)
    for line in lines:
        results.append([[int(i)] for i in line])

>>results
[[['11'], ['10'], ['8'], ['12'], ['13'], ['11']],
 [['0'], ['1'], ['0'], ['2'], ['3'], ['0']],
 [['5'], ['15'], ['13'], ['11'], ['18'], ['18']]]