Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

obtain average from a data extracted from csv

I’m working with a csv file, I extract certain information given a condition, from it I have to obtain the average, but the result I obtain does not allow me to calculate the average, I tried converting it to integer and list but I am still in the same situation.

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)

when I print population I obtain a str like this

1780000
237500
186800
127800

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this is my csv file looks like and i want he average from the country code= AFG, so when i print my population y have this and i can’t have the average from that list

>Solution :

Here’s a step-by-step guide on how to achieve this:

  • Read the CSV file and extract the population data for the specified condition.

  • Convert the population data from strings to integers.

  • Calculate the average population.

      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.")
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading