我有一列值從 0 更改為 600,我想將 0 到 9.2 的值按 0.4 增量分組,并將 9.2 和 600 值之間的 1 組作為例外值進行分組。我嘗試了以下代碼;
bin_labels = ['0-0.4', '0.4-0.8', '0.8-1.2', '1.2-1.6',
'1.6-2.0', '2.0-2.4','2.4-2.8', '2.8-3.2',
'3.2-3.6', '3.6-4.0','4.0-4.4', '4.4-4.8',
'4.8-5.2', '5.2-5.6','5.6-6.0', '6.0-6.4',
'6.4-6.8', '6.8-7.2','7.2-7.6', '7.6-8.0',
'8.0-8.4', '8.4-8.8','8.8-9.2']
bins = np.linspace(0.0,9.2,24)
df['A_group'] = pd.cut(df['A'], bins = bins, labels = bin_labels, include_lowest = True)
之后,我想使用以下代碼用“9.2-more”標簽值填充 9.2 和 600 之間的值;
df['A_group'] = df['A_group'].fillna('9.2-more')
但它說以下錯誤;
無法在具有新類別的 Categorical 上設定專案,請先設定類別
uj5u.com熱心網友回復:
您可以附加float("inf")到bins并在以下內容中包含“9.2-more” bin_labels:
bin_labels = [ '0-0.4', '0.4-0.8', '0.8-1.2', '1.2-1.6',
'1.6-2.0', '2.0-2.4', '2.4-2.8', '2.8-3.2',
'3.2-3.6', '3.6-4.0', '4.0-4.4', '4.4-4.8',
'4.8-5.2', '5.2-5.6', '5.6-6.0', '6.0-6.4',
'6.4-6.8', '6.8-7.2', '7.2-7.6', '7.6-8.0',
'8.0-8.4', '8.4-8.8', '8.8-9.2', "9.20-more"]
bins = np.append(np.linspace(0.0, 9.2, 24), float("inf"))
df["A_group"] = pd.cut(df['A'], bins = bins, labels = bin_labels, include_lowest = True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/349180.html
上一篇:在熊貓中取條件均值
