在Python中从CSV转换为数组[重复]

wljmcqd8  于 5个月前  发布在  Python
关注(0)|答案(4)|浏览(62)

这个问题已经有答案了

How to read numbers in python from csv file?(2个答案)
23天前关闭
我有一个包含以下内容的CSV文件。

0.000264,0.000352,0.000087,0.000549
0.00016,0.000223,0.000011,0.000142
0.008853,0.006519,0.002043,0.009819
0.002076,0.001686,0.000959,0.003107
0.000599,0.000133,0.000113,0.000466
0.002264,0.001927,0.00079,0.003815
0.002761,0.00288,0.001261,0.006851
0.000723,0.000617,0.000794,0.002189

字符串
我想在Python中将值转换为数组并保持相同的顺序(行和列)。我如何实现这一点?
我尝试了不同的功能,但以错误结束。

lstz6jyr

lstz6jyr1#

你应该使用csv模块:

import csv

results = []
with open("input.csv") as csvfile:
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats
    for row in reader: # each row is a list
        results.append(row)

字符串
这给出了:

[[0.000264, 0.000352, 8.7e-05, 0.000549], 
[0.00016, 0.000223, 1.1e-05, 0.000142], 
[0.008853, 0.006519, 0.002043, 0.009819], 
[0.002076, 0.001686, 0.000959, 0.003107], 
[0.000599, 0.000133, 0.000113, 0.000466], 
[0.002264, 0.001927, 0.00079, 0.003815], 
[0.002761, 0.00288, 0.001261, 0.006851], 
[0.000723, 0.000617, 0.000794, 0.002189]]

w8ntj3qf

w8ntj3qf2#

如果您的文件不包含括号

with open('input.csv') as f:
    output = [float(s) for line in f.readlines() for s in line[:-1].split(',')]
print(output)

字符串

ny6fqffe

ny6fqffe3#

创建csv模块就是为了完成这个任务。下面的模块实现直接取自Python docs

import csv 
with open('file.csv','rb') as csvfile: 
    reader = csv.reader(csvfile, delimiter=',', quotechar='|') 
    for row in reader:
        #add data to list or other data structure

字符串
空格是分隔数据条目的字符,引号是引号。

tpgth1q7

tpgth1q74#

为了更广泛的使用:

#!/usr/bin/env python3

from pprint import pprint

result = []
delim=','
rows=0

for line in open("input_file.csv"):
    line=line.strip()
    row=line.split(delim)
    result.append(row)
    rows=rows+1

cols=len(row)

pprint(result)
print('rows: '+str(rows))
print('cols: '+str(cols))

# you get array of rows consisting of array of columns, all text

字符串
或者如果你想要整数:

#!/usr/bin/env python3

from pprint import pprint

result = []
delim=','
rows=0

for line in open("input_file.csv"):
    line=line.strip()
    row=line.split(delim)
    newrow=[]
    for col in row:
        newrow.append(int(col))
    result.append(newrow)
    rows=rows+1

cols=len(row)

pprint(result)
print('rows: '+str(rows))
print('cols: '+str(cols))

# you get array of rows consisting of array of columns, all integers


只需将int(col)更改为float(col)即可获得浮点数。
你应该得到:

[[0.000264, 0.000352, 8.7e-05, 0.000549],
 [0.00016, 0.000223, 1.1e-05, 0.000142],
 [0.008853, 0.006519, 0.002043, 0.009819],
 [0.002076, 0.001686, 0.000959, 0.003107],
 [0.000599, 0.000133, 0.000113, 0.000466],
 [0.002264, 0.001927, 0.00079, 0.003815],
 [0.002761, 0.00288, 0.001261, 0.006851],
 [0.000723, 0.000617, 0.000794, 0.002189]]
rows: 8
cols: 4

相关问题