Python 打印用户定义的二维数组行
Python print user defined of rows from 2D array
我有一个根据用户输入从 SQL(使用 PyMySQL)导入的行列表。有时这些 return 可以超过 5000 行(这些存储在二维数组中,至少有 4 列)。这对于用户在屏幕上打印时能够阅读是不切实际的。
我已经实现了一个限制器,它会根据用户的输入 return 前 X 行。但是,我想 return 行样本,而不是第一个 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.")
我建议你使用Pandas。
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
希望对您有所帮助
此致
我有一个根据用户输入从 SQL(使用 PyMySQL)导入的行列表。有时这些 return 可以超过 5000 行(这些存储在二维数组中,至少有 4 列)。这对于用户在屏幕上打印时能够阅读是不切实际的。
我已经实现了一个限制器,它会根据用户的输入 return 前 X 行。但是,我想 return 行样本,而不是第一个 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.")
我建议你使用Pandas。 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
希望对您有所帮助
此致