如何从 csv 文件中读取字符串并将其转换为整数数组?
How to read strings from a csv file and convert it into a integer array?
我正在寻找借助 csv 文件中的数据创建整数数组的最优化方法。
csv文件("sample.csv")数据是这样的,
prediciton1
prediction2
prediction3
low
low
low
low
high
high
其中 低 = 1,高 = 3,
我想从 csv 中读取这些数据并制作一个数组,如下所示,
array =
[[1,1,1],
[1,3,3]]
import csv
import sys
num1 = 'low'
num2 = 'high'
csv_file = csv.reader(open('sample.csv', "r"), delimiter=",")
count = 0
for row in csv_file:
if count == 1:
if num1 == row[0]:
dat1 = 1
elif num2 == row[0]:
dat1 = 3
if num1 == row[1]:
dat2 = 1
elif num2 == row[1]:
dat2 = 3
if num1 == row[2]:
dat3 = 1
elif num2 == row[2]:
dat3 = 3
count = count + 1
array =[dat1,dat2,dat3]
这种方法有效,但效率似乎很低。寻找替代和优化的方法来实现这一目标。
使用 dict
进行查找和列表理解
例如:
check = {'low': 1, "high": 3}
with open('sample.csv') as infile:
csv_file = csv.reader(infile)
next(csv_file) # skip header
result = [[check[c] for c in row] for row in csv_file]
由于 CSV 文件非常简单,您甚至可以在没有 CSV 包的情况下完成它:
# We open the CSV file
with open('sample.csv') as file:
# We read all the lines and store them in a list
lines = file.readlines()
# We remove the CSV header
lines = lines[1:]
# We create the array
array = [
[{
'low': 1,
'high': 3
}.get(value.strip()) for value in line.split(',')
] for line in lines]
# We print the array
print(array)
这将打印以下数组:[[1, 1, 1], [1, 3, 3]]
请注意使用 dict
的 get
方法来避免错误,以防 CSV 包含不需要的值。在这些情况下,该数组将包含一个 None
值。
我正在寻找借助 csv 文件中的数据创建整数数组的最优化方法。
csv文件("sample.csv")数据是这样的,
prediciton1 | prediction2 | prediction3 |
---|---|---|
low | low | low |
low | high | high |
其中 低 = 1,高 = 3,
我想从 csv 中读取这些数据并制作一个数组,如下所示,
array =
[[1,1,1],
[1,3,3]]
import csv
import sys
num1 = 'low'
num2 = 'high'
csv_file = csv.reader(open('sample.csv', "r"), delimiter=",")
count = 0
for row in csv_file:
if count == 1:
if num1 == row[0]:
dat1 = 1
elif num2 == row[0]:
dat1 = 3
if num1 == row[1]:
dat2 = 1
elif num2 == row[1]:
dat2 = 3
if num1 == row[2]:
dat3 = 1
elif num2 == row[2]:
dat3 = 3
count = count + 1
array =[dat1,dat2,dat3]
这种方法有效,但效率似乎很低。寻找替代和优化的方法来实现这一目标。
使用 dict
进行查找和列表理解
例如:
check = {'low': 1, "high": 3}
with open('sample.csv') as infile:
csv_file = csv.reader(infile)
next(csv_file) # skip header
result = [[check[c] for c in row] for row in csv_file]
由于 CSV 文件非常简单,您甚至可以在没有 CSV 包的情况下完成它:
# We open the CSV file
with open('sample.csv') as file:
# We read all the lines and store them in a list
lines = file.readlines()
# We remove the CSV header
lines = lines[1:]
# We create the array
array = [
[{
'low': 1,
'high': 3
}.get(value.strip()) for value in line.split(',')
] for line in lines]
# We print the array
print(array)
这将打印以下数组:[[1, 1, 1], [1, 3, 3]]
请注意使用 dict
的 get
方法来避免错误,以防 CSV 包含不需要的值。在这些情况下,该数组将包含一个 None
值。