代码之家  ›  专栏  ›  技术社区  ›  Joan Lopez

从csv中提取的数据获得平均值

  •  1
  • Joan Lopez  · 技术社区  · 1 年前

    我使用的是csv文件,我在给定条件下提取某些信息,我必须从中获得平均值,但我获得的结果不允许我计算平均值,我尝试将其转换为整数和列表,但我仍然处于相同的情况。

    city=open('ciudades.csv')
    lineas=csv.reader(city)
    for a,name,countrycode,district, population in lineas:
        if countrycode =='AFG':
            print(population)
            a=[population]
            #a2=int(population)
            b=a.mean()
            print(b)
            #print(a2)
    

    当我打印人口时,我会得到这样的str

    1780000
    237500
    186800
    127800
    

    enter image description here

    这是我的csv文件,我想要国家代码=AFG的平均值,所以当我打印我的人口时,我有这个,我不能有那个列表的平均值

    2 回复  |  直到 1 年前
        1
  •  1
  •   Chris    1 年前

    没有 mean 函数。您需要在列表中获取这些值,然后将这些值求和并除以它们的长度。列表理解会很好地发挥作用。

    city = open('ciudades.csv')
    lineas = csv.reader(city)
    
    populations = [
      int(population)
      for a, name, countrycode, district, population in lineas
      if countrycode == 'AFG'
    ]
    
    avg = sum(populations) / len(populations)
    
        2
  •  0
  •   Proyash Paban Sharma Borah    1 年前

    以下是如何实现这一目标的分步指南:

    • 读取CSV文件并提取指定条件的总体数据。

    • 将填充数据从字符串转换为整数。

    • 计算平均人口。

        import csv
      
        # Open the CSV file
        with open('ciudades.csv') as city:
            lineas = csv.reader(city)
      
            # Initialize an empty list to store populations
            populations = []
      
            # Iterate through the rows of the CSV file
            for a, name, countrycode, district, population in lineas:
                # Check if the country code is 'AFG'
                if countrycode == 'AFG':
                    # Convert population to integer and add to the list
                    populations.append(int(population))
      
            # Calculate the average population
            if populations:
                average_population = sum(populations) / len(populations)
                print(f"The average population is {average_population}")
            else:
               print("No data found for the specified condition.")