Here are the first few rows of the dataset:
This time your aim is to find the safest and least safe locations in San Antonio, Texas. The safeness of a location is measured as 1/(Kills + 0.8 x Injuries + 1). So if a particular location has, say, 3 kills and 5 injuries, its safeness index would be 1/(3 + 0.8 x 5 + 1) = 0.125
You're given the latitude and longitude of each instance of gun violence. Round the latitude and longitude to a single decimal place first and find out the safest location. Print the safest location first and then in the next line, print the most unsafe location
Print these locations in a dictionary format. For example:
{'Latitude': 30.1, 'Longitude': -94.5}
{'Latitude': 72.3, 'Longitude': -96.4}
import pandas as pd
# Reading the gun violence dataset
gun = pd.read_csv('https://query.data.world/s/3iebgxp57luarsikz5wtcwahpjwed7')
# Round Latitude and Longitude to one decimal place
gun['Latitude'] = round(gun['Latitude'], 1)
gun['Longitude'] = round(gun['Longitude'], 1)
# Group the gun dataframe using #Killed and #Injuries and values, and 'Latitude'
# and 'Longitude' as indices
gun_g = gun.pivot_table(values = ['# Killed', '# Injured'],
index = ['Latitude', 'Longitude'],
aggfunc = 'sum')
# Add a column 'Safeness Index' which is calculate by using the formula given
# above
gun_g['Safeness Index'] = 1/(gun_g['# Killed'] + 0.8 * gun_g['# Injured'] + 1)
# Sort the values in the dataframe using the Safeness Index
gun_g.sort_values(by = ['Safeness Index'], inplace = True, ascending = False)
# Reindex the gun_g dataframe so you can access the Latitude and Longitude easily
# as columns
gun_g.reset_index(inplace = True)
# Store the safest and least safe location in two variables as dictionaries
safest = {'Latitude': gun_g.loc[0, 'Latitude'],
'Longitude': gun_g.loc[0, 'Longitude']}
least_safe = {'Latitude': gun_g.loc[len(gun_g['Latitude'])-1, 'Latitude'],
'Longitude': gun_g.loc[len(gun_g['Longitude'])-1, 'Longitude']}
# Print the values of the safest and the least safe location
print(sorted(list(safest.values())))
print(sorted(list(least_safe.values())))
Comments