在 python 中的多个列表中查找列的最小值

Finding the min of a column across multiple lists in python

我需要从 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:

您可以使用 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]

看看图书馆pandas and especially the DataFrameclass。这可能是一般处理 .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())

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

# 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))