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...
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 -...
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...
How would I create a nested dictionary given a csv file in Python? Say I want...
How would I create a nested dictionary given a csv file in Python? Say I want to make a dictionary that read {'country':{'China':'Fit', 'China':'Overweight', 'USA': 'Overweight', 'USA': 'Fit', 'England':'Fit'...}, 'category':{'Asian':'Fit', 'Caucasian': 'Overweight', 'Caucasian':'Overweight', 'Asian': 'Fit', 'Middle Eastern': 'Fit'...}} given a file that had country category Weight China Asian Fit China Caucasian Overweight USA Caucasian Overweight USA Asian Fit England Middle Eastern Fit... ... And so on in the file.
PYTHON - You are given a data.csv file in the /root/customers/ directory containing information about your...
PYTHON - You are given a data.csv file in the /root/customers/ directory containing information about your customers. It has the following columns: ID,NAME,CITY,COUNTRY,CPERSON,EMPLCNT,CONTRCNT,CONTRCOST where ID: Unique id of the customer NAME: Official customer company name CITY: Location city name COUNTRY: Location country name CPERSON: Email of the customer company contact person EMPLCNT: Customer company employees number CONTRCNT: Number of contracts signed with the customer CONTRCOST: Total amount of money paid by customer (float in format dollars.cents) Read and analyze the...
In Python: Assume a file containing a series of integers is named numbers.txt and exists on...
In Python: Assume a file containing a series of integers is named numbers.txt and exists on the computer's Disk. Write a program that reads al the numbers stored in the file and calculates their total. - create your own text file called numbers.txt and put in a set of 20 numbers (each number should be between 1 and 100). - Each number should be on its own line. - do not assume that the file will always have 20 numbers...
CODE BLOCK E import csv filename = "D:/python/Week8/files/green.csv" with open(filename) as file: data_from_file = csv.reader(file) header_row...
CODE BLOCK E import csv filename = "D:/python/Week8/files/green.csv" with open(filename) as file: data_from_file = csv.reader(file) header_row = next(data_from_file) for index,column_header in enumerate(header_row): print(index,column_header) How many COUMNS (not rows!) will be printed in the above code?
Send this as a Python file. Note: this is an example where you have the original...
Send this as a Python file. Note: this is an example where you have the original file, and are writing to a temp file with the new information. Then, you remove the original file and rename the temp file to the original file name. Don't forget the import os statement.A file exist on the disk named students.txt The file contains several records and each record contains 2 fields :1. The student's name and 2: the student's score for final exam....
in PYTHON given a specific text file containing a list of numbers on each line (numbers...
in PYTHON given a specific text file containing a list of numbers on each line (numbers on each line are different) write results to a new file after the following tasks are performed: Get rid of each line of numbers that is not 8 characters long Get rid of lines that don't begin with (478, 932, 188, 642, 093)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT