Question

In: Computer Science

{PYTHON }You have a CSV file containing the location and population of various cities around the...

{PYTHON }You have a CSV file containing the location and population of various cities around the world. For this question you'll be given a list of cities and return the total population across all those cities. Write a function named "total_population" that takes a string then a list as parameters where the string represents the name of a CSV file containing city data in the format "CountryCode,CityName,Region,Population,Latitude,Longitude" and the second parameter is a list where each element is itself a list containing 3 strings as elements representing the CountryCode, CityName, and Region in this order. Return the total population of all cities in the list. Note that the city must match the country, name, and region to ensure that the correct city is being read.

import pandas as pd #to read csv into a dataset
  
def total_population(file_name, city_list): #function definition with required parameters
data = pd.read_csv(file_name) #reading a csv file
pop = 0 #for storing population
for i in city_list: #looping through the list
temp = data.loc[(data.Country == int(i[0])) & (data.City == i[1]) & (data.Region == i[2])] #selecting row matching the conditions
pop += int(temp['Population']) #summing population for each city
return pop

error on input ['cities.csv', [['nl', 'vlissingen', '10'], ['ca', 'whitehorse', '12'], ['ph', 'camflora', 'H2'], ['gb', 'johnshaven', 'T6']]]: 'DataFrame' object has no attribute 'CountryCode'

also that return outside function

Solutions

Expert Solution

Here is the code:

def total_population(filename,city_list):
    data = pd.read_csv(filename)  # reading the data

    all_population = list()   # creating a list to store the corresponding populations
    for city in city_list:
        for loop1 in range(len(data)):
            if(city[0] == data['CountryCode'][loop1] and city[1] == data['CityName'][loop1] and city[2] == data['Region'][loop1]):
                all_population.append(data['Population'][loop1])

    # printing the results
    for loop2 in range(len(city_list)):
        print('Population of ' + str(city_list[loop2][1]) + ' is: ' + str(all_population[loop2]))
            
# calling the function
city_list = [[33, 'Chicago', 'West'],[22,'DC','East']]
total_population('sample_data_df.csv',city_list)

Here is the results:

For any doubt please comment below.


Related Solutions

{PYTHON }You have a CSV file containing the location and population of various cities around the...
{PYTHON }You have a CSV file containing the location and population of various cities around the world. For this question you'll be given a list of cities and return the total population across all those cities. Write a function named "total_population" that takes a string then a list as parameters where the string represents the name of a CSV file containing city data in the format "CountryCode,CityName,Region,Population,Latitude,Longitude" and the second parameter is a list where each element is itself a...
Problem 9 - PYTHON There is a CSV-formatted file called olympics2.csv. Write code that creates a...
Problem 9 - PYTHON There is a CSV-formatted file called olympics2.csv. Write code that creates a dictionary named country_olympians where the keys are country names and the values are lists of unique olympians from that country (no olympian's name should appear more than once for a given country). Name,Sex,Age,Team,Event,Medal A Dijiang,M,24,China,Basketball,NA A Lamusi,M,23,China,Judo,NA Gunnar Nielsen Aaby,M,24,Denmark,Football,NA Edgar Lindenau Aabye,M,34,Sweden,Tug-Of-War,Gold Christine Jacoba Aaftink,F,21,Netherlands,Speed Skating,NA Christine Jacoba Aaftink,F,21,Netherlands,Speed Skating,NA Christine Jacoba Aaftink,F,25,Netherlands,Speed Skating,NA Christine Jacoba Aaftink,F,25,Netherlands,Speed Skating,NA Christine Jacoba Aaftink,F,27,Netherlands,Speed Skating,NA Christine...
build a python program that will be performing: - Read a CSV file 'annual.csv' enterprise into...
build a python program that will be performing: - Read a CSV file 'annual.csv' enterprise into a data structure - Count the number of rows and columns - Determine if the data contains empty values - Replace the empty values by 'NA' for strings, '0' for decimals and '0.0' for floats - Transform all Upper case characters to Lower case characters - Transform all Lower case characters to Upper case characters - save back the 'repaired' array as csv -...
Goal: to write a Python program that will read a playlist from a CSV file and...
Goal: to write a Python program that will read a playlist from a CSV file and display it in the console in the form of a table. https://s3.eu-west-2.amazonaws.com/bb-python-modules/Coursework/CW3/playlist_text_question.html The following is a link to the question. It includes all instruction and a template file (with additional instructions) where the answer must be completed.
Using Python read dataset in the HTML in beautiful way. You need to read CSV file...
Using Python read dataset in the HTML in beautiful way. You need to read CSV file ( Use any for example, You can use small dataset) You need to use pandas library You need to use Flask Make search table like YouTube has.
Recall that the population average of the heights in the file "pop1.csv" is μ = 170.035....
Recall that the population average of the heights in the file "pop1.csv" is μ = 170.035. Using simulations we found that the probability of the sample average of the height falling within 1 centimeter of the population average is approximately equal to 0.626. From the simulations we also got that the standard deviation of the sample average is (approximately) equal to 1.122. In the next 3 questions you are asked to apply the Normal approximation to the distribution of the...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns:...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns: None Description : You want to see what order the items of a particular category in your file would be in if you sorted them by rating. Given a file, a category of clothing, and an order boolean (True for ascending order, False for descending order), create a function that writes a file called “sorted_items.csv” that includes all of the items in the specified...
python - needed asap (thank you in advance!!!!) Using the provided climate_data_Dec2017.csv file, find out how...
python - needed asap (thank you in advance!!!!) Using the provided climate_data_Dec2017.csv file, find out how many readings there were across our recorded weather stations for each wind direction on the 26th of December. The file contains data for more than this particular day. To make sure that you only include readings from the 26th, you should use pandas to filter the data. If any wind direction value can still be found for the other days but not 26th, it...
PYTHON LANGUAGE Write the data in variable artist_songs into a csv file, 'songs.txt', where the first...
PYTHON LANGUAGE Write the data in variable artist_songs into a csv file, 'songs.txt', where the first column is singer name and second column is a song name. Each line should have a singer and a song name. Use "Name" and "Song" as headers. Do not include double quotation marks (") in your CSV but you should include apostrophes where necessary (for example, for the song "We Don't Talk Anymore"). In [110]: artist_songs = { 'Taylor Swift': ['Love Story', 'You need...
Use Python to Load a file containing a list of words as a python list :param...
Use Python to Load a file containing a list of words as a python list :param str filename: path/name to file to load :rtype: list
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT