pHorseSpec
pHorseSpec

Reputation: 1274

2D array/list in python

I'm trying to read in a csv into a 2D array, and I seem to be stuck. 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

Upvotes: -1

Views: 79

Answers (2)

Keith Brodie
Keith Brodie

Reputation: 655

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()

Upvotes: 2

Prune
Prune

Reputation: 77900

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

is equivalent to

i = i+1

.

Upvotes: 2

Related Questions