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

如何通过Google Analytics Reporting API将多维度指标转为Pandas DataFrame

问题解决方法

你遇到的两个报错根因如下:

  • 所有维度、指标数据都被平铺存入一维列表,没有按行分组,赋值给DataFrame列时长度完全不匹配,触发ValueError: Length of values does not match length of index
  • 用df["Revenue", "Quantity"]=val的写法实际创建的是MultiIndex多级列名,不是同时给两个单独列赋值,后续选择单列时就会触发索引不存在的报错

修正后代码

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'client_secrets.json'
VIEW_ID = '123456789' # 替换为你自己的GA视图ID

credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)
analytics = build('analyticsreporting', 'v4', credentials=credentials)

response = analytics.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': VIEW_ID,
                'dateRanges': [
                    {'startDate': '30daysAgo', 'endDate': 'today'},
                    ],
                'metrics': [
                    {'expression': 'ga:itemRevenue'},
                    {'expression': 'ga:itemQuantity'}
                ],
                'dimensions': [
                    {"name": "ga:productName"},
                    {"name": "ga:productSku"}
                    ],
                'orderBys': [{"fieldName": "ga:itemRevenue", "sortOrder": "DESCENDING"}],
                'pageSize': 1000
            }]
    }
).execute()

# 存储所有行数据的列表
all_rows = []

for report in response.get('reports', []):
    rows = report.get('data', {}).get('rows', [])
    for row in rows:
        # 取当前行的两个维度
        product_name, sku = row.get('dimensions', [])
        # 取当前行的两个指标
        revenue, quantity = row.get('metrics', [])[0].get('values')
        # 按行拼接数据
        all_rows.append({
            "Product": product_name,
            "SKU": sku,
            "Revenue": float(revenue),
            "Quantity": float(quantity)
        })

# 直接生成DataFrame
df = pd.DataFrame(all_rows)
print(df)

说明

修改后按行提取对应维度、指标值,一一对应存入列表,不会出现长度不匹配的问题,生成的DataFrame直接包含你需要的4个列,无需额外调整列顺序或列名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:39:04