python - 如何将 pandas 列中的浮点值离散为 [1, 10]

标签 python pandas dataframe

我有一个数据框,如何根据它们所属的范围将列中的值转换为相应整数的列表。例如,

test = pd.DataFrame({"price": [0.1, 0.5, 0.2, 0.11, 0.8, 0.3, 0.9, 1.0, 0.47]})
out[1]:
        price
    0   0.10
    1   0.50
    2   0.20
    3   0.11
    4   0.80
    5   0.30
    6   0.90
    7   1.00
    8   0.47

然后,我需要根据范围将值转换为整数,例如,当 x <= 0.1 时,使 x = 1,当 0.1 < x <= 0.2 时,使 x = 2。结果如下所示:

out[2]:
        price   price_new 
    0   0.10     1          # 0.10 belongs to [0, 0.1] ---> 1
    1   0.50     5          # 0.50 belongs to (0.40, 0.5] ---> 5
    2   0.20     2                .
    3   0.11     2                .
    4   0.80     8                .
    5   0.30     3
    6   0.90     9
    7   1.00     10
    8   0.47     5

我尝试了一些方法,但效果不佳。请帮忙!非常感谢!

最佳答案

你可以使用 pandas cut

bins = np.arange(0, 1.1, 0.1)
labels = np.arange(1, 11)
test['price_new'] = pd.cut(test.price, bins = bins, labels = labels)


price   price_new
0   0.10    1
1   0.50    5
2   0.20    2
3   0.11    2
4   0.80    8
5   0.30    3
6   0.90    9
7   1.00    10
8   0.47    5

编辑:使用 - 和 + inf 创建 bin 以包含极值。

bins = [-np.inf , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, np.inf ]

关于python - 如何将 pandas 列中的浮点值离散为 [1, 10],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54080117/

相关文章:

python - Pandas:使用 apply 创建 2 个新列

r - "foreach"并行循环返回 <NA>s

python - 忽略 numpy 数组创建中的嵌套结构

python - 子类化 Python 的 `property`

python - 重新索引多索引的问题

python - 将 pandas 过滤器应用于数据帧会得到一个充满 NaN 的数据帧

python - 如何在 pandas python 中填充一行

python - 理解 Python 中的可变性

python - cookiecutter-django 上的数据库设置问题

python - 使用 Pandas Python 进行透视以获取 bool 值