[英]2D array/list in python
I'm trying to read in a csv into a 2D array, and I seem to be stuck. 我试图将csv读入2D数组,但似乎卡住了。 Any help with the below code will be appreciated.
以下代码的任何帮助将不胜感激。
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
Working code: 工作代码:
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
It seems my i2
variable was located in the wrong spot. 看来我的
i2
变量位于错误的位置。
It is hard to beat pandas for ease of use: 为了易于使用,很难击败大熊猫:
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()
Your problem is in the last line: you're making your column number dependent on the row number. 您的问题出在最后一行:您使列号取决于行号。 Try something like this instead:
尝试这样的事情:
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
In case you haven't seen it before, 如果您以前没看过,
i += 1
我+ = 1
is equivalent to 相当于
i = i+1
我=我+1
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.