python - 如何在 pandas 中有效地对列和 groupby 进行分类?
问题描述
我有以下数据框:
date = ['2015-02-03 23:00:00','2015-02-03 23:30:00','2015-02-04 00:00:00','2015-02-04 00:30:00','2015-02-04 01:00:00','2015-02-04 01:30:00','2015-02-04 02:00:00','2015-02-04 02:30:00','2015-02-04 03:00:00','2015-02-04 03:30:00','2015-02-04 04:00:00','2015-02-04 04:30:00','2015-02-04 05:00:00','2015-02-04 05:30:00','2015-02-04 06:00:00','2015-02-04 06:30:00','2015-02-04 07:00:00','2015-02-04 07:30:00','2015-02-04 08:00:00','2015-02-04 08:30:00','2015-02-04 09:00:00','2015-02-04 09:30:00','2015-02-04 10:00:00','2015-02-04 10:30:00','2015-02-04 11:00:00','2015-02-04 11:30:00','2015-02-04 12:00:00','2015-02-04 12:30:00','2015-02-04 13:00:00','2015-02-04 13:30:00','2015-02-04 14:00:00','2015-02-04 14:30:00','2015-02-04 15:00:00','2015-02-04 15:30:00','2015-02-04 16:00:00','2015-02-04 16:30:00','2015-02-04 17:00:00','2015-02-04 17:30:00','2015-02-04 18:00:00','2015-02-04 18:30:00','2015-02-04 19:00:00','2015-02-04 19:30:00','2015-02-04 20:00:00','2015-02-04 20:30:00','2015-02-04 21:00:00','2015-02-04 21:30:00','2015-02-04 22:00:00','2015-02-04 22:30:00','2015-02-04 23:00:00','2015-02-04 23:30:00']
value = [33.24 , 31.71 , 34.39 , 34.49 , 34.67 , 34.46 , 34.59 , 34.83 , 35.78 , 33.03 , 35.49 , 33.79 , 36.12 , 37.09 , 39.54 , 41.19 , 45.99 , 50.23 , 46.72 , 47.47 , 48.46 , 48.38 , 48.40 , 48.13 , 38.35 , 38.19 , 38.12 , 38.05 , 38.06 , 37.83 , 37.49 , 37.41 , 41.84 , 42.26 , 44.09 , 48.85 , 50.07 , 50.94 , 51.09 , 50.60 , 47.39 , 45.57 , 45.03 , 44.98 , 41.32 , 40.37 , 41.12 , 39.33 , 35.38 , 33.44 ]
df = pd.DataFrame({'value':value,'index':date})
df.index = pd.to_datetime(df['index'],format='%Y-%m-%d %H:%M')
df.drop(['index'],axis=1,inplace=True)
print(df)
value
index
2015-02-03 23:00:00 33.24
2015-02-03 23:30:00 31.71
2015-02-04 00:00:00 34.39
2015-02-04 00:30:00 34.49
2015-02-04 01:00:00 34.67
2015-02-04 01:30:00 34.46
我想有效地执行以下操作:
- 对于每一年,计算严格低于 0、介于 0 和严格低于 20 以及高于 20 之间的值的出现百分比
我知道 cut 和 groupby 函数,但我想不出一种将两者合并以优雅地做到这一点的方法。
预期的结果是这样的:
inf0 supequal0_inf20 supequal20
2015 0.2 0.6 0.2
2016 0.7 0.1 0.2
2017 0.1 0.8 0.1
非常感谢您的帮助,
解决方案
考虑到您的情况,这应该可以工作df
,但我不知道优雅:
# altered bins for demonstration purposes
binned = pd.cut(x=df.value, bins=[-np.inf, 40, 50, np.inf], right=False, labels=['low', 'mid', 'high'])
grouped = binned.groupby([pd.Grouper(freq='Y'), binned]).count() / binned.groupby(pd.Grouper(freq='Y')).count()
结果print(grouped)
:
index value
2015-12-31 low 0.520000
mid 0.380000
high 0.100000
推荐阅读
- python - 跳转到 for 循环内 readlines 的下一行
- javascript - jQuery:单击“添加”按钮后动态附加表行
- jenkins - 有 jenkins 插件的版本更新日志吗?
- html - 如何制作一组样式以指向特定元素内的类
- kubernetes - 如何将独立的 mysql 容器作为依赖项传递给 kubernetes-helm 中的服务?
- php - 如何为用户显示一些随机帖子?
- r - 如何在矩阵中创建每个可能的对
- c++ - C++ 自动类型说明符编译时间
- ruby-on-rails - Rails 在 ActiveRecord 中翻译原始 SQL
- github - 构建问题:找不到所需的包