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

Pandas按时间段筛选DataFrame后如何统计location列的数值出现次数?

实现方案

首先注意你现有代码的小问题:set_index和between_time默认都会返回新的DataFrame,没有赋值给变量的话筛选结果不会生效,你可以根据使用场景选择以下两种实现方式:

  • 方式1:链式调用一步完成,适合不需要单独保留筛选后DataFrame的场景
count_result = (
    df.set_index('Time')
    .pipe(lambda x: x.set_index(pd.to_datetime(x.index)))
    .between_time('08:00', '17:00')
    ['location']
    .value_counts()
)

其中value_counts()是Pandas统计列各值出现频次的专用方法,默认按频次从高到低排序。

  • 方式2:先保存筛选结果再统计,适合后续还要继续使用筛选后DataFrame的场景
# 完成时间范围筛选并保存结果
df_filtered = df.set_index('Time')
df_filtered.index = pd.to_datetime(df_filtered.index)
df_filtered = df_filtered.between_time('08:00', '17:00')

# 统计location列各值出现次数
location_count = df_filtered['location'].value_counts()

若需要统计空值的出现次数,可添加参数dropna=False,即value_counts(dropna=False)
若需要输出各值占比而非绝对次数,可添加参数normalize=True,即value_counts(normalize=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:24:06