You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python pandas按月份统计水质数据集sample.purpose.label取值数量

解决步骤

  • 第一步:存储月份列
    你之前编写的df['time'].dt.month_name()仅返回月份字符串序列,未保存到数据框中,需要先赋值为新列:
# 提取月份名称存储为新列,如需数字月份可替换为 dt.month
df['month'] = df['time'].dt.month_name()
# 如需后续按自然月份排序,建议额外存储数字月份列
df['month_num'] = df['time'].dt.month
  • 第二步:按月统计标签出现次数
    两种常用实现方式按需选择:
  1. 长表格式输出(每一行对应「月份-标签-次数」组合,适合后续筛选)
stat_result = df.groupby(['month_num', 'month'], sort=True)['sample.purpose.label'].value_counts().reset_index(name='count')
# 查询1月COMPLIANCE FORMAL (PERMIT)次数的写法
target_count = stat_result[(stat_result['month']=='January') & (stat_result['sample.purpose.label']=='COMPLIANCE FORMAL (PERMIT)')]['count'].iloc[0]
  1. 宽表格式输出(行是标签、列是月份,直观查看各月分布)
cross_result = pd.crosstab(df['sample.purpose.label'], df['month'])
# 查询1月COMPLIANCE FORMAL (PERMIT)次数的写法
target_count = cross_result.loc['COMPLIANCE FORMAL (PERMIT)', 'January']

内容的提问来源于stack exchange,提问作者sf984

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 01:12:03