Skip to main content
 首页 » 编程设计

python之索引错误 : too many indices when working with pandas data

2025年05月04日12artech

编写了一个函数,用于查找信号的波峰和波谷,并输出到名为 mintab 和 maxtab 的 numpy 库中的两个 ndarray 对象,其索引是时间戳,其值是峰值。

我想将这些数据绘制成散点图,时间戳作为 x 轴,峰值作为 y,所以我这样写:

xMax = maxtab[:,0] 
yMax = maxtab[:,1] 
xMin = mintab[:,0] 
yMin = mintab[:,1] 
 
mpl.rc('figure', figsize=(20, 2))                     # configure plot window size 
plt.scatter(xMax, yMax, color='g', alpha=1) 
plt.scatter(xMin, yMin, color= 'r', alpha = 1) 

但我不断收到一条错误消息:IndexError: too many indices 并指向行 xMin = mintab[:,0]

我不明白为什么会这样,我在谷歌上找不到任何相关信息。

请您参考如下方法:

我很惊讶你没有收到无法散列的类型错误:

In [1]: df = pd.DataFrame([[1, 2], [3, 4]]) 
 
In [2]: df[:, 0] 
# TypeError: unhashable type 

如果你想以这种方式选择 0 列,你应该使用 loc:

In [3]: df.loc[:, 0] 
Out[3]: 
0    1 
1    3 
Name: 0, dtype: int64 

或者直接选择列:

In [4]: df[0] 
Out[4]: 
0    1 
1    3 
Name: 0, dtype: int64 

如果你想指定第 0 列(不管标签)使用 iloc:

In [5]: df.iloc[:, 0] 
Out[5]: 
0    1 
1    3 
Name: 0, dtype: int64