gpt4 book ai didi

Python - 将列值分组到类中

转载 作者:行者123 更新时间:2023-11-28 21:37:44 25 4
gpt4 key购买 nike

我有一个包含以下数据的 CSV:

Customer    Age
A 10
B 53
C 20
D 2
E 55
F 12

为此,我使用 Pandas 库来读取 csv。我的问题是如何对年龄值进行分组以获得具有如下间隔的新列:

Customer    Age   Age_Interval
A 10 [0-10]
B 53 [50-60]
C 20 [10-20]
D 2 [0-10]
E 55 [50-60]
F 12 [10-20]

我该怎么做?

谢谢!

最佳答案

我相信你需要cut :

df['Age_Interval'] = pd.cut(df['Age'], bins=np.arange(0,110,10))
print (df)
Customer Age Age_Interval
0 A 10 (0, 10]
1 B 53 (50, 60]
2 C 20 (10, 20]
3 D 2 (0, 10]
4 E 55 (50, 60]
5 F 12 (10, 20]

b = np.arange(0,110,10)
l = [ "{0}-{1}".format(i, i + 10) for i in range(0, 100, 10)]
df['Age_Interval'] = pd.cut(df['Age'], bins=b, labels=l)
print (df)
Customer Age Age_Interval
0 A 10 0-10
1 B 53 50-60
2 C 20 10-20
3 D 2 0-10
4 E 55 50-60
5 F 12 10-20

编辑:

print (df)
Customer Age
0 A 10
1 B 53
2 C 20
3 D 2
4 E 55
5 F 12
6 G 0

b = np.arange(0,110,10)
l = [ "{0}-{1}".format(i, i + 10) for i in range(0, 100, 10)]
df['Age_Interval'] = pd.cut(df['Age'], bins=b, labels=l, include_lowest=True)
print (df)
Customer Age Age_Interval
0 A 10 0-10
1 B 53 50-60
2 C 20 10-20
3 D 2 0-10
4 E 55 50-60
5 F 12 10-20
6 G 0 0-10

关于Python - 将列值分组到类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49045283/

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