对数据框中的列中的数据进行分类

Categorize Data in a column in dataframe

我的数据框中有一列数字,我想将这些数字分类为例如高、低、排除。我该怎么做。我很无能,我已经尝试查看 cut 函数和类别数据类型。

这个问题很宽泛,但是文档中的这个页面可能是一个不错的起点:

http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing

或者您可以查看 numpy.where

    import numpy as np
    df['is_high'] = np.where(df.['column_of_interest'] > 5 ,1,0) 

pd.cut 的简短示例。

让我们从一些数据框开始:

df = pd.DataFrame({'A': [0, 8, 2, 5, 9, 15, 1]})

并且,比方说,我们要将数字分配给以下类别:'low' 如果数字在 [0, 2] 区间内,'mid' 对于 (2, 8]'high' 对于 (8, 10],我们排除了 10 以上(或以下 0)的数字。

因此,我们有 3 个带边的 bin: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        NaN
6     [0, 2]
Name: A, dtype: category
Categories (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     low
1     mid
2     low
3     mid
4    high
5     NaN
6     low
Name: A, dtype: category
Categories (3, object): [low < mid < high]

被排除的数字 15 获得 "category" NaN。如果您更喜欢一个更有意义的名称,可能最简单的解决方案(还有其他方法可以处理 NaN 的)是添加另一个 bin 和一个类别名称,例如:

pd.cut(df['A'], bins=[0, 2, 8, 10, 1000], include_lowest=True, labels=['low', 'mid', 'high', 'excluded'])
Out[35]: 
0         low
1         mid
2         low
3         mid
4        high
5    excluded
6         low
Name: A, dtype: category
Categories (4, object): [low < mid < high < excluded]