psycopg2谷歌分析数据到postgresql
问题描述:
我想从我创建的数据框中插入数据,使用API调用到GA,并使用psycopg2将其插入到我的postgresql数据库中。 这是我使用的代码: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
有人能看到我在做什么错?
答
我认为问题在于如何尝试遍历数据框。
使用try itertuples代替:
for index, row in gafill.itertuples(): .....
注释掉表创建语句不符合插入语句。我不确定这是问题还是仅仅是将问题编辑成问题的人为因素。 –