通过requests向Google Analytics上报数据遇IndexingError求助
Hey there, let's break down what's causing that IndexingError: Too many indexers and fix your code step by step.
The Root Cause
Your mistake comes from how you're using df.iterrows():
- When you write
for i in df.iterrows(), eachiis actually a tuple containing (row_index, row_data)—not an integer row number like you're expecting. - When you try to use this tuple in
df.iloc[i,0], pandas gets confused becauseilocexpects integer-based index values (like0,1,2), not a tuple. That's exactly why you're seeing the "Too many indexers" error.
On top of that, you defined payload1 outside your loop, where i isn't even defined yet—so even if the loop worked, this would throw another error before it ever runs.
Fix 1: Use iterrows() Correctly (Recommended)
Destructure the tuple from iterrows() to get both the index and the row data, then use the row directly to access values. This is cleaner and more readable than relying on iloc with integer positions:
import requests import time import pandas as pd endpoint = 'http://www.google-analytics.com/collect' # Loop through each row by unpacking the (index, row) tuple for idx, row in df.iterrows(): # Build the payload INSIDE the loop, using the current row's data payload1 = { 'v' : "1", 't' : "event", 'pa' : "purchase", 'tid' : "xxx", 'cid' : row.iloc[0], # Use row.iloc[n] for position-based access 'ti' : row.iloc[6], 'ec' : "ecommerce", 'ea' : "transaction", 'ta' : "aaaa", 'tr' : row.iloc[17], 'cd1' : row.iloc[0], 'cd2' : row.iloc[6], 'cu' : "bbb", "pr1id" : "ccc", 'pr1nm' : "ddd", 'pr1pr' : row.iloc[17], 'pr1qt' : 1, 'cs' : "offline" } r = requests.post(url=endpoint, data=payload1, headers={'User-Agent': 'User 1.0'}) time.sleep(0.1) print(r)
Pro Tip: If you know the actual column names in your DataFrame (instead of just positions), replace row.iloc[0] with row['your_cid_column_name']—this makes your code more robust if the column order ever changes.
Fix 2: Loop with Integer Indices
If you prefer sticking with integer row numbers, use range(len(df)) instead of iterrows():
import requests import time import pandas as pd endpoint = 'http://www.google-analytics.com/collect' # Loop using integer row indices for i in range(len(df)): payload1 = { 'v' : "1", 't' : "event", 'pa' : "purchase", 'tid' : "xxx", 'cid' : df.iloc[i,0], 'ti' : df.iloc[i,6], 'ec' : "ecommerce", 'ea' : "transaction", 'ta' : "aaaa", 'tr' : df.iloc[i,17], 'cd1' : df.iloc[i,0], 'cd2' : df.iloc[i,6], 'cu' : "bbb", "pr1id" : "ccc", 'pr1nm' : "ddd", 'pr1pr' : df.iloc[i,17], 'pr1qt' : 1, 'cs' : "offline" } r = requests.post(url=endpoint, data=payload1, headers={'User-Agent': 'User 1.0'}) time.sleep(0.1) print(r)
Key Takeaways
- Always build your payload inside the loop so it uses the current row's data.
iterrows()returns tuples—remember to unpack them if you use this method.- Using column names instead of integer positions makes your code easier to maintain.
内容的提问来源于stack exchange,提问作者Charles

