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

如何用Pandas将Apple Health步数数据按日分组绘制单图?

Apple Health步数数据按日分组绘制单张图表解决方案

你已经成功从Apple Health导出的export.zip中提取出步数数据,并完成了按日分组求和,但直接在groupby对象上调用plot()会生成每日单独的图表,解决方法很简单:直接对分组聚合后的DataFrame调用绘图方法即可。

完整代码示例

import zipfile
import pandas
import matplotlib.pyplot as plt

# 从zip文件读取并解析Apple Health数据
with zipfile.ZipFile('/Users/steven/Downloads/export.zip') as myzip:
    with myzip.open('apple_health_export/export.xml') as myfile:
        x = pandas.read_xml(myfile, xpath='//Record', attrs_only=True, parse_dates=["creationDate","startDate","endDate"])

# 数据清洗:转换数值并过滤空值
x.value = pandas.to_numeric(x.value, errors='coerce')
x = x[x.value.notnull()]

# 筛选步数数据
data = x[x.type == 'HKQuantityTypeIdentifierStepCount']

# 按日分组求和,得到每日总步数
df = data.groupby(pandas.Grouper(key='endDate', axis=0, freq='D')).sum('value')

# 绘制单张每日总步数图表
plt.figure()
plt.rcParams.update({'font.family':'Avenir'})
# 用折线图展示趋势,也可替换为kind='bar'生成柱状图
df.plot(title='Daily Total Steps', grid=True, kind='line', fontsize=8, figsize=(11,5),
        xlim=(pandas.to_datetime('2024-08-01'), pandas.to_datetime('today')))
plt.xlabel('Date')
plt.ylabel('Total Steps')
plt.show()

关键说明

  • groupby().sum()已经帮你生成了以日期为索引、每日总步数为值的DataFrame,直接对这个聚合后的df调用plot(),就会生成单张包含所有日期数据的图表。
  • 若需要聚焦特定日期范围,也可以先对df做筛选再绘图,比如:
    df_filtered = df.loc['2024-08-01': pandas.to_datetime('today')]
    df_filtered.plot(...)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:13:14