ValueError: invalid literal for float(): 17/08/2015 - python

I'm getting this error "ValueError: invalid literal for float(): 17/08/2015". This is the last row in the file I'm reading and it follows the same format as the others. The code for the script is below.
I'm wondering. Is the error actually occurring throughout the file but it's being flagged as the only error because it's the last of the errors, if that makes sense to anyone.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rankings = pd.read_csv('data/rankingunitsdata.csv', parse_dates='date')
rankings.plot('date','rankingpos')
x = rankings.date.values
y = rankings.rankingpos.values
plt.plot(x,y, 'o')
plt.xlabel('Ranking Position')
plt.ylabel('Date')
plt.show()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-b6d9eb0809d3> in <module>()
----> 1 plt.plot(x,y, 'o')
2 plt.xlabel('Ranking Position')
3 plt.ylabel('Date')
4 plt.show()
C:\Anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(*args, **kwargs)
3097 ax.hold(hold)
3098 try:
-> 3099 ret = ax.plot(*args, **kwargs)
3100 draw_if_interactive()
3101 finally:
C:\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, *args, **kwargs)
1372
1373 for line in self._get_lines(*args, **kwargs):
-> 1374 self.add_line(line)
1375 lines.append(line)
1376
C:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in add_line(self, line)
1502 line.set_clip_path(self.patch)
1503
-> 1504 self._update_line_limits(line)
1505 if not line.get_label():
1506 line.set_label('_line%d' % len(self.lines))
C:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _update_line_limits(self, line)
1513 Figures out the data limit of the given line, updating self.dataLim.
1514 """
-> 1515 path = line.get_path()
1516 if path.vertices.size == 0:
1517 return
C:\Anaconda3\lib\site-packages\matplotlib\lines.py in get_path(self)
872 """
873 if self._invalidy or self._invalidx:
--> 874 self.recache()
875 return self._path
876
C:\Anaconda3\lib\site-packages\matplotlib\lines.py in recache(self, always)
573 x = ma.asarray(xconv, np.float_)
574 else:
--> 575 x = np.asarray(xconv, np.float_)
576 x = x.ravel()
577 else:
C:\Anaconda3\lib\site-packages\numpy\core\numeric.py in asarray(a, dtype, order)
472
473 """
--> 474 return array(a, dtype, copy=False, order=order)
475
476 def asanyarray(a, dtype=None, order=None):
ValueError: could not convert string to float: '17/08/2015'

The error occurs because you are trying to plot some stuff with dates as strings on the x-axis while plt.plot() expects numerical values. Hence it fails when it tries to convert '17/08/2015' to a float, which cannot work.
You need to convert your x-values to datetime objects and then use plt.plot_date, which is for example demonstrated here.

Related

Issue with Trackpy - InvalidIndexError when fitting EMSD to a power law from the tutorial

possibly a silly problem, but I'm stuck and I'd really appreciate someone's help. I'm trying to replicate the examples given in the walkthrough tutorial for trackpy (https://soft-matter.github.io/trackpy/dev/tutorial/walkthrough.html). I've been succesful up until I got to the point where I had to fit the ensemble mean-squared displacement to a power law (In [34]):
plt.figure()
plt.ylabel(r'$\langle \Delta r^2 \rangle$ [$\mu$m$^2$]')
plt.xlabel('lag time $t$');
tp.utils.fit_powerlaw(em) # performs linear best fit in log space, plots]
This is the error message I get. Can someone suggest a solution?
Thanks!
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexes/base.py:3621, in Index.get_loc(self, key, method, tolerance)
3620 try:
-> 3621 return self._engine.get_loc(casted_key)
3622 except KeyError as err:
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas/_libs/index.pyx:136, in pandas._libs.index.IndexEngine.get_loc()
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas/_libs/index.pyx:142, in pandas._libs.index.IndexEngine.get_loc()
TypeError: '(slice(None, None, None), None)' is an invalid key
During handling of the above exception, another exception occurred:
InvalidIndexError Traceback (most recent call last)
Input In [178], in <cell line: 4>()
2 plt.ylabel(r'$\langle \Delta r^2 \rangle$ [$\mu$m$^2$]')
3 plt.xlabel('lag time $t$');
----> 4 tp.utils.fit_powerlaw(em)
File ~/opt/anaconda3/lib/python3.9/site-packages/trackpy/utils.py:50, in fit_powerlaw(data, plot, **kwargs)
48 if plot:
49 from trackpy import plots
---> 50 plots.fit(data, fits, logx=True, logy=True, legend=False, **kwargs)
51 return values
File ~/opt/anaconda3/lib/python3.9/site-packages/trackpy/plots.py:50, in make_axes.<locals>.wrapper(*args, **kwargs)
47 # Delete legend keyword so remaining ones can be passed to plot().
48 legend = kwargs.pop('legend', False)
---> 50 result = func(*args, **kwargs)
52 if legend:
53 handles, labels = kwargs['ax'].get_legend_handles_labels()
File ~/opt/anaconda3/lib/python3.9/site-packages/trackpy/plots.py:652, in fit(data, fits, inverted_model, logx, logy, ax, **kwargs)
650 ax.set_yscale('log')
651 if not inverted_model:
--> 652 fitlines = ax.plot(fits.index, fits, **kwargs)
653 else:
654 fitlines = ax.plot(fits.reindex(data.dropna().index),
655 data.dropna(), **kwargs)
File ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/axes/_axes.py:1632, in Axes.plot(self, scalex, scaley, data, *args, **kwargs)
1390 """
1391 Plot y versus x as lines and/or markers.
1392
(...)
1629 (``'green'``) or hex strings (``'#008000'``).
1630 """
1631 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1632 lines = [*self._get_lines(*args, data=data, **kwargs)]
1633 for line in lines:
1634 self.add_line(line)
File ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/axes/_base.py:312, in _process_plot_var_args.__call__(self, data, *args, **kwargs)
310 this += args[0],
311 args = args[1:]
--> 312 yield from self._plot_args(this, kwargs)
File ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/axes/_base.py:488, in _process_plot_var_args._plot_args(self, tup, kwargs, return_kwargs)
486 if len(xy) == 2:
487 x = _check_1d(xy[0])
--> 488 y = _check_1d(xy[1])
489 else:
490 x, y = index_of(xy[-1])
File ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/cbook/__init__.py:1327, in _check_1d(x)
1321 with warnings.catch_warnings(record=True) as w:
1322 warnings.filterwarnings(
1323 "always",
1324 category=Warning,
1325 message='Support for multi-dimensional indexing')
-> 1327 ndim = x[:, None].ndim
1328 # we have definitely hit a pandas index or series object
1329 # cast to a numpy array.
1330 if len(w) > 0:
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/frame.py:3505, in DataFrame.__getitem__(self, key)
3503 if self.columns.nlevels > 1:
3504 return self._getitem_multilevel(key)
-> 3505 indexer = self.columns.get_loc(key)
3506 if is_integer(indexer):
3507 indexer = [indexer]
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexes/base.py:3628, in Index.get_loc(self, key, method, tolerance)
3623 raise KeyError(key) from err
3624 except TypeError:
3625 # If we have a listlike key, _check_indexing_error will raise
3626 # InvalidIndexError. Otherwise we fall through and re-raise
3627 # the TypeError.
-> 3628 self._check_indexing_error(key)
3629 raise
3631 # GH#42269
File ~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/indexes/base.py:5637, in Index._check_indexing_error(self, key)
5633 def _check_indexing_error(self, key):
5634 if not is_scalar(key):
5635 # if key is not a scalar, directly raise an error (the code below
5636 # would convert to numpy arrays and raise later any way) - GH29926
-> 5637 raise InvalidIndexError(key)
InvalidIndexError: (slice(None, None, None), None)

Error using SMOTE TypeError: cannot safely cast non-equivalent float64 to int64

I'm preparing an unbalanced dataset and would like to use a Python package called SMOTE. When I try to run the code it shows up an error: TypeError: cannot safely cast non-equivalent float64 to int64
My dataset (first 5 rows):
Dataset
The error traceback:
TypeError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\arrays\integer.py in safe_cast(values, dtype, copy)
147 try:
--> 148 return values.astype(dtype, casting="safe", copy=copy)
149 except TypeError:
TypeError: Cannot cast array from dtype('float64') to dtype('int64') according to the rule 'safe'
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-456-c6d4d3314a06> in <module>
5
6 # transform the dataset
----> 7 X_smote, y_smote = pipeline.fit_resample(X, y)
8
9
~\anaconda3\lib\site-packages\imblearn\pipeline.py in fit_resample(self, X, y, **fit_params)
351 """
352 last_step = self._final_estimator
--> 353 Xt, yt, fit_params = self._fit(X, y, **fit_params)
354 with _print_elapsed_time('Pipeline',
355 self._log_message(len(self.steps) - 1)):
~\anaconda3\lib\site-packages\imblearn\pipeline.py in _fit(self, X, y, **fit_params)
234 )
235 elif hasattr(cloned_transformer, "fit_resample"):
--> 236 X, y, fitted_transformer = fit_resample_one_cached(
237 cloned_transformer, X, y,
238 message_clsname='Pipeline',
~\anaconda3\lib\site-packages\joblib\memory.py in __call__(self, *args, **kwargs)
350
351 def __call__(self, *args, **kwargs):
--> 352 return self.func(*args, **kwargs)
353
354 def call_and_shelve(self, *args, **kwargs):
~\anaconda3\lib\site-packages\imblearn\pipeline.py in _fit_resample_one(sampler, X, y, message_clsname, message, **fit_params)
401 **fit_params):
402 with _print_elapsed_time(message_clsname, message):
--> 403 X_res, y_res = sampler.fit_resample(X, y, **fit_params)
404
405 return X_res, y_res, sampler
~\anaconda3\lib\site-packages\imblearn\base.py in fit_resample(self, X, y)
86 if binarize_y else output[1])
87
---> 88 X_, y_ = arrays_transformer.transform(output[0], y_)
89 return (X_, y_) if len(output) == 2 else (X_, y_, output[2])
90
~\anaconda3\lib\site-packages\imblearn\utils\_validation.py in transform(self, X, y)
38
39 def transform(self, X, y):
---> 40 X = self._transfrom_one(X, self.x_props)
41 y = self._transfrom_one(y, self.y_props)
42 return X, y
~\anaconda3\lib\site-packages\imblearn\utils\_validation.py in _transfrom_one(self, array, props)
57 import pandas as pd
58 ret = pd.DataFrame(array, columns=props["columns"])
---> 59 ret = ret.astype(props["dtypes"])
60 elif type_ == "series":
61 import pandas as pd
~\anaconda3\lib\site-packages\pandas\core\generic.py in astype(self, dtype, copy, errors)
5681 if col_name in dtype:
5682 results.append(
-> 5683 col.astype(dtype=dtype[col_name], copy=copy, errors=errors)
5684 )
5685 else:
~\anaconda3\lib\site-packages\pandas\core\generic.py in astype(self, dtype, copy, errors)
5696 else:
5697 # else, only a single dtype is given
-> 5698 new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors)
5699 return self._constructor(new_data).__finalize__(self)
5700
~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in astype(self, dtype, copy, errors)
580
581 def astype(self, dtype, copy: bool = False, errors: str = "raise"):
--> 582 return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
583
584 def convert(self, **kwargs):
~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in apply(self, f, filter, **kwargs)
440 applied = b.apply(f, **kwargs)
441 else:
--> 442 applied = getattr(b, f)(**kwargs)
443 result_blocks = _extend_blocks(applied, result_blocks)
444
~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in astype(self, dtype, copy, errors)
623 vals1d = values.ravel()
624 try:
--> 625 values = astype_nansafe(vals1d, dtype, copy=True)
626 except (ValueError, TypeError):
627 # e.g. astype_nansafe can fail on object-dtype of strings
~\anaconda3\lib\site-packages\pandas\core\dtypes\cast.py in astype_nansafe(arr, dtype, copy, skipna)
819 # dispatch on extension dtype if needed
820 if is_extension_array_dtype(dtype):
--> 821 return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy)
822
823 if not isinstance(dtype, np.dtype):
~\anaconda3\lib\site-packages\pandas\core\arrays\integer.py in _from_sequence(cls, scalars, dtype, copy)
352 #classmethod
353 def _from_sequence(cls, scalars, dtype=None, copy=False):
--> 354 return integer_array(scalars, dtype=dtype, copy=copy)
355
356 #classmethod
~\anaconda3\lib\site-packages\pandas\core\arrays\integer.py in integer_array(values, dtype, copy)
133 TypeError if incompatible types
134 """
--> 135 values, mask = coerce_to_array(values, dtype=dtype, copy=copy)
136 return IntegerArray(values, mask)
137
~\anaconda3\lib\site-packages\pandas\core\arrays\integer.py in coerce_to_array(values, dtype, mask, copy)
249 values = safe_cast(values, dtype, copy=False)
250 else:
--> 251 values = safe_cast(values, dtype, copy=False)
252
253 return values, mask
~\anaconda3\lib\site-packages\pandas\core\arrays\integer.py in safe_cast(values, dtype, copy)
153 return casted
154
--> 155 raise TypeError(
156 f"cannot safely cast non-equivalent {values.dtype} to {np.dtype(dtype)}"
157 )
TypeError: cannot safely cast non-equivalent float64 to int64
X = new_dataset_enc.drop(['stroke'], axis=1)
y = new_dataset_enc['stroke']
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
from imblearn.pipeline import Pipeline
from collections import Counter
num_before = dict(Counter(y))
over = SMOTE(sampling_strategy=0.8)
under = RandomUnderSampler(sampling_strategy=0.8)
steps = [('o', over), ('u', under)]
pipeline = Pipeline(steps=steps)
# transform the dataset
X_smote, y_smote = pipeline.fit_resample(X, y)
# the numbers after SMOTE
num_after =dict(Counter(y_smote))
I have already tried several ways to fix it, but the issue keeps showing up. There are no "NaN" values in columns or missing ones. I've changed the type of each column to int64 and to object to test if that could fix the error. Nothing works.
Appreciate a lot any idea to come up with a solution.
I face the same issue. my solution is similar with Tim's suggestion which is adding:
y = y.astype(np.float64)
but it's not enough for me since it return the same error.
It works when I also convert the x to float64 like:
X = X.astype(np.float64)
right after your first two code line

Pandas returns error: 'Series' objects are mutable, thus they cannot be hashed

I have a problem here, I was trying to find a specific value in my data frame. However I have received this error:
TypeError Traceback (most recent call last)
<ipython-input-245-ded282cec75c> in <module>
----> 1 data.iloc(data['Amount'] == '11,99')
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in __call__(self, axis)
576
577 if axis is not None:
--> 578 axis = self.obj._get_axis_number(axis)
579 new_self.axis = axis
580 return new_self
~\Anaconda3\lib\site-packages\pandas\core\generic.py in _get_axis_number(cls, axis)
396 #classmethod
397 def _get_axis_number(cls, axis):
--> 398 axis = cls._AXIS_ALIASES.get(axis, axis)
399 if is_integer(axis):
400 if axis in cls._AXIS_NAMES:
~\Anaconda3\lib\site-packages\pandas\core\generic.py in __hash__(self)
1796
1797 def __hash__(self):
-> 1798 raise TypeError(
1799 f"{repr(type(self).__name__)} objects are mutable, "
1800 f"thus they cannot be hashed"
TypeError: 'Series' objects are mutable, thus they cannot be hashed
How can I proceed?
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv('Data.csv', sep = ';')
data.iloc(data['Amount'] == '11,99')
Use data[data['Amount'] == '11,99']
It should work just fine..!

category_encoders: TargetEncoder error "TypeError: Categorical cannot perform the operation mean"

I'm getting the below error when I try to target encode a categorical column.
"TypeError: Categorical cannot perform the operation mean"
When I try to run similar code through Jupyter Notebook it works fine but when I try to run it as part of python file it errors out with the above error message.
I know this sounds a bit crazy but I am not able to understand what's going on in the background?
Error:
TypeError Traceback (most recent call last)
<ipython-input-4-9ba53c6b7375> in <module>()
----> 1 tpmodeller.initialize()
~/SageMaker/tp/tp_kvr.py in initialize(self)
127
128 # Target Encode Te_cat_col Features
--> 129 df_cat_te = target_encode_bin(self.train[self.Te_cat_col], self.train['vol_trmnt_in_4_quarters'])
130 self.train = pd.concat([self.train, df_cat_te], axis=1)
131
~/SageMaker/tp/tp_kvr.py in target_encode_bin(df_te, target)
366 te = TargetEncoder(smoothing = 1, min_samples_leaf = 5, handle_unknown='ignore')
--> 367 df_te = te.fit_transform(df_te, target)
368 #
369 # Binning and then placing it in {col}_bin feature
~/anaconda3/envs/python3/lib/python3.6/site-packages/category_encoders/target_encoder.py in fit_transform(self, X, y, **fit_params)
249 transform(X)
250
--> 251 return self.fit(X, y, **fit_params).transform(X, y)
252
~/anaconda3/envs/python3/lib/python3.6/site-packages/category_encoders/target_encoder.py in fit(self, X, y, **kwargs)
138 self.ordinal_encoder = self.ordinal_encoder.fit(X)
139 X_ordinal = self.ordinal_encoder.transform(X)
--> 140 self.mapping = self.fit_target_encoding(X_ordinal, y)
141
142 X_temp = self.transform(X, override_return_df=True)
~/anaconda3/envs/python3/lib/python3.6/site-packages/category_encoders/target_encoder.py in fit_target_encoding(self, X, y)
164 values = switch.get('mapping')
165
--> 166 prior = self._mean = y.mean()
167
168 stats = y.groupby(X[col]).agg(['count', 'mean'])
~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/generic.py in stat_func(self, axis, skipna, level, numeric_only, **kwargs)
10954 skipna=skipna)
10955 return self._reduce(f, name, axis=axis, skipna=skipna,
> 10956 numeric_only=numeric_only)
10957
10958 return set_function_name(stat_func, name, cls)
~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/series.py in _reduce(self, op, name, axis, skipna, numeric_only, filter_type, **kwds)
3614 # TODO deprecate numeric_only argument for Categorical and use
3615 # skipna as well, see GH25303
-> 3616 return delegate._reduce(name, numeric_only=numeric_only, **kwds)
3617 elif isinstance(delegate, ExtensionArray):
3618 # dispatch to ExtensionArray interface
~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/arrays/categorical.py in _reduce(self, name, axis, **kwargs)
2170 if func is None:
2171 msg = 'Categorical cannot perform the operation {op}'
-> 2172 raise TypeError(msg.format(op=name))
2173 return func(**kwargs)
2174
TypeError: Categorical cannot perform the operation mean
Your target feature needs to be converted to a 'number' type.

TypeError: unhashable type: 'numpy.ndarray' with Pandas after importing data from MYSQL

I ran the same program on two different data sources (a CSV file & MYSQL database), CSV import runs fine but MYSQL import throws the numpy type error:
I'm guessing issue may lie with these 2 points:
1. Data import issues - INT, TEXT etc? I'm using VARCHAR for the data.
2. Issue with how matplotlib works with Panda dataframes?
I'm new so please treat me as one :)
import pandas as pd
import numpy as np
import matplotlib.pyplot as pp
import seaborn
from sqlalchemy import create_engine
import pymysql
engine = create_engine("mysql+pymysql://root:root#127.0.0.1:3306/babynames",echo=False)
names = pd.read_sql_query('select * from BABYNAMES',engine)
names_indexed = names.set_index(['gender','name','year']).sort_index()
def plotname(gender, name):
data = names_indexed.loc[gender, name]
pp.plot(data.index, data.values)
plotname('F','Nancy')
Error code:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-9d981bcf8365> in <module>()
----> 1 plotname('F','Nancy')
<ipython-input-31-85c728659ad0> in plotname(gender, name)
1 def plotname(gender, name):
2 data = allyears_indexed.loc[gender, name]
----> 3 pp.plot(data.index, data.values)
~/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in plot(*args, **kwargs)
3361 mplDeprecation)
3362 try:
-> 3363 ret = ax.plot(*args, **kwargs)
3364 finally:
3365 ax._hold = washold
~/anaconda3/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
1865 "the Matplotlib list!)" % (label_namer, func.__name__),
1866 RuntimeWarning, stacklevel=2)
-> 1867 return func(ax, *args, **kwargs)
1868
1869 inner.__doc__ = _add_data_doc(inner.__doc__,
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in plot(self, *args, **kwargs)
1526 kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
1527
-> 1528 for line in self._get_lines(*args, **kwargs):
1529 self.add_line(line)
1530 lines.append(line)
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in _grab_next_args(self, *args, **kwargs)
404 this += args[0],
405 args = args[1:]
--> 406 for seg in self._plot_args(this, kwargs):
407 yield seg
408
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
381 x, y = index_of(tup[-1])
382
--> 383 x, y = self._xy_from_xy(x, y)
384
385 if self.command == 'plot':
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
214 if self.axes.xaxis is not None and self.axes.yaxis is not None:
215 bx = self.axes.xaxis.update_units(x)
--> 216 by = self.axes.yaxis.update_units(y)
217
218 if self.command != 'plot':
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in update_units(self, data)
1467 neednew = self.converter != converter
1468 self.converter = converter
-> 1469 default = self.converter.default_units(data, self)
1470 if default is not None and self.units is None:
1471 self.set_units(default)
~/anaconda3/lib/python3.7/site-packages/matplotlib/category.py in default_units(data, axis)
113 # default_units->axis_info->convert
114 if axis.units is None:
--> 115 axis.set_units(UnitData(data))
116 else:
117 axis.units.update(data)
~/anaconda3/lib/python3.7/site-packages/matplotlib/category.py in __init__(self, data)
180 self._counter = itertools.count(start=0)
181 if data is not None:
--> 182 self.update(data)
183
184 def update(self, data):
~/anaconda3/lib/python3.7/site-packages/matplotlib/category.py in update(self, data)
197 data = np.atleast_1d(np.array(data, dtype=object))
198
--> 199 for val in OrderedDict.fromkeys(data):
200 if not isinstance(val, VALID_TYPES):
201 raise TypeError("{val!r} is not a string".format(val=val))
TypeError: unhashable type: 'numpy.ndarray'
I was right, the issue was with the data types. I created a new table replacing VARCHAR for INT and then used the same code from above and the program worked perfectly.

Categories