解决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,)

问题分析:
由于上图索引(时间列)存在重复,导致下面代码中, 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')

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年9月6日
下一篇 2023年9月6日

相关推荐