J. Jones J. Jones - 2 months ago 48
Python Question

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

Answer

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)