python - 在熊猫数据框中按月和年分组
问题描述
我有以下数据集,包括刷卡和刷卡时间。输出必须是按月和按年刷卡的总数。
Card No Date Time
34235 9/17/2018 5:19
56438 9/17/2018 5:57
634787 9/17/2018 5:58
79749 9/17/2018 5:59
48947 9/17/2018 6:00
3776 9/17/2018 6:07
34235 9/17/2018 6:20
56438 9/17/2018 6:23
634787 9/17/2018 6:29
79749 9/17/2018 6:35
48947 9/17/2018 6:43
3776 9/17/2018 7:05
34235 9/17/2018 7:06
56438 9/20/2018 14:25
634787 9/20/2018 14:25
79749 9/20/2018 14:26
48947 9/20/2018 14:27
3776 9/20/2018 14:28
34235 9/20/2018 14:29
56438 9/20/2018 14:32
634787 9/20/2018 14:34
79749 11/21/2018 7:58
48947 11/21/2018 8:02
3776 11/21/2018 8:02
634787 11/21/2018 8:05
79749 11/21/2018 8:11
48947 11/21/2018 8:13
3776 11/21/2018 8:20
34235 12/4/2018 14:36
56438 12/4/2018 14:37
634787 12/4/2018 14:44
79749 12/4/2018 14:44
48947 12/4/2018 14:52
3776 12/4/2018 14:54
输出
Month/Year Count
Sep/2018 21
Nov/2018 7
Dec/2018 6
我尝试使用 groupby 但无法达到预期的输出。
df1 = pd.DataFrame(data1, columns= ['Card No','Date Time'])
df2 = df1.groupby([df1['Date Time'].dt.year.rename('year'), df1['Date Time'].dt.month.rename('month')).agg({'count'})
如何包含月份名称?
解决方案
既然你做了尝试 - 这就是我会为你的预期输出做的,
df['month_'] = df['Date Time'].dt.strftime('%b')
df['year_'] = df['Date Time'].dt.strftime('%Y')
new_df = df.groupby(["month_", "year_"])["Card_No"].count().reset_index().sort_values(
"Card_No", ascending=False)
print(new_df)
month_ year_ Card No
2 Sep 2018 21
1 Nov 2018 7
0 Dec 2018 6
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html了解更多信息。
编辑
要按月排序,您需要使用某种整数值(尽管有些人可能知道得更好)
df['month_'] = df['Date Time'].dt.strftime('%m') # change %b to %m
df['year_'] = df['Date Time'].dt.strftime('%Y')
new_df = df.groupby(["month_", "year_"])["Card_No"].count().reset_index().sort_values(
"month_")
推荐阅读
- database-design - 处理避免不一致状态的多状态系统
- python - 列出我使用 np.loadtxt 创建的数组的理解
- java - 将数据通过捆绑包从 Activity 传递到 Fragment 时获取 null
- python - 无法使用 paramiko 执行一些 unix 命令(我可以使用 pexpect)
- javascript - 使用 babel-loader + babel/preset-env 填充 DOM 函数
- c# - 带有 ScrollHeader 和 WrapPanel 的 ListView (ItemsPanel.ItemsPanelTemplate)
- google-cloud-platform - 如果没有 root 用户,云 sql mysql 消失
- javascript - Uppy IO 可恢复文件上传 allowedFileTypes
- android - 更新了最新的依赖项:Getting Configuration 'compile' is obsolete issue and cannot connect with firebase
- qtp - UFT 错误“运行被用户停止”。并在 2 个失败场景的情况下跳过输入表