我的数据框中有一列数字,我想将这些数字分类为例如高、中、低、排除。该如何实现?我对此一无所知,我尝试过查看cut函数和category数据类型。
回答:
使用pd.cut
的简短示例。
让我们从一个数据框开始:
df = pd.DataFrame({'A': [0, 8, 2, 5, 9, 15, 1]})
假设我们想将这些数字分配到以下类别:如果数字在区间[0, 2]
内,则为'low'
;如果在(2, 8]
内,则为'mid'
;如果在(8, 10]
内,则为'high'
;我们排除10以上的数字(或低于0的数字)。
因此,我们有3个区间,边界为:0, 2, 8, 10。现在,我们可以按如下方式使用cut
:
pd.cut(df['A'], bins=[0, 2, 8, 10], include_lowest=True)Out[33]: 0 [0, 2]1 (2, 8]2 [0, 2]3 (2, 8]4 (8, 10]5 NaN6 [0, 2]Name: A, dtype: categoryCategories (3, object): [[0, 2] < (2, 8] < (8, 10]]
参数include_lowest=True
包括第一个区间的左端。(如果您希望区间在右侧开放,请使用right=False
。)
区间可能不是类别的最佳名称。所以,让我们使用名称:low/mid/high
:
pd.cut(df['A'], bins=[0, 2, 8, 10], include_lowest=True, labels=['low', 'mid', 'high'])Out[34]: 0 low1 mid2 low3 mid4 high5 NaN6 lowName: A, dtype: categoryCategories (3, object): [low < mid < high]
被排除的数字15会得到一个“类别”NaN
。如果您希望使用更有意义的名称,可能最简单的解决方案(处理NaN的其他方法也存在)是添加另一个区间和一个类别名称,例如:
pd.cut(df['A'], bins=[0, 2, 8, 10, 1000], include_lowest=True, labels=['low', 'mid', 'high', 'excluded'])Out[35]: 0 low1 mid2 low3 mid4 high5 excluded6 lowName: A, dtype: categoryCategories (4, object): [low < mid < high < excluded]