我有一个数据列,我想要将其剪切到离散的存储箱中。我的min是1,max是70
df.total_value.describe()
count 37926.000000
mean 12.368138
std 7.385642
min 1.000000
25% 8.000000
50% 10.000000
75% 16.000000
max 70.000000
Name: total_value, dtype: float64我试过了
labels = ["{0} - {1}".format(i, i + 1) for i in range(1, 70, 1)]
cut_bins = range(1, 70)
df['total_value_bins'] = pd.cut(df['total_value'], bins= cut_bins, labels=labels)我得到了这个错误
ValueError: Bin labels must be one fewer than the number of bin edges如果我用的话我能拿到垃圾桶
df['total_value_bins'] = pd.cut(df['total_value'], bins= cut_bins)但是我想拥有格式良好的e.g. 1-2
任何有帮助的建议都将不胜感激。
提前谢谢。
发布于 2021-08-26 12:43:44
正如错误所说,你需要有len(cut_bins) = len(labels)+1,而现在它们的长度是一样的。此外,为了能够将值1和70绑定在一起,需要将cut_bins的range中的上限更改为71 (因为上限不是在range中创建的),并使用cut中的参数include_lowest
labels = ["{0} - {1}".format(i, i + 1) for i in range(1, 70, 1)]
cut_bins = range(1, 71) # here goes to 71
# dummy data
s = pd.Series([1,4,45,70])
print(pd.cut(s, bins= cut_bins, labels=labels, include_lowest=True))
0 1 - 2
1 3 - 4
2 44 - 45
3 69 - 70
dtype: category
Categories (69, object): ['1 - 2' < '2 - 3' < '3 - 4' < '4 - 5' ... '66 - 67' < '67 - 68' < '68 - 69' < '69 - 70']https://stackoverflow.com/questions/68938604
复制相似问题