我试图将csv读入2D阵列,但我似乎陷入困境。任何有关以下代码的帮助将不胜感激。
import sys, csv
rowColumn = []
rowColumn.append([])
rowColumn.append([])
with open('filelocation.csv', "r+") as inputFile:
fieldnames = ['col1','col2','col3','col4','col5','col6','col7','col8',]
reader = csv.reader(inputFile)
i1=-1
i2=0
for row in reader:
i1=i1+1
print(row)
for item in row:
#store item in 2D list/array
rowColumn[i1][i2].append(item)#error occurs here
i2=i1+1
工作代码:
import sys, csv
rowColumn = []
rowColumn.append([])
rowColumn.append([])
with open('filelocation.csv', "r+") as inputFile:
reader = csv.reader(inputFile)
i1=-1
for row in reader:
i1+=1
i2=0
for item in row:
#store item in 2D list/array
rowColumn[i1][i2].append(item)
i2+=1
我的i2
变量似乎位于错误的位置。
答案 0 :(得分:3)
为了便于使用,很难击败熊猫:
import pandas as pd
# Read CSV file into pandas dataframe df
df = pd.read_csv('filelocation.csv', index_col=False)
# Convert dataframe to python list via a numpy array
python_list = df.values.tolist()
答案 1 :(得分:2)
您的问题出在最后一行:您的列号取决于行号。尝试这样的事情:
for row in reader:
i1 += 1
print(row)
i2 = 0
for item in row:
#store item in 2D list/array
rowColumn[i1][i2].append(item)
i2 += 1
如果您以前没有见过,
i + = 1
相当于
i = i + 1