0

我有以下 CSV 文件: 在此处输入图像描述

如何一次仅将数字导入python中的数组中?没有日期,没有字符串。

我的代码:

import csv

def test():
    out = open("example.csv","rb")
    data = csv.reader(out)
    data = [row for row in data]
    out.close()
    print data

让我更清楚。我不想要一个巨大的二维数组。我只想导入第二行,然后操作数据,然后获取第三行。为此我需要一个 for 循环,但我不确定 csv 是如何完全工作的。

4

3 回答 3

0

试试这个:

with open('the_CSV_file.csv','r') as f:
  box = f.readlines()

result_box = []
for line in box[1:]:
  items = line.split(';') # adjust the separator character in the CSV as needed
  result_box.append(items[1:])

print result_box
于 2013-05-14T17:04:43.717 回答
0
% <csv # just a silly CSV I got from http://secrets.d8u.us/csv
Secret,Timestamp
Forza la fiera!,1368230474
American healthcare SUXXXXX,1368232342
I am not sure if I wanna take the girl out again,1368240406
I bred a race of intelligent penguin assassins to murder dick cheney. ,1368245584
"I guess it is my mother's time of the month, as it were",1368380424
i've seen walls breath,1368390258

In [33]: %paste
with open('csv', 'rb') as csvfile:
       csv_reader = csv.reader(csvfile, dialect='excel') # excel may be the default, but doesn't hurt to be explicit
       csv_reader.next()
       for row in csv_reader:
              array.append(row[1:])
## -- End pasted text --

In [34]: array
Out[34]: 
[['1368230474'],
 ['1368232342'],
 ['1368240406'],
 ['1368245584'],
 ['1368380424'],
 ['1368390258']]
于 2013-05-14T17:10:32.560 回答
0

根据@DSM 的评论更正

你最终应该得到你想要的array

import csv

with open('theFile.csv', 'r', encoding = 'utf8') as data:
    reader = csv.reader(data)

    array = []
    next(reader)    # skips 'string's row
    for row in reader:
        numberRow = [float(x) for x in row[1:]) # This slice skips 'date's
        array.append(numberRow)

我不确定是否有必要定义编码。但是,如果您想将它们视为数字,则必须使用float(x),否则它们将只是字符串。

于 2013-05-14T17:15:37.730 回答