gpt4 book ai didi

python - 使用 Pandas 对 float 列进行分组

转载 作者:太空宇宙 更新时间:2023-11-03 12:26:03 27 4
gpt4 key购买 nike

我需要按重量对 Pandas 进行分组

Name      weight(kg)
Person1 4.44
Person2 37.3
Person3 36.38
Person4 39.52
Person5 81.57
Person6 43.55
Person7 91.11
Person8 5
Person9 36.48
Person10 38.25

我的代码如下。需要根据if条件分组。我的代码如下。但是我得到的所有行都是 0 到 20。

if 0 <= data_file['weight(kg)'].all() < 20:
data_file['target'] = "0 to 20%"
if 20 < data_file['weight(kg)'].all() < 40:
data_file['target'] = "20 to 40%"
if 40 < data_file['weight(kg)'].all() < 60:
data_file['target'] = "40 to 60%"
if 60 < data_file['weight(kg)'].all() < 80:
data_file['target'] = "60 to 80%"
if 80 < data_file['weight(kg)'].all() <= 100:
data_file['target'] = "80 to 100%"

预计结束

Name     weight(kg) Target
Person1 4.44 0 to 20
Person2 37.3 20 to 40
Person3 36.38 20 to 40
Person4 39.52 20 to 40
Person5 81.57 80 to 100
Person6 43.55 40 to 60
Person7 91.11 80 to 100
Person8 5 0 to 20
Person9 36.48 20 to 40
Person10 38.25 20 to 40

最佳答案

使用pd.cut

df.assign(bins = pd.cut(df["weight(kg)"], [0,20,40,60,80,100], 
labels=['0 to 20', '20 to 40', '40 to 60', '60 to 80', '80 to 100']))

结果

      Name   weight(kg) bins
0 Person1 4.44 0 to 20
1 Person2 37.30 20 to 40
2 Person3 36.38 20 to 40
3 Person4 39.52 20 to 40
4 Person5 81.57 80 to 100
5 Person6 43.55 40 to 60
6 Person7 91.11 80 to 100
7 Person8 5.00 0 to 20
8 Person9 36.48 20 to 40
9 Person10 38.25 20 to 40

关于python - 使用 Pandas 对 float 列进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57729864/

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