想要使用 for 循环多次 运行 查询并将每个结果添加到字典中。此代码即使在循环时也只执行一次
Want to run a query multiple times using a for loop and add each result into a dictionary. This code only execute once even as it loops through
我有一个随机抽取记录样本的查询。我想多次执行此操作并将每个结果添加到字典中,稍后我会将其连接到 pandas DataFrame 中。这段代码即使在循环中也只执行一次。
cursor.execute("select record1, record2 from table order by random() limit 1000")
d = {}
for x in range(10):
d[x] = pd.DataFrame(cursor.fetchall())
cursor.fetchall()
不执行查询,它只是从 cursor.execute()
已执行的查询中获取剩余结果。循环的第一次迭代获取所有内容,因此其他 9 次迭代没有任何内容可获取,您得到空数据帧。
您需要将 cursor.execute()
调用移动到循环中。
d = {}
for x in range(10):
cursor.execute("select record1, record2 from table order by random() limit 1000")
d[x] = pd.DataFrame(cursor.fetchall())
请注意,每个数据框中的记录之间可能会有重叠。如果你不想这样,你应该对 10,000 条记录进行一次查询,然后将它们分成数据帧,每块 1,000。
cursor.execute("select record1, record2 from table order by random() limit 10000")
rows = cursor.fetchall()
d = {}
for x in range(0,10000,1000):
d[x/1000] = pd.DataFrame(rows[x:x+1000])
我有一个随机抽取记录样本的查询。我想多次执行此操作并将每个结果添加到字典中,稍后我会将其连接到 pandas DataFrame 中。这段代码即使在循环中也只执行一次。
cursor.execute("select record1, record2 from table order by random() limit 1000")
d = {}
for x in range(10):
d[x] = pd.DataFrame(cursor.fetchall())
cursor.fetchall()
不执行查询,它只是从 cursor.execute()
已执行的查询中获取剩余结果。循环的第一次迭代获取所有内容,因此其他 9 次迭代没有任何内容可获取,您得到空数据帧。
您需要将 cursor.execute()
调用移动到循环中。
d = {}
for x in range(10):
cursor.execute("select record1, record2 from table order by random() limit 1000")
d[x] = pd.DataFrame(cursor.fetchall())
请注意,每个数据框中的记录之间可能会有重叠。如果你不想这样,你应该对 10,000 条记录进行一次查询,然后将它们分成数据帧,每块 1,000。
cursor.execute("select record1, record2 from table order by random() limit 10000")
rows = cursor.fetchall()
d = {}
for x in range(0,10000,1000):
d[x/1000] = pd.DataFrame(rows[x:x+1000])