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

使用Pandas处理Meraki API数据并绘制AP客户端数时间趋势图的实现困惑

Pandas处理Meraki API数据并绘制AP客户端数时间趋势图的实现困惑

看起来你已经完成了最核心的API调用部分啦!我来帮你梳理下接下来的步骤,核心就是把每个AP的客户端历史数据和它本身的标识信息绑定,再整理成适合Pandas和绘图库处理的格式,一步步来:

1. 先修复循环里的小问题

你当前的循环代码有缩进错误,而且每次循环都会重置times列表,最终只能保留最后一个AP的数据。我们需要把每个AP的历史数据和它的专属标识(比如序列号、名称)绑定在一起,方便后续关联:

# 准备一个空列表,用来收集所有AP的带标识的历史数据
all_ap_client_history = []

# 遍历每个AP的行数据,同时拿到serial和name(方便后续识别AP)
for idx, row in df.iterrows():
    serial = row['serial']
    ap_name = row['name']
    # 调用API获取该AP的客户端数历史
    client_history = dashboard.wireless.getNetworkWirelessClientCountHistory(
        Network_ID, 
        deviceSerial=serial, 
        timespan=3600, 
        resolution=300
    )
    # 给每个时间节点的历史数据加上所属AP的标识
    for entry in client_history:
        entry['ap_serial'] = serial
        entry['ap_name'] = ap_name
        all_ap_client_history.append(entry)

这样all_ap_client_history里的每一条数据,都自带所属AP的序列号和名称,后续处理会非常方便。

2. 转成结构化Pandas DataFrame并清洗数据

现在把收集到的原始数据转成Pandas DataFrame,同时做必要的清洗,让它适合绘图:

import pandas as pd

# 转成DataFrame
history_df = pd.DataFrame(all_ap_client_history)

# 解析时间格式:把ISO字符串转成Pandas时间对象,方便后续处理
history_df['startTs'] = pd.to_datetime(history_df['startTs'])
# 提取时分秒作为X轴显示的标签
history_df['time_label'] = history_df['startTs'].dt.strftime('%H:%M:%S')

# 处理clientCount为None的情况:转成0避免绘图出错(None在绘图时会被忽略,转成0更直观)
history_df['clientCount'] = history_df['clientCount'].fillna(0)

整理后的history_df结构大概是这样的:

startTsendTsclientCountap_serialap_nametime_label
2024-12-12 11:05:00+00:002024-12-12 11:10:00+00:000Q2XX-XXXX-XXXXAP-前台区域11:05:00
..................

3. 绘制趋势图(用Matplotlib举例)

现在数据已经整理好,我们可以用Matplotlib轻松绘制需要的折线图,分两种常见场景:

场景1:单个AP的客户端数趋势

如果只需要看某一个AP的时间趋势:

import matplotlib.pyplot as plt

# 筛选目标AP的数据
target_ap_data = history_df[history_df['ap_name'] == 'AP-前台区域']

# 绘制折线图
plt.figure(figsize=(10, 6))
plt.plot(target_ap_data['time_label'], target_ap_data['clientCount'], marker='o', color='#1f77b4', label='AP-前台区域')

# 设置图表细节
plt.xlabel('时间')
plt.ylabel('在线客户端数')
plt.title('单AP客户端数时间趋势')
plt.xticks(rotation=45)  # 旋转X轴标签避免重叠
plt.legend()
plt.tight_layout()  # 自动调整布局
plt.show()

场景2:多AP同图对比趋势

如果需要同时对比多个AP的客户端数变化:

plt.figure(figsize=(12, 7))

# 遍历每个不同的AP,分别绘制折线
for ap_name in history_df['ap_name'].unique():
    ap_data = history_df[history_df['ap_name'] == ap_name]
    plt.plot(ap_data['time_label'], ap_data['clientCount'], marker='o', label=ap_name)

# 设置图表细节
plt.xlabel('时间')
plt.ylabel('在线客户端数')
plt.title('多AP客户端数时间趋势对比')
plt.xticks(rotation=45)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()

额外小提示

  • 如果你不想把None转成0,也可以在绘图时过滤掉这些行,比如ap_data = ap_data[ap_data['clientCount'].notna()]。
  • 后续如果需要更复杂的时间分析(比如按小时统计),Pandas的时间序列功能可以轻松实现,比如history_df['hour'] = history_df['startTs'].dt.hour。

备注:内容来源于stack exchange,提问作者Promise

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:38:08