首页 > 解决方案 > AttributeError:“numpy.ndarray”对象没有属性“get”

问题描述

实际上,我正在尝试使用 seaborn 库为形状为 (5216,1) 的 numpy 数组绘制计数图。当我这样尝试时

train_y.shape
sns.set(style="darkgrid")
ax = sns.countplot(x="class", data=train_y)

But it throughs out like this

AttributeError                            Traceback (most recent call last)
<ipython-input-33-44c4401caea5> in <module>
    1 sns.set(style="darkgrid")
----> 2 ax = sns.countplot(x="class", data=train_y)

/opt/conda/lib/python3.7/site-packages/seaborn/categorical.py in countplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, dodge, ax, **kwargs)
 3553                           estimator, ci, n_boot, units, seed,
 3554                           orient, color, palette, saturation,
-> 3555                           errcolor, errwidth, capsize, dodge)
 3556 
 3557     plotter.value_label = "count"

/opt/conda/lib/python3.7/site-packages/seaborn/categorical.py in __init__(self, x, y, hue, data, order, hue_order, estimator, ci, n_boot, units, seed, orient, color, palette, saturation, errcolor, errwidth, capsize, dodge)
 1613         """Initialize the plotter."""
 1614         self.establish_variables(x, y, hue, data, orient,
-> 1615                                  order, hue_order, units)
 1616         self.establish_colors(color, palette, saturation)
 1617         self.estimate_statistic(estimator, ci, n_boot, seed)

/opt/conda/lib/python3.7/site-packages/seaborn/categorical.py in establish_variables(self, x, y, hue, data, orient, order, hue_order, units)
  141             # See if we need to get variables from `data`
  142             if data is not None:
--> 143                 x = data.get(x, x)
  144                 y = data.get(y, y)
  145                 hue = data.get(hue, hue)

AttributeError: 'numpy.ndarray' object has no attribute 'get'

任何人都请帮我解决这个错误

标签: pythonnumpymatplotlibdata-visualizationseaborn

解决方案


如果您想使用numpy数组而不是 a pandas.Dataframe,您可以简单地将数组作为xory参数传递给countplot

例如

import numpy
import seaborn

data = numpy.array([1, 2, 2, 3, 3, 3])
ax = seaborn.countplot(x=data)

这似乎不适用于多维数组。如果不了解您正在绘制的数据的更多信息,很难确定如何生成您想要的特定图。但是,由于您的数组在第二维中只有长度 1,那么简单地将数组重新整形为一维怎么样?

例如

train_y.shape = len(train_y)
ax = sns.countplot(x=train_y)

顺便说一句,最好使用pandas.DataFrames而不是numpy.arrays. 文档中的示例(我假设您已尝试在此处模拟)使用DataFrames. 您可以将数组转换为 a DataFrame,并指定稍后要绘制的变量的名称。

例如

import numpy
import seaborn as sns
import pandas

data = numpy.array([1, 2, 2, 3, 3, 1, 1, 1, 2])
df = pandas.DataFrame(data=data, columns=["variable"])

这里,"variable"df“表”中列的名称。然后,当您使用 绘图时countplot,将此列指定为 的参数x

ax = sns.countplot(x="variable", data=df)

推荐阅读