解决pandas.errors.InvalidIndexError: (slice(None, None, None), None)

Traceback (most recent call last):
  File "D:\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 3621, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 136, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 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:

Traceback (most recent call last):
  File "D:\Anaconda\lib\site-packages\matplotlib\cbook\__init__.py", line 1318, in _check_1d
    ndim = x[:, None].ndim
  File "D:\Anaconda\lib\site-packages\pandas\core\frame.py", line 3505, in __getitem__
    indexer = self.columns.get_loc(key)
  File "D:\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 3628, in get_loc
    self._check_indexing_error(key)
  File "D:\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 5637, in _check_indexing_error
    raise InvalidIndexError(key)
pandas.errors.InvalidIndexError: (slice(None, None, None), None)

ValueError: x and y must have same first dimension, but have shapes (2, 14) and (14,)
解决pandas.errors.InvalidIndexError: (slice(None, None, None), None)_第1张图片
问题分析:
由于上图索引(时间列)存在重复,导致下面代码中, ax.plot()的时候,把两个相同的索引,构造了一个(2,14)的重复

fig, ax = plt.subplots(figsize=(15, 7))
cmap = plt.get_cmap('viridis')
colors = cmap(np.linspace(0, 1, len(df_10minv2)))
for i, (name, color) in tqdm(enumerate(zip(names, colors), 1)):
    ax.plot(df_10minv2.loc[name], height, c=color, linestyle='-', label=str(name), marker='.')

解决办法:对索引列去重复

# 如果你想保留第一个aa,那么keep就是first
df.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')

你可能感兴趣的:(bug,pandas,python,开发语言)