gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:31:39 25 4
gpt4 key购买 nike

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

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/

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