[英]How to produce equally sized bins with pandas cut?
在 pandas 自己的關於cut
方法的文檔中,它說它產生相同大小的垃圾箱。 但是,在他們提供的示例中,它顯然沒有:
>>>pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3)
[(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...
Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...
第一個區間比其他所有區間都大,這是為什么呢?
編輯:即使數組中的最小數字 (1) 大於 1(例如 1.001),它仍然會產生寬度不等的 bin:
In [291]: pd.cut(np.array([1.001, 7, 5, 4, 6, 3]), 3)
Out[291]:
[(0.995, 3.001], (5.0, 7.0], (3.001, 5.0], (3.001, 5.0], (5.0, 7.0], (0.995, 3.001]]
Categories (3, interval[float64]): [(0.995, 3.001] < (3.001, 5.0] < (5.0, 7.0]]
對於您獲得的那種性能,我可以忍受這種小數誤差。 但是,如果您知道您的數據並希望盡可能接近均勻間隔的 bin,請使用linspace
作為 bin 規范(類似於此處):
arr = np.array([1, 7, 5, 4, 6, 3])
pd.cut(arr, np.linspace(arr.min(), arr.max(), 3+1), include_lowest=True)
# [(0.999, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], (0.999, 3.0]]
# Categories (3, interval[float64]): [(0.999, 3.0] < (3.0, 5.0] < (5.0, 7.0]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.