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

前端 未结 6 1133
醉梦人生
醉梦人生 2020-12-07 16:24

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.         


        
6条回答
  •  盖世英雄少女心
    2020-12-07 16:54

    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.

提交回复
热议问题