将python列表复制到numpy数组时,如何防止TypeError:列表索引必须是整数,而不是元组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15884527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?
提问by mark mcmurray
I am trying to create 3 numpy arrays/lists using data from another array called mean_data as follows:
我正在尝试使用来自另一个名为 mean_data 的数组的数据创建 3 个 numpy 数组/列表,如下所示:
---> 39 R = np.array(mean_data[:,0])
40 P = np.array(mean_data[:,1])
41 Z = np.array(mean_data[:,2])
When I try run the program I get the error:
当我尝试运行程序时,出现错误:
TypeError: list indices must be integers, not tuple
The mean_data list looks like this sample...
mean_data 列表看起来像这个示例...
[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.
我不知道如何防止此错误,我尝试将 mean_data 创建为 np.array 并使用 np.append 为其添加值,但这也不能解决问题。
Here's the traceback (was using ipython before)
这是回溯(之前使用过 ipython)
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
采纳答案by mbattifarano
The variable mean_datais 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].
该变量mean_data是一个嵌套列表,在 Python 中访问嵌套列表不能通过多维切片来完成,即:mean_data[1,2],而是写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.
这是因为mean_data[2]是一个列表。进一步的索引是递归完成的 - 因为mean_data[2]是一个列表,所以是该列表mean_data[2][0]的第一个索引。
Additionally, mean_data[:][0]does not work because mean_data[:]returns mean_data.
此外,mean_data[:][0]不起作用,因为mean_data[:]返回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.
numpy 数组(类似于 MATLAB 数组,而不是嵌套列表)支持使用元组进行多维切片。
回答by gcbirzan
np.append needs the array as the first argument and the list you want to append as the second:
np.append 需要将数组作为第一个参数,将要附加的列表作为第二个参数:
mean_data = np.append(mean_data, [ur, ua, np.mean(data[samepoints,-1])])
回答by lmsteffan
import numpy as np
mean_data = np.array([
[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]])
R = mean_data[:,0]
print R
print R.shape
EDIT
编辑
The reason why you had an invalid indexerror is the lack of a comma between mean_dataand the values you wanted to add.
出现invalid index错误的原因是mean_data您要添加的值之间缺少逗号。
Also, np.append returns a copy of the array, and does not change the original array. From the documentation :
此外, np.append 返回数组的副本,并且不会更改原始数组。从文档:
Returns : append : ndarray
A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.
返回:追加:ndarray
将值附加到轴的 arr 副本。请注意,追加不会就地发生:分配并填充一个新数组。如果axis 为None,则out 是一个扁平数组。
So you have to assign the np.appendresult to an array (could be mean_dataitself, I think), and, since you don't want a flattened array, you must also specify the axis on which you want to append.
因此,您必须将np.append结果分配给一个数组(mean_data我认为可以是它本身),并且,由于您不想要扁平数组,因此您还必须指定要附加的轴。
With that in mind, I think you could try something like
考虑到这一点,我认为你可以尝试类似
mean_data = np.append(mean_data, [[ur, ua, np.mean(data[samepoints,-1])]], axis=0)
Do have a look at the doubled [[and ]]: I think they are necessary since both arrays must have the same shape.
看看加倍的[[和]]:我认为它们是必要的,因为两个数组必须具有相同的形状。
回答by askewchan
You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.
您可能不需要制作列表并将它们附加到您的数组中。您可能一次完成所有操作,这样速度更快,因为您可以使用 numpy 来执行循环,而不是自己在纯 Python 中执行循环。
To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_datato an array before not after you try to slice it:
要回答你的问题,正如其他人所说,你不能像你那样访问带有两个索引的嵌套列表。如果mean_data在尝试切片之后先转换为数组,则可以:
R = np.array(mean_data)[:,0]
instead of
代替
R = np.array(mean_data[:,0])
But, assuming mean_data has a shape nx3, instead of
但是,假设 mean_data 有一个 shape nx3,而不是
R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]
You can simply do
你可以简单地做
A = np.array(mean_data).mean(axis=0)
which averages over the 0th axis and returns a length-narray
它在第0th 轴上取平均值并返回一个长度n数组
But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:
但就我最初的观点而言,我将编造一些数据来尝试说明如何在不一次构建任何列表的情况下执行此操作:
回答by Fabio Sungurlian
Just if someone is having this issue and hadn't done list[index, sub-index], you could be having the problem because you're missing a comma between to arrays in an array of arrays (It happened to me).
只是如果有人遇到这个问题并且没有做list[index, sub-index],你可能会遇到这个问题,因为你在数组数组中的数组之间缺少一个逗号(它发生在我身上)。

