我有一个数据框,如何根据它们所属的范围将列中的值转换为相应整数的列表。例如,
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/