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

如何用Python计算各标签当月与上月末值差值及月度总和

Python实现标签月度差值计算与总和统计

实现步骤与代码

1. 依赖安装

若读取谷歌表格数据,先安装所需依赖:

pip install pandas gspread oauth2client

若使用本地CSV文件,仅需安装pandas:

pip install pandas

2. 完整代码

import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 读取谷歌表格数据(需提前配置服务账号)
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('service-account-key.json', scope)
client = gspread.authorize(creds)

# 替换为目标表格名称
sheet = client.open("Dataset").sheet1
data = sheet.get_all_records()
df = pd.DataFrame(data)

# 若使用本地CSV文件,替换为以下代码:
# df = pd.read_csv('dataset.csv')

# 数据预处理:转换日期格式,按标签和日期取单日最新记录
df['datetime'] = pd.to_datetime(df['datetime'])  # 替换为实际日期列名
df = df.sort_values(['tag', 'datetime'], ascending=[True, False])
daily_latest = df.groupby(['tag', df['datetime'].dt.date]).first().reset_index()

# 提取每月最后一条记录
daily_latest['month'] = daily_latest['datetime'].dt.to_period('M')
monthly_last = daily_latest.sort_values(['tag', 'datetime']).groupby(['tag', 'month']).last().reset_index()

# 计算标签当月与上月的差值
monthly_last['prev_month_val'] = monthly_last.groupby('tag')['value'].shift(1)  # 替换为实际值列名
monthly_last['monthly_diff'] = monthly_last['value'] - monthly_last['prev_month_val']

# 统计所有标签的月度差值总和
monthly_total = monthly_last.groupby('month')['monthly_diff'].sum().reset_index()

# 输出结果
print("各标签月度差值:")
print(monthly_last[['tag', 'month', 'monthly_diff']].dropna())
print("\n所有标签月度差值总和:")
print(monthly_total)

注意事项

  • 请将代码中的datetime、value替换为数据集实际的日期列和数值列名称
  • 读取谷歌表格需提前配置:在Google Cloud控制台创建项目,启用Google Sheets和Drive API,生成服务账号密钥,并将表格共享给服务账号的邮箱
  • 若无法使用API,可手动将表格导出为CSV文件,改用pd.read_csv读取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:52:34