我有一个基于用户输入从SQL(使用PyMySQL)导入的行的列表。有时,这些返回值可以超过5000行(这些存储在2D数组中,至少有4列)。对于用户来说,在屏幕上打印出来时无法阅读。
我已经实现了一个限制器,它将根据用户的输入返回前X行。但是,我想返回行的样本,而不是第一个X。
即如果用户选择了100行,而不是获得前100行,他们将获得由数组中的随机行组成的大小为100的样本。有办法吗?
到目前为止,我的代码是:
with conn:
cursor = conn.cursor()
cursor.execute(query, Pop_Lim)
city = cursor.fetchall()
if len(city) >= 50:
print()
print("This search will return ",len(city), "rows of data.")
Ret_Lim = int(input("How many rows of data do you want to display? "))
print()
with conn:
cursor = conn.cursor()
cursor.execute(query, Pop_Lim)
city = cursor.fetchmany(Ret_Lim)
print("ID : CountryCode : District : Population")
for row in city:
print(row["ID"], row["Name"]," : ",row["CountryCode"]," : ",row["District"]," : ",row["Population"]) # insert spacers for legibility purposes
print()
print(Ret_Lim,"rows of data returned, as requested.")
答案 0 :(得分:1)
我建议您使用熊猫。 https://pandas.pydata.org/
您可以将数据库导入pandas.DataFrame(), 尝试
import pandas as pd
df = pd.read_sql(query, connection, params=(start_date, end_date))
然后轻松执行所需的操作。
在我看来,Pandas是处理大型数据框和表的最佳解决方案。您可以轻松地将随机行作为整个数据框的样本。 在这里看看:
Random row selection in Pandas dataframe
希望有帮助
最诚挚的问候