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

标签 python pandas machine-learning data-analysis

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

最佳答案

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 得到一个“类别”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]

关于python - 对数据框中的列中的数据进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38936854/

相关文章:

android - 值错误: Invalid tensors 'input' were found

python - Pandas :使用元组索引将数据从两个数据帧移动到另一个数据帧

python - 在组的子组中使用 pandas 中的模式来替换缺失值

machine-learning - 我们可以在最大熵模型中使用梯度下降法吗?

python - 在 R/Python 中为边缘节点三角形邻接矩阵创建共聚类

Python:for循环中的索引字典

python - 如何允许或拒绝通知地理位置麦克风摄像头弹出

Python字符串精确结束,没有附加字符

python - 根据元素位置从另一列中提取某些元素

python - Keras 密集层输出形状