我试图从我使用API调用GA创建的数据框中插入数据,并使用psycopg2将其插入到postgresql数据库中。这是我正在使用的代码:
garesults = df.reindex_axis(['campaign', 'adClicks', 'adCost', 'CPC', 'sessions', 'bounceRate', 'pageviewsPerSession', 'goal6ConversionRate', 'goal6Completions', 'goal6Values'], axis = 1)
gafill = garesults.fillna(value = 0)
# Connect to an existing database
conn = psycopg2.connect("dbname=test user=xxx password=xxx")
# Open a cursor to perform database operations
cur = conn.cursor()
# Execute a command: this creates a new table
#cur.execute("CREATE TABLE adform (campaign, campaignid, impressions, clicks );")
for row in gafill:
cur.execute("""INSERT INTO ga ( campaign, adClicks, adCost, CPC, sessions, bounceRate, pageviewsPerSession, goal6ConversionRate, goal6Completions, goal6Values)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", [row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9]])
当我运行它时,它会返回一条错误消息:
IndexError: string index out of range
任何人都可以看到我做错了什么?
我认为问题是你如何尝试迭代数据帧。
尝试使用itertuples代替:
for index, row in gafill.itertuples():
.....