Does anyone know what to do with this error? TypeError: unhashable type: 'numpy.ndarray'

Viewed 50

we got following instructions from our class:

It seems, that other people can do it, but there are no other steps mentioned, what did I do wrong?

import pandas as pd
import numpy as np
house1 = pd.read_csv("House1.csv")
house1.set_index('tstp', drop=True, inplace=True)
# replace 'Null' String with proper built-in NaN
house1.replace('Null', np.nan, inplace=True)

either: 
house1.dropna(axis=0, inplace=True) 
house1.dropna(axis=1, inplace=True)

or 
house1.fillna(42, inplace=True) #guess

#replace NaN with last valid entry in the column
house1.fillna(method='ffill', inplace=True)

#Or fill with mean or median

plt.plot(house1, label="Original") #Here I get the error.


I searched online and found out, that there is something wrong, that I would need to convert it first,.... Problem: I don't know how. Anyone have an idea? Thanks so much always!

1 Answers

There are a couple of ways to fix this issue, that have been suggested on the comments already:

Option 1

Specify the x, and y arguments of plt.plot:

plt.plot(x=house1['SOME_COL'], y=house1['SOME_OTHER_COL'], label="Original")
plt.show()

# Or:

plt.plot('SOME_COL', 'SOME_OTHER_COL', data=house1, label="Original")
plt.show()

For example

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

house1 = pd.DataFrame({'tstp': [1, 2, 3, 4], 'a': ['a', 'Null', 'b', 'a'], 'b': [10, 10, 20, 30]})
house1.set_index('tstp', drop=True, inplace=True)
house1.replace('Null', np.nan, inplace=True)
house1.dropna(axis=0, inplace=True) 
house1.dropna(axis=1, inplace=True)

plt.plot(house1['a'], house1['b'], label="Original")
plt.show()

Outputs:

Example output

If I didn't specify the x and y I would receive the same error as you did:

plt.plot(house1)

TypeError                                 Traceback (most recent call last)
<ipython-input-56-bd9f7a34c87b> in <module>
----> 1 plt.plot(house1)

7 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   2761     return gca().plot(
   2762         *args, scalex=scalex, scaley=scaley, **({"data": data} if data
-> 2763         is not None else {}), **kwargs)
   2764 
   2765 

/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1645         """
   1646         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1647         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1648         for line in lines:
   1649             self.add_line(line)

/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_base.py in __call__(self, *args, **kwargs)
    214                 this += args[0],
    215                 args = args[1:]
--> 216             yield from self._plot_args(this, kwargs)
    217 
    218     def get_next_color(self):

/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
    337             self.axes.xaxis.update_units(x)
    338         if self.axes.yaxis is not None:
--> 339             self.axes.yaxis.update_units(y)
    340 
    341         if x.shape[0] != y.shape[0]:

/usr/local/lib/python3.7/dist-packages/matplotlib/axis.py in update_units(self, data)
   1514         neednew = self.converter != converter
   1515         self.converter = converter
-> 1516         default = self.converter.default_units(data, self)
   1517         if default is not None and self.units is None:
   1518             self.set_units(default)

/usr/local/lib/python3.7/dist-packages/matplotlib/category.py in default_units(data, axis)
    105         # the conversion call stack is default_units -> axis_info -> convert
    106         if axis.units is None:
--> 107             axis.set_units(UnitData(data))
    108         else:
    109             axis.units.update(data)

/usr/local/lib/python3.7/dist-packages/matplotlib/category.py in __init__(self, data)
    173         self._counter = itertools.count()
    174         if data is not None:
--> 175             self.update(data)
    176 
    177     @staticmethod

/usr/local/lib/python3.7/dist-packages/matplotlib/category.py in update(self, data)
    208         # check if convertible to number:
    209         convertible = True
--> 210         for val in OrderedDict.fromkeys(data):
    211             # OrderedDict just iterates over unique values in data.
    212             cbook._check_isinstance((str, bytes), value=val)

TypeError: unhashable type: 'numpy.ndarray'

Note

If all the columns from your dataframe had numeric values, your code would work fine:

house2 = pd.DataFrame({'a': [10, 10, 20, 30], 'b': [10, 10, 20, 30], 'tstp': [1, 2, 3, 4]})
plt.plot(house2)
plt.show()

enter image description here

Option 2

Use the plot method that comes with pandas.DataFrame class. The pandas.DataFrame.plot filters out any non-numeric columns before trying to plot your data.

Example

house1.plot()

enter image description here

Related