gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:12 25 4
gpt4 key购买 nike

我的数据框中有一列数字,我想将这些数字分类为例如高、低、排除。我该怎么做。我很无能,我试过查看 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com