Попытка построить подзаговоры, но получить их пустыми - PullRequest
1 голос
/ 10 апреля 2020

Попытка построить подзаговоры для сравнения 3 разных столбцов, но отображается пустым. Все необходимые библиотеки импортируются, и используемые имена столбцов также совпадают с именами в файле .csv. Ниже приведен код, который я использовал. У меня нет разрешения на прикрепление изображения пустых участков, поэтому я разместил ссылку ниже.

# visualize the relationship between the features and the response using scatterplots
fig, axs = plt.subplots(1, 3, sharey=True)
data.plot(kind='scatter', x='TV', y='sales', ax=axs[0], figsize=(16, 8))
data.plot(kind='scatter', x='radio', y='sales', ax=axs[1])
data.plot(kind='scatter', x='newspaper', y='sales', ax=axs[2])

, которая дает

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\Users\kanks\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2896             try:
-> 2897                 return self._engine.get_loc(key)
   2898             except KeyError:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'TV'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-8-f7be7f05c794> in <module>
      1 # visualize the relationship between the features and the response using scatterplots
      2 fig, axs = plt.subplots(1, 3, sharey=True)
----> 3 data.plot(kind='scatter', x='TV', y='sales', ax=axs[0], figsize=(16, 8))
      4 data.plot(kind='scatter', x='radio', y='sales', ax=axs[1])
      5 data.plot(kind='scatter', x='newspaper', y='sales', ax=axs[2])

C:\Users\kanks\Anaconda3\lib\site-packages\pandas\plotting\_core.py in __call__(self, *args, **kwargs)
    736         if kind in self._dataframe_kinds:
    737             if isinstance(data, ABCDataFrame):
--> 738                 return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs)
    739             else:
    740                 raise ValueError(

C:\Users\kanks\Anaconda3\lib\site-packages\pandas\plotting\_matplotlib\__init__.py in plot(data, kind, **kwargs)
     59                 ax = plt.gca()
     60             kwargs["ax"] = getattr(ax, "left_ax", ax)
---> 61     plot_obj = PLOT_CLASSES[kind](data, **kwargs)
     62     plot_obj.generate()
     63     plot_obj.draw()

C:\Users\kanks\Anaconda3\lib\site-packages\pandas\plotting\_matplotlib\core.py in __init__(self, data, x, y, s, c, **kwargs)
    928             # the handling of this argument later
    929             s = 20
--> 930         super().__init__(data, x, y, s=s, **kwargs)
    931         if is_integer(c) and not self.data.columns.holds_integer():
    932             c = self.data.columns[c]

C:\Users\kanks\Anaconda3\lib\site-packages\pandas\plotting\_matplotlib\core.py in __init__(self, data, x, y, **kwargs)
    867         if is_integer(y) and not self.data.columns.holds_integer():
    868             y = self.data.columns[y]
--> 869         if len(self.data[x]._get_numeric_data()) == 0:
    870             raise ValueError(self._kind + " requires x column to be numeric")
    871         if len(self.data[y]._get_numeric_data()) == 0:

C:\Users\kanks\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2978             if self.columns.nlevels > 1:
   2979                 return self._getitem_multilevel(key)
-> 2980             indexer = self.columns.get_loc(key)
   2981             if is_integer(indexer):
   2982                 indexer = [indexer]

C:\Users\kanks\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2897                 return self._engine.get_loc(key)
   2898             except KeyError:
-> 2899                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2900         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2901         if indexer.ndim > 1 or indexer.size > 1:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'TV' 

enter image description here

1 Ответ

0 голосов
/ 10 апреля 2020

Не могли бы вы подтвердить, что столбец TV существует? Печатая:

print(data.columns)

Поскольку в вашем наборе данных нет столбца TV, попробуйте закомментировать первый график. Таким образом, теперь вы должны увидеть как минимум 2 сюжета

#data.plot(kind='scatter', x='TV', y='sales', ax=axs[0], figsize=(16,8))
...