【问题标题】:Finding the min of a column across multiple lists in python在python中跨多个列表查找列的最小值
【发布时间】:2021-07-02 01:11:19
【问题描述】:

我需要从 csv 文件中找到给定列的最小值和最大值,目前该值是一个字符串,但我需要它是一个整数,现在我将所有行拆分为列表后的输出看起来像这样

['FRA', 'Europe', 'France', '14/06/2020', '390', '10\n']
['FRA', 'Europe', 'France', '11/06/2020', '364', '27\n']
['FRA', 'Europe', 'France', '12/06/2020', '802', '28\n']
['FRA', 'Europe', 'France', '13/06/2020', '497', '24\n']

从那条线以及其他许多条线中,我想找到 第 5 列,目前我这样做的时候

min(column[4]) 

它只是给出每个单独列表的最小值,即该列中的数字,而不是将它们全部分组并获得最小值。

P.S:我对 python 和编码很陌生,我也必须在不导入任何模块的情况下这样做。

为你阿兹罗。

def main(csvfile,country,analysis):
infile = csvfile
datafile = open(infile, "r")
country = country.capitalize()     
if analysis == "statistics":
    for line in datafile.readlines():
        column = line.split(",")
        if column[2] == country:

【问题讨论】:

  • 您正在使用单词列。我们是在谈论我们的列表中的数据框吗?
  • 你能分享读取数据和构建列表的代码吗?
  • 我在想我需要把它转换成整数

标签: python list minimum


【解决方案1】:

您可以使用pandas,它允许读取csv文件并将它们操作为DataFrame,然后很容易从列中检索min/max

import pandas as pd

df = pd.read_csv("test.txt", sep=',')

mini = df['colName'].min()
maxi = df['colName'].max()
print(mini, maxi)

然后,如果您已经在列表列表中读取数据,则最多使用内置 minmax

# use rstrip() when reading line, to remove leading \n
values = [
    ['FRA', 'Europe', 'France', '14/06/2020', '390', '10'],
    ['FRA', 'Europe', 'France', '14/06/2020', '395', '10']
]

mini = min(values, key=lambda x: int(x[4]))[4]
maxi = max(values, key=lambda x: int(x[4]))[4]

【讨论】:

    【解决方案2】:

    看看pandas 库,尤其是DataFrame 类。这可能是处理 .csv 文件和一般表格数据的首选方法。

    基本上,您的代码应该是这样的:

    import pandas as pd
    df = pd.read_csv('my_file.csv') # Construct a DataFrame from a csv file
    print(df.columns) # check to see which column names the dataframe has
    print(df['My Column'].min())
    print(df['My Column'].max())
    

    【讨论】:

      【解决方案3】:

      有更短的方法可以做到这一点。但是这个例子是一步一步来的:

      # After you read a CSV file, you'll have a bunch of rows.
      rows = [
          ['A', '390', '...'],
          ['B', '750', '...'],
          ['C', '207', '...'],
      ]
      
      # Grab a column that you want.
      col = [row[1] for row in rows]
      
      # Convert strings to integers.
      vals = [int(s) for s in col]
      
      # Print max.
      print(max(vals))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-18
        • 2021-07-28
        • 1970-01-01
        • 2021-01-25
        • 2013-11-06
        • 2019-03-17
        • 1970-01-01
        • 2019-11-10
        相关资源
        最近更新 更多