仍然困惑地看着这个资源:
TypeError: not all arguments converted during string formatting in psycopg2
在将熊猫数据帧添加到数据库中时,我遇到了这个错误
user_df = [df.userId, df.firstName,df.lastName,df.gender,df.level]
user_df = pd.DataFrame(user_df)
这是userId firstName等的样子
useId = 73 (may be an int or string unknown)
firstName = Jacob
LastName = Klein
gender = M
level = paid
user_df = [df.userId, df.firstName,df.lastName,df.gender,df.level]
user_df = pd.DataFrame(user_df)
for i, row in user_df.iterrows():
cur.execute(user_table_insert, row)
conn.commit()
user_table_insert如下所示:
user_table_insert = ("""
INSERT INTO users(userId, firstName, lastName, gender, level)
VALUES(%s,%s,%s,%s,%s);
""")
使用用户表create语句,如下所示:
createuserstable = "CREATE TABLE IF NOT EXISTS users(userId VARCHAR, firstName VARCHAR, lastName VARCHAR, gender VARCHAR, level VARCHAR);"
这是当我的代码尝试将其插入users
模型中时的错误
Traceback (most recent call last):
File "etl.py", line 111, in <module>
main()
File "etl.py", line 105, in main
process_data(cur, conn, filepath='data/log_data', func=process_log_file)
File "etl.py", line 94, in process_data
func(cur, datafile)
File "etl.py", line 61, in process_log_file
cur.execute(user_table_insert, row)
TypeError: not all arguments converted during string formatting
不确定我为什么要得到这个。看看psycopg2文档,也许你们当中有人遇到类似的问题?
答案 0 :(得分:1)
好吧,你这样做:
userId = 73
firstName = 'Jacob'
lastName = 'Klein'
gender = 'M'
level = 'paid'
user_df = [userId, firstName, lastName, gender, level]
user_df = pd.DataFrame(user_df)
for i, row in user_df.iterrows():
print(row)
0 73
Name: 0, dtype: object
0 Jacob
Name: 1, dtype: object
0 Klein
Name: 2, dtype: object
0 M
Name: 3, dtype: object
0 paid
Name: 4, dtype: object
您会看到该行由Pandas对象组成。 psycopg2不知道如何适应这些问题,因此会出现错误。除此之外,您还要遍历单行并获取该行中的元素。
不确定为什么仍要转换为DataFrame。只需使用列表即可:
user_row = [userId, firstName, lastName, gender, level]
cur.execute(user_table_insert, user_row)