首页 > 解决方案 > ValueError:x 和 y 必须具有相同的第一维,但具有形状 (1, 2) 和 (2,)

问题描述

我想从列表中找到最大值和最小值,但在运行我的程序后,终端显示错误,如“ValueError:x 和 y 必须具有相同的第一维,但具有形状 (1, 2) 和 (2,)”。如何解决这个问题?

代码:

from scipy.signal import argrelextrema

data = np.array([-1, 0, 1, 2, 1, 0, -1, -2, -1, 0, 1, 2, 1 ])
plt.plot(data)


maximums = argrelextrema(data, np.greater) 

plt.plot(maximums, data[maximums], "x")

minimums = np.array(argrelextrema(data, np.less))

plt.plot(minimums, data[minimums], ".")

plt.show()

标签: pythonscipy

解决方案


正如您在文档中看到的那样,maximaminima不是一维数组,而是 ndarrays 的元组

import numpy as np
from scipy.signal import argrelextrema
import matplotlib.pyplot as plt

data = np.array([-1, 0, 1, 2, 1, 0, -1, -2, -1, 0, 1, 2, 1 ])

maxima = argrelextrema(data, np.greater) 
minima = argrelextrema(data, np.less)

让我们检查

print(maxima)

(array([ 3, 11]),)

print(minima)

(array([7]),)

由于您只需要元组的第一个元素,您可以这样做

plt.plot(data)
plt.plot(maxima[0], data[maxima[0]], "x", ms=10)
plt.plot(minima[0], data[minima[0]], ".", ms=10)
plt.show()

在此处输入图像描述


推荐阅读