In: Computer Science
Using Python: cities = pd.DataFrame( [[2463431, 2878.52], [1392609, 5110.21], [5928040, 5905.71]], columns=['population', 'area'], index=pd.Index(['Vancouver','Calgary','Toronto'], name='city') )
Do the following:
# The code for the required problem is given below with screenshots of code
# for indentation and output and if you feel any problem then feel free to ask
# importing pandas module with name pd
import pandas as pd
# data frame named cities
cities = pd.DataFrame(
[[2463431, 2878.52], [1392609, 5110.21], [5928040, 5905.71]],
columns=['population', 'area'],
index=pd.Index(['Vancouver','Calgary','Toronto'], name='city')
)
# empty list named density to store the calculted densities
density=[]
# calculating the densities and storing them into the list
for i in range(3):
density.append( cities.population[i]/cities.area[i])
# Appending the density column into the data frame
cities['density']=density
# appending the rank column into the data frame according
# the rank function with ascending parameter is used
# for achieving the ranking as required
cities['rank'] = cities['density'].rank(ascending=False)
# printing the updated data frame
print(cities)
OUTPUT:-