在Python中查找.CSV文件中的最大数字

1 投票
3 回答
7585 浏览
提问于 2025-04-29 11:57

我有一个.csv文件,打开后在Excel里看起来像这样:

enter image description here

我的代码:

myfile = open("/Users/it/Desktop/Python/In-Class Programs/countries.csv", "rb")

    countries = []
    for item in myfile:
        a = item.split(",")
        countries.append(a)

    hdi_list = []
    for acountry in countries:
        hdi = acountry[3]

        try:
            hdi_list.append(float(hdi))
        except:
            pass

    average = round(sum(hdi_list)/len(hdi_list), 2)
    maxNumber = round(max(hdi_list), 2)
    minNumber = round(min(hdi_list), 2)

这段代码运行得很好,不过,当我想找出最大值、最小值或平均值时,我需要同时获取对应的国家名称,并把它打印出来。

我该如何修改我的代码,以便同时获取最小值、最大值和平均值对应的国家名称呢?

暂无标签

3 个回答

2

使用 pandas 模块,下面的 [4][5][6] 应该分别显示最大值、最小值和平均值。请注意,下面的数据除了国家以外与您的数据不匹配。

In [1]: import pandas as pd

In [2]: df = pd.read_csv("hdi.csv")

In [3]: df
Out[3]: 
         Country    HDI
0         Norway  83.27
1      Australia  80.77
2    Netherlands  87.00
3  United States  87.43
4    New Zealand  87.43
5         Canada  87.66
6        Ireland  75.47
7  Liechtenstein  88.97
8        Germany  86.31
9         Sweden  80.54

In [4]: df.ix[df["HDI"].idxmax()]
Out[4]: 
Country    Liechtenstein
HDI                88.97
Name: 7, dtype: object

In [5]: df.ix[df["HDI"].idxmin()]
Out[5]: 
Country    Ireland
HDI          75.47
Name: 6, dtype: object

In [6]: df["HDI"].mean()
Out[6]: 84.484999999999985

假设 列支敦士登德国 的最大值都是:

In [15]: df
Out[15]: 
         Country    HDI
0         Norway  83.27
1      Australia  80.77
2    Netherlands  87.00
3  United States  87.43
4    New Zealand  87.43
5         Canada  87.66
6        Ireland  75.47
7  Liechtenstein  88.97
8        Germany  88.97
9         Sweden  80.54

In [16]: df[df["HDI"] == df["HDI"].max()]
Out[16]: 
         Country    HDI
7  Liechtenstein  88.97
8        Germany  88.97

同样的逻辑也可以用来计算最小值。

3

与其直接把数值放在列表里,不如用元组来代替,像这样:

hdi_list.append((float(hdi), acountry[1]))

然后你可以用这个来代替:

maxTuple = max(hdi_list)
maxNumber = round(maxTuple[0], 2)
maxCountry = maxTuple[1]
1

下面这个方法和你现在的做法差不多,我觉得可能会对你有帮助。不过,如果你开始处理更大或者更复杂的csv文件,建议你看看像“csv.reader”或者“Pandas”这样的工具(之前提到过)。它们在处理复杂的.csv数据时更强大、更高效。你也可以通过Excel和“xlrd”这个工具来处理。

我认为,最简单的方式来把国家名称和它们对应的数值关联起来,就是把你的‘for循环’合并起来。与其用两个单独的‘for循环’分别遍历数据,创建两个不同的列表,不如用一个‘for循环’来创建一个包含相关数据的字典(比如“国家名称”、“人类发展指数”)。你也可以创建一个元组(之前提到过),但我觉得字典更清晰。

myfile = open("/Users/it/Desktop/Python/In-Class Programs/countries.csv", "rb")

countries = []
for line in myfile:
    country_name = line.split(",")[1]
    value_of_interest = float(line.split(",")[3])
    countries.append(
        {"Country Name": country_name, 
         "Value of Interest": value_of_interest})

ave_value = sum([country["Value of Interest"] for country in countries])/len(countries)
max_value = max([country["Value of Interest"] for country in countries])
min_value = min([country["Value of Interest"] for country in countries])

print "Country Average == ", ave_value
for country in countries:
    if country["Value of Interest"] == max_value:
        print "Max == {country}:{value}".format(country["Country Name"], country["Value of Interest"])
    if country["Value of Interest"] == min_value:
        print "Min == {country}:{value}".format(country["Country Name"], country["Value of Interest"])

需要注意的是,如果有多个国家的最小值或最大值相同,这种方法会返回多个国家。

如果你坚持要创建两个独立的列表(像你现在的做法那样),你可以考虑用zip()来连接你的列表(通过索引),这样可以更方便。

zip(countries, hdi_list) = [(countries[1], hdi_list[1]), ...]

例如:

for country in zip(countries, hdi_list):
    if country[1] == max_value:
        print country[0], country[1]

用类似的逻辑来处理最小值和平均值。这种方法是可行的,但不够清晰,维护起来也更困难。

撰写回答