J. Jones
J. Jones

Reputation: 69

Python IndexError: too many indices for array when trying to append two csv files

I keep getting this error whenever I try to append two csv files together.

log1 = np.genfromtxt('log40a.csv', dtype = float, delimiter=',', skip_header =1)
log2 = np.genfromtxt('log40b.csv', dtype = float, delimiter=',', skip_header= 1)
data = np.append(log1, log2)

This is the line the error I get on.

mSec = data[:,0]

It works fine if I don't append both csv and I just plot the log1 file, but when I try to append them for some reason I the error:

  File "<ipython-input-5-6155c8de61ad>", line 1, in <module>
    runfile('C:/Users/myname/.spyder2-py3/setdataexp.py', wdir='C:/Users/Myname/.spyder2-py3')

  File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)

  File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Myname/.spyder2-py3/setdataexp.py", line 11, in <module>
    mSec = data[:,0]

IndexError: too many indices for array

EDIT: I forgot to add a sample of the csv file

mSec,speed,heading,gspeed,....
20,3.5,3,4.5
21,3,4,5
22,3.5,6,5.5

Upvotes: 1

Views: 383

Answers (2)

Gatusko
Gatusko

Reputation: 2608

Giving the python documetation and you are using numpay you need to check this method for fusing existing arrays numpy.concatenate Ex taked from the docs:

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])

Documetation of numpay

And you have more methods to fusion your array:

Upvotes: 1

outoftime
outoftime

Reputation: 765

Just remove ,0 and everything will work fine.

mSec = data[:]

This traceback

  File "C:/Users/Myname/.spyder2-py3/setdataexp.py", line 11, in <module>
    mSec = data[:,0]

said that it is a problem in your code.

UPD:

np.append produce single dimensional array and it doesn't allow slicing operations, you have to modify append operation like this:

data = np.append(log1, log2, axis=0)

Upvotes: 1

Related Questions