【问题标题】:Python print user defined of rows from 2D arrayPython打印用户定义的二维数组中的行
【发布时间】:2019-09-30 22:14:31
【问题描述】:

我有一个根据用户输入从 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.")

【问题讨论】:

    标签: python pymysql


    【解决方案1】:

    我建议你使用 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

    希望对你有帮助

    最好的问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2013-07-26
      • 2016-11-27
      相关资源
      最近更新 更多