Pandas: NameError: el nombre '_converter' no está definido

Creado en 21 feb. 2018  ·  11Comentarios  ·  Fuente: pandas-dev/pandas

Ejemplo de código, un ejemplo que se puede copiar, si es posible

import pandas
d = pandas.DataFrame({"lat": [-6.081690, -5.207080], "lon": [145.789001, 145.391998]})
d.plot(kind='scatter', x='lat', y='lon')

Descripción del problema

NameError                                 Traceback (most recent call last)
<ipython-input-4-f42fef061f30> in <module>()
      1 import pandas
      2 d = pandas.DataFrame({"lat": [-6.081690, -5.207080], "lon": [145.789001, 145.391998]})
----> 3 d.plot(kind='scatter', x='lat', y='lon')

~/.local/lib/python3.6/site-packages/pandas/plotting/_core.py in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   2675                           fontsize=fontsize, colormap=colormap, table=table,
   2676                           yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 2677                           sort_columns=sort_columns, **kwds)
   2678     __call__.__doc__ = plot_frame.__doc__
   2679 

~/.local/lib/python3.6/site-packages/pandas/plotting/_core.py in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   1900                  yerr=yerr, xerr=xerr,
   1901                  secondary_y=secondary_y, sort_columns=sort_columns,
-> 1902                  **kwds)
   1903 
   1904 

~/.local/lib/python3.6/site-packages/pandas/plotting/_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
   1685         if isinstance(data, DataFrame):
   1686             plot_obj = klass(data, x=x, y=y, subplots=subplots, ax=ax,
-> 1687                              kind=kind, **kwds)
   1688         else:
   1689             raise ValueError("plot kind %r can only be used for data frames"

~/.local/lib/python3.6/site-packages/pandas/plotting/_core.py in __init__(self, data, x, y, s, c, **kwargs)
    835             # the handling of this argument later
    836             s = 20
--> 837         super(ScatterPlot, self).__init__(data, x, y, s=s, **kwargs)
    838         if is_integer(c) and not self.data.columns.holds_integer():
    839             c = self.data.columns[c]

~/.local/lib/python3.6/site-packages/pandas/plotting/_core.py in __init__(self, data, x, y, **kwargs)
    802 
    803     def __init__(self, data, x, y, **kwargs):
--> 804         MPLPlot.__init__(self, data, **kwargs)
    805         if x is None or y is None:
    806             raise ValueError(self._kind + ' requires and x and y column')

~/.local/lib/python3.6/site-packages/pandas/plotting/_core.py in __init__(self, data, kind, by, subplots, sharex, sharey, use_index, figsize, grid, legend, rot, ax, fig, title, xlim, ylim, xticks, yticks, sort_columns, fontsize, secondary_y, colormap, table, layout, **kwds)
     98                  table=False, layout=None, **kwds):
     99 
--> 100         _converter._WARN = False
    101         self.data = data
    102         self.by = by

NameError: name '_converter' is not defined

Salida de pd.show_versions()

VERSIONES INSTALADAS

cometer: Ninguno
python: 3.6.4.final.0
bits de pitón: 64
SO: Linux
Versión del SO: 4.14.0-3-amd64
máquina: x86_64
procesador:
byteorder: pequeño
LC_ALL: Ninguno
IDIOMA: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.22.0
pytest: Ninguno
pip: 9.0.1
herramientas de configuración: 38.5.1
Cython: Ninguno
numpy: 1.14.1
scipy: 0.19.1
pyarrow: Ninguno
xarray: Ninguno
IPython: 6.2.1
esfinge: 1.6.6
patsy: Ninguno
dateutil: 2.6.1
pytz: 2018.3
blosc: Ninguno
cuello de botella: Ninguno
tablas: ninguna
numexpr: Ninguno
pluma: ninguna
matplotlib: Ninguno
openpyxl: Ninguno
xlrd: Ninguno
xlwt: Ninguno
xlsxwriter: Ninguno
lxml: Ninguno
bs4: Ninguno
html5lib: 0.999999999
sqlalchemy: Ninguno
pymysql: Ninguno
psycopg2: Ninguno
jinja2: 2.10
s3fs: Ninguno
fastparquet: Ninguno
pandas_gbq: Ninguno
pandas_datareader: Ninguno

Blocker Error Reporting Visualization

Comentario más útil

Experimenté esto en Jupyter Notebook. Instaló matplotlib , lo importó y reimportó pandas después, la excepción no desapareció. Reinició el portátil y se arregló. Parece que algún estado global no se reinicializa.

Todos 11 comentarios

Esto es causado por la falta de matplotlib:

>>> from pandas.plotting import _converter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/whitequark/.local/lib/python3.6/site-packages/pandas/plotting/_converter.py", line 8, in <module>
    import matplotlib.units as units
ModuleNotFoundError: No module named 'matplotlib'

El error debería ser más útil.

Entonces este es un duplicado de https://github.com/pandas-dev/pandas/issues/19340 , y el problema es que no podemos reproducirlo. Se muestra claramente para varias personas, pero necesitamos diagnosticar por qué sucede esto.

¿Puede ejecutar el código en https://github.com/pandas-dev/pandas/issues/19340#issuecomment -359416261 y verificar si falla?

Seguro:

>>> from pandas.plotting._misc import (scatter_matrix, radviz,
...                                    andrews_curves, bootstrap_plot,
...                                    parallel_coordinates, lag_plot,
...                                    autocorrelation_plot)
>>> from pandas.plotting._core import boxplot
>>> from pandas.plotting._style import plot_params
>>> from pandas.plotting._tools import table
>>>
>>> from pandas.plotting._converter import \
...     register as register_matplotlib_converters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/whitequark/.local/lib/python3.6/site-packages/pandas/plotting/_converter.py", line 8, in <module>
    import matplotlib.units as units
ModuleNotFoundError: No module named 'matplotlib'
>>> from pandas.plotting._converter import \
...     deregister as deregister_matplotlib_converters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/whitequark/.local/lib/python3.6/site-packages/pandas/plotting/_converter.py", line 8, in <module>
    import matplotlib.units as units
ModuleNotFoundError: No module named 'matplotlib'

Ah, de hecho puedo reproducir esto, y supongo que se debe a

https://github.com/pandas-dev/pandas/blob/f8dfcfb35ca975575dcfba625eac6c9f231c0e5e/pandas/plotting/_core.py#L44 -L50

donde importamos _converter , que luego se usa en el archivo, pero luego no genera un buen mensaje de error cuando matplotlib no está disponible.

Sí, esto ciertamente debería resolverse.

También recibo el mismo error al aprender el curso de pandas de Google.
Estoy usando python3.6
y el sistema informático es mac osx 11

>>> import pandas as pd
>>> pd.__version__
'0.22.0'
>>> california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/ml_universities/california_housing_train.csv", sep=",")
>>> california_housing_dataframe.head()
   longitude  latitude  housing_median_age  total_rooms  total_bedrooms  \
0    -114.31     34.19                15.0       5612.0          1283.0   
1    -114.47     34.40                19.0       7650.0          1901.0   
2    -114.56     33.69                17.0        720.0           174.0   
3    -114.57     33.64                14.0       1501.0           337.0   
4    -114.57     33.57                20.0       1454.0           326.0   

   population  households  median_income  median_house_value  
0      1015.0       472.0         1.4936             66900.0  
1      1129.0       463.0         1.8200             80100.0  
2       333.0       117.0         1.6509             85700.0  
3       515.0       226.0         3.1917             73400.0  
4       624.0       262.0         1.9250             65500.0  
>>> california_housing_dataframe.hist('housing_median_age')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/pandas/plotting/_core.py", line 2160, in hist_frame
    _converter._WARN = False
NameError: name '_converter' is not defined

Experimenté esto en Jupyter Notebook. Instaló matplotlib , lo importó y reimportó pandas después, la excepción no desapareció. Reinició el portátil y se arregló. Parece que algún estado global no se reinicializa.

Experimenté esto en Jupyter Notebook. Instaló matplotlib, lo importó y luego reimporté pandas, la excepción no desapareció. Reinició el portátil y se arregló. Parece que algún estado global no se reinicializa.

@megaserg para verificar de manera confiable las importaciones con Python, siempre debe reiniciar el proceso de Python.
Pero de todos modos, esto es un error y tenemos que arreglarlo para la próxima versión.

@tonyshare me encontré con la misma pregunta, ¿cómo la resuelves?

@ Ako520 Instalando matplotlib. Esto se solucionará en la próxima versión de pandas.

La solución es reiniciar el kernel o reiniciar el servidor jupyter

reiniciar el kernel no me funciona

¿Fue útil esta página
0 / 5 - 0 calificaciones