Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python np.nditer引用类型的返回类型_Python_Numpy_Matplotlib_Data Science - Fatal编程技术网

Python np.nditer引用类型的返回类型

Python np.nditer引用类型的返回类型,python,numpy,matplotlib,data-science,Python,Numpy,Matplotlib,Data Science,如何为np.nditer获取正确的返回类型?我需要在这里遍历ax对象: fig, ax = plt.subplots(figsize=(16,9), ncols=3, nrows=2) for col, elem in zip(df.columns[:-1], np.nditer(ax, flags = ['refs_ok'])): sns.countplot(x="CLASS", hue=col, data=df, ax=elem) 我知道我可以在这里使用ax数组的维度进行迭代,但我

如何为np.nditer获取正确的返回类型?我需要在这里遍历
ax
对象:

fig, ax = plt.subplots(figsize=(16,9), ncols=3, nrows=2)
for col, elem in zip(df.columns[:-1], np.nditer(ax, flags = ['refs_ok'])):
    sns.countplot(x="CLASS", hue=col, data=df, ax=elem)
我知道我可以在这里使用ax数组的维度进行迭代,但我想知道,我是否可以使这项工作正常。基本上,
ax=elem
在迭代中应该看起来像
ax=ax[i][j]
。但事实证明它们有不同的类型:

print(type(elem))
print(type(ax[0][0]))
返回:

<class 'numpy.ndarray'>
<class 'matplotlib.axes._subplots.AxesSubplot'>

像这样使用
numpy
函数的问题是,它会立即将iterable转换为
np.ndarray
对象

因此,您的返回值将是这个
np.ndarray
对象的一个片段。请看下面的示例

In [472]: list(np.nditer([[None, None], [None, None]], flags = ['refs_ok']))
Out[472]:
[(array(None, dtype=object), array(None, dtype=object)),
 (array(None, dtype=object), array(None, dtype=object))]

In [473]: list(np.nditer([[None, None], [None, None]], flags = ['refs_ok']))[0][0]
Out[473]: array(None, dtype=object)
如果要从0维
numpy
数组中获取原始项,请使用
.tolist()
方法


正如您现在可能已经意识到的,由于您没有迭代数值类型,因此引入所有这些
numpy
复杂性和开销是没有意义的。正确的方法是

fig, ax = plt.subplots(figsize=(16,9), ncols=3, nrows=2)
for col, elem in zip(df.columns[:-1], ax.flat):
    sns.countplot(x="CLASS", hue=col, data=df, ax=elem)

它较短,并且总是使
元素成为
matplotlib.axes.\u subPlot.AxesSubplot
对象。

nditer
是一个专门的迭代器,大多数
numpy
工作都不需要它。正如您所发现的,它生成数组(单个元素0d)
elem.item()
可能是
ax[0,0]
。但是被接受的答案使用的
ax.flat
是一个更好的迭代器。