【问题标题】:Pandas binning of integer for years多年的整数熊猫分箱
【发布时间】:2020-11-19 00:57:39
【问题描述】:

鉴于此示例数据:

 year   zan_inj bins
0   1980    15  NaN
1   1981    18  (1980.0, 1985.0]
2   1982    23  (1980.0, 1985.0]
3   1983    33  (1980.0, 1985.0]
4   1984    42  (1980.0, 1985.0]
5   1985    54  (1980.0, 1985.0]
6   1986    59  (1985.0, 1990.0]
7   1987    65  (1985.0, 1990.0]
8   1988    76  (1985.0, 1990.0]
9   1989    86  (1985.0, 1990.0]

两个问题。我想对所有 bin 值进行分组以获取下面的数据框,并且还希望以 1980 开头的 bin 实际上包含 1980 年的顶行值。我的两列都是“int”类型。

理想输出:

total   bin
185    (1980.0, 1985.0]
311    (1985.0, 1990.0]

我试过了:

df.groupby('bins').size()
pd.cut(df['year'], bins=bins).value_counts()

【问题讨论】:

    标签: pandas pandas-groupby binning


    【解决方案1】:

    你可以尝试添加include_lowest,但这会使下边界不是int

    pd.cut(df['year'], bins=bins, include_lowest=True).value_counts()
    

    更新

    out = df.groupby( pd.cut(df['year'], bins=bins, include_lowest=True)).agg({'total':'sum'})
    

    【讨论】:

    • 我尝试了与此类似的操作,但尝试上面的代码实际上会计算实际 bin 值连续出现的次数。像这样。 (1979.999, 1985.0] 6 (2010.0, 2015.0] 5 (2005.0, 2010.0] 5 (2000.0, 2005.0] 5 (1995.0, 2000.0] 5 (1990.0, 1995.0] 5) (1985.0, 1990.0] 2 (1985.0, 1990.0]2.跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    相关资源
    最近更新 更多