尝试从数据集创建散点图时,TypeError:无法散列的类型:'numpy.ndarray'

时间:2019-05-01 22:09:38

标签: python pandas numpy matplotlib

我正在尝试使用电影上的数据集创建散点图。目的是查看不同类别与目标变量之间的相关性,无论电影是否获得奖项。我尝试对变量进行类型调用,但它们都不属于numpy.ndarray类型,因为它们都是pandas数据帧,但在尝试创建散点图时仍然出现以下错误:

  

TypeError:不可哈希类型:'numpy.ndarray'

我的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

file=pd.read_csv('academy_awards.csv',sep=',',error_bad_lines=False,encoding="ISO 8859-1")
print(file)
df=pd.DataFrame(file)

#df=df.dropna(axis=0,how='any')
target=df.Category
X=pd.DataFrame(df.Won)

y=target
#print(type(X))
#print(type(y))

plt.scatter(X,y)

以下是我正在使用的数据集的前5行:

Year,Category,Nominee,Additional Info,Won
2010 (83rd),Actor -- Leading Role,Javier Bardem,Biutiful 
{'Uxbal'},NO
2010 (83rd),Actor -- Leading Role,Jeff Bridges,True Grit {'Rooster 
Cogburn'},NO
2010 (83rd),Actor -- Leading Role,Jesse Eisenberg,The Social 
Network {'Mark Zuckerberg'},NO
2010 (83rd),Actor -- Leading Role,Colin Firth,The King's Speech 
{'King George VI'},YES
2010 (83rd),Actor -- Leading Role,James Franco,127 Hours {'Aron 
Ralston'},NO
2010 (83rd),Actor -- Supporting Role,Christian Bale,The Fighter 
{'Dicky Eklund'},YES

任何帮助或建议,我们将不胜感激!

编辑: 以下是完整的回溯-

-----------------------------------------------------------------------
TypeError                                 Traceback (most recent call 
last)
<ipython-input-211-efcb7c41bca1> in <module>
     14 print(y.shape)
     15 
---> 16 plt.scatter(X,y)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/pyplot.py in scatter(x, y, s, c, marker, cmap, 
norm, vmin, vmax, alpha, linewidths, verts, edgecolors, data, **kwargs)
   2862         vmin=vmin, vmax=vmax, alpha=alpha, 
linewidths=linewidths,
   2863         verts=verts, edgecolors=edgecolors, **({"data": data} 
if data
-> 2864         is not None else {}), **kwargs)
   2865     sci(__ret)
   2866     return __ret

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1808                         "the Matplotlib list!)" % (label_namer, 
func.__name__),
   1809                         RuntimeWarning, stacklevel=2)
-> 1810             return func(ax, *args, **kwargs)
   1811 
   1812         inner.__doc__ = _add_data_doc(inner.__doc__,

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, 
cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
   4170             edgecolors = 'face'
   4171 
-> 4172         self._process_unit_info(xdata=x, ydata=y, 
kwargs=kwargs)
   4173         x = self.convert_xunits(x)
   4174         y = self.convert_yunits(y)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/axes/_base.py in _process_unit_info(self, xdata, 
ydata, kwargs)
   2133             return kwargs
   2134 
-> 2135         kwargs = _process_single_axis(xdata, self.xaxis, 
'xunits', kwargs)
   2136         kwargs = _process_single_axis(ydata, self.yaxis, 
'yunits', kwargs)
   2137         return kwargs

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/axes/_base.py in _process_single_axis(data, axis, 
unit_name, kwargs)
   2116                 # We only need to update if there is nothing 
set yet.
   2117                 if not axis.have_units():
-> 2118                     axis.update_units(data)
   2119 
   2120             # Check for units in the kwargs, and if present 
update axis

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/axis.py in update_units(self, data)
   1471         neednew = self.converter != converter
   1472         self.converter = converter
-> 1473         default = self.converter.default_units(data, self)
   1474         if default is not None and self.units is None:
   1475             self.set_units(default)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/category.py in default_units(data, axis)
    101         # default_units->axis_info->convert
    102         if axis.units is None:
--> 103             axis.set_units(UnitData(data))
    104         else:
    105             axis.units.update(data)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/category.py in __init__(self, data)
    167         self._counter = itertools.count()
    168         if data is not None:
--> 169             self.update(data)
    170 
    171     def update(self, data):

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
packages/matplotlib/category.py in update(self, data)
    184         data = np.atleast_1d(np.array(data, dtype=object))
    185 
--> 186         for val in OrderedDict.fromkeys(data):
    187             if not isinstance(val, (str, bytes)):
    188                 raise TypeError("{val!r} is not a 
string".format(val=val))

TypeError: unhashable type: 'numpy.ndarray'

2 个答案:

答案 0 :(得分:0)

数组是不可哈希的,因为它们是可变的。您可以通过将其转换为不可变的元组(用tuple()对其进行哈希处理)来进行哈希处理,但是您通常不应该尝试对数组进行哈希处理。您的数据可能格式错误。

答案 1 :(得分:0)

首先,您不需要:df=pd.DataFrame(file)。用熊猫打开CSV文件并将其保存在file变量中之后,您已经将数据作为dataFrame获得。

然后,您可以轻松调用scatter并使用来选择x轴和y轴

df.plot(kind ="scatter", x= "Won", y = "Category")

您不需要预处理数据,因为使用pandas打开文件后数据已经进行了预处理。