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
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.")
