pythonarrayslistnumpytypeerror

How to prevent TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?


I am trying to create 3 numpy arrays/lists using data from another array called mean_data as follows:

---> 39 R = np.array(mean_data[:,0])
     40 P = np.array(mean_data[:,1])
     41 Z = np.array(mean_data[:,2])

When I try to run the program I get the error:

TypeError: list indices must be integers, not tuple

The mean_data list looks like this sample...:

[6.0, 315.0, 4.8123788544375692e-06],
[6.5, 0.0, 2.259217450023793e-06],
[6.5, 45.0, 9.2823565008402673e-06],
[6.5, 90.0, 8.309270169336028e-06],
[6.5, 135.0, 6.4709418114245381e-05],
[6.5, 180.0, 1.7227922423558414e-05],
[6.5, 225.0, 1.2308522579848724e-05],
[6.5, 270.0, 2.6905672894824344e-05],
[6.5, 315.0, 2.2727114437176048e-05]]

I don't know how to prevent this error, I have tried creating mean_data as a np.array and using np.append to add values to it but that doesn't solve the problem either.

Here's the traceback (was using ipython before):

Traceback (most recent call last):
  File "polarplot.py", line 36, in <module>
    R = np.array(mean_data[:,0])
TypeError: list indices must be integers, not tuple

And the other way I tried to create an array was:

mean_data = np.array([])

for ur, ua in it.product(uradius, uangle):
    samepoints = (data[:,0]==ur) & (data[:,1]==ua)
    if samepoints.sum() > 1:  # check if there is more than one match
        np.append(mean_data[ur, ua, np.mean(data[samepoints,-1])])
    elif samepoints.sum() == 1:
        np.append(mean_data, [ur, ua, data[samepoints,-1]])

The traceback on that is:

IndexError                                Traceback (most recent call last)
<ipython-input-3-5268bc25e75e> in <module>()
     31     samepoints = (data[:,0]==ur) & (data[:,1]==ua)
     32     if samepoints.sum() > 1:  # check if there is more than one match
---> 33         np.append(mean_data[ur, ua, np.mean(data[samepoints,-1])])
     34     elif samepoints.sum() == 1:
     35         np.append(mean_data, [ur, ua, data[samepoints,-1]])

IndexError: invalid index

Solution

  • The variable mean_data is a nested list, in Python accessing a nested list cannot be done by multi-dimensional slicing, i.e.: mean_data[1,2], instead one would write mean_data[1][2].

    This is becausemean_data[2] is a list. Further indexing is done recursively - since mean_data[2] is a list, mean_data[2][0] is the first index of that list.

    Additionally, mean_data[:][0] does not work because mean_data[:] returns mean_data.

    The solution is to replace the array ,or import the original data, as follows:

    mean_data = np.array(mean_data)
    

    numpy arrays (like MATLAB arrays and unlike nested lists) support multi-dimensional slicing with tuples.