x = np.array([123,172,76,161,314,77,226,330,202,321,260,155,120,163,221,400,45,106,296,125,210,66,131,242,372]) x.sort() w = int(input("请输入等宽分箱的宽度:")) max = x.max() min = x.min() m = int(math.ceil((max - min)/w)) bins = [min+k*w for k in range(0,m+1)] x_cuts = pd.cut(x, bins, right=False) number = pd.value_counts(x_cuts) rows = number.max() width = np.full([m, rows], 0) size = x.size a = 0 for j in range(0, m-1): for i in range(0, number[j]): width[j][i] = x[a] a = a + 1 print(width) Traceback (most recent call last):KeyError: 0
时间: 2023-05-25 10:04:40 浏览: 78
The error "KeyError: 0" is raised because the code is trying to access an index that does not exist in a dictionary or a list.
In this case, it is likely that the error is caused by the line "for i in range(0, number[j]):", where "number" is a dictionary generated by "pd.value_counts(x_cuts)". The loop is trying to access the index "0", which may not exist in the dictionary.
To fix this error, you can modify the loop to iterate over the keys and values of the dictionary, like this:
for bin, count in number.items():
for i in range(count):
width[j][i] = x[a]
a += 1
This will iterate over the keys (i.e., the bins) and values (i.e., the counts) in the dictionary, and then iterate over the range of the count to fill in the corresponding values in the "width" array. The variable "a" is incremented each time to keep track of the index in the sorted array "x".
阅读全文