【问题标题】:Grouping Age into custom Sections?将年龄分组到自定义部分?
【发布时间】:2018-06-17 10:59:26
【问题描述】:

我正在读取用户的 CSV,并尝试在我的新数据框中创建一个年龄组。但我收到的是未来警告,而不是预期的结果。对我来说很难解释。因此,我将说明我的意思。

这就是代码。在评论部分是我尝试过但收到未来警告的内容。

users = pd.read_csv('Users.csv')
group_names = ['[0-10]','[11-20]','[21-30]','[31-40]','[41-50],[51-60],[61-70],[71-80],[81-90],[91-100]']
bins = ([0,10,20,30,40,50,60,70,80,90,100])


ageGroup = users.groupby('Age').size()
# ageGroup = users.groupby((pd.cut(users.Age,bins),'Age')).sum()
print(ageGroup)

我得到了什么数据框:

Age
0      7794612
6            1
13          14
14         260

我想要什么数据框:

Age           Frequency
[0 - 10]      7794613
[11 - 12]     274

希望你们能帮助我。我尝试了很多东西,但由于某种原因它不起作用。我在 Stackoverflow 中搜索,但没有找到任何东西。 Stackoverflow上是否有方法或类似问题请提醒我。

最好的问候

托比亚斯

【问题讨论】:

  • usersDF 在您的代码中未定义。发布Users.csv的可测试片段
  • 这只是一个测试。我编辑它是因为我重命名了它。很抱歉造成混淆。
  • 使用 pd.cut() 来分类年龄和分组

标签: python pandas dataframe group-by data-science


【解决方案1】:

您需要为此使用cut。如:

users["binned_ages"] = pd.cut(users["Age"], bins=[10,20,30,40,50,60,70])

More on cut and bins here.

然后你就可以在你的垃圾箱上发牢骚了。

ageGroup = users.groupby("binned_ages").size()

在一行中,这看起来像:

ageGroup = users.groupby(pd.cut(users["Ages"], bins=bins)).size()

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 2020-10-08
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    相关资源
    最近更新 更多