python-3.x - 如何将 1 个系列的唯一值作为列并计算每季度系列中唯一值的每次出现?
问题描述
我有一个看起来像这样的df:
date col1
0 2020-01-09T19:25 a
1 2020-01-09T13:27 a
2 2020-01-04T13:44 b
3 2019-12-31T15:37 b
4 2019-12-23T21:47 c
我想将 col1 的唯一值分配为列标题,并按季度对日期进行分组,并按季度计算 col1 的唯一值。
我可以按季度分组并像这样计算:
df['date'] = pd.to_datetime(df['date'])
df = df.groupby(df['date'].dt.to_period('Q'))['col1'].agg(['count'])
df 现在看起来像这样:
count
dateresponded
2019Q4 2
2020Q1 3
我无法分辨出唯一值的计数是多少。
我希望 df 看起来像这样:
a b c
dateresponded
2019Q4 1 1
2020Q1 2 1
解决方案
IIUC,你想要pd.crosstab
new_df = pd.crosstab(df['date'].dt.to_period('Q'),df['col1'],
rownames=['dateresponded'],
colnames=[None])
print(new_df)
我们也可以使用groupby
+ DataFrame.unstack
。我们可以使用 重命名轴DataFrame.rename_axis
。
new_df = (df.groupby([df['date'].dt.to_period('Q'),'col1'])
.size()
.unstack(fill_value = 0)
.rename_axis(columns = None,index = 'dateresponded'))
print(new_df)
new_df = (df.groupby(df['date'].dt.to_period('Q'))
.col1
.value_counts()
.unstack(fill_value = 0)
.rename_axis(columns = None,index = 'dateresponded'))
print(new_df)
输出
a b c
dateresponded
2019Q4 0 1 1
2020Q1 2 1 0
推荐阅读
- html - 仅在输入而不是标签上应用悬停选择器
- postgresql - 在 postgres 中正确设置角色的 statement_timeout
- javascript - 用于条件加载变体字段的 Jquery Click 功能无法正常工作
- javascript - 为什么箭头函数可以解决其他需要 .bind 的问题?(SetInverval 调用使用 setState 的函数)
- pdf - FileMaker Pro 电子签名
- python - discord py 删除所有个人角色
- mysql - 为什么 DELETE 语句不会一次性删除所有满足条件的记录?
- python - 与实现 len() 或 shape 的对象无关的函数
- azure - 无法在 Azure DevOps 管道中运行嵌套的 az cli 命令
- python - 从文件夹文件运行程序