需求:导入文件,查看原始数据,将美国各州人口数据和简称合并,去掉重复的一列。合并各州面积数据,找到2010年的全民人口数据,计算各州的人口密度,排序,找到人口密度最高的州。
链接:https://pan.baidu.com/s/1VmWnvVkgL0QalnoCrQCEfg
提取码:qgxu
表1:州名和简称
表2:各州各时间、各年龄段人口
表3:各州面积
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
import pandas as pd
df_abbrevs = pd.read_csv("state-abbrevs.csv")
df_population = pd.read_csv("state-population.csv")
df_usa = pd.merge(df_abbrevs, df_population, left_on="abbreviation", right_on="state/region")
print(df_usa)
df_usa = df_usa.drop("abbreviation", axis=1)
print(df_usa)
df_area = pd.read_csv("state-areas.csv")
df_usa = pd.merge(df_usa, df_area, on="state")
print(df_usa)
df_usa_2010 = df_usa[df_usa.loc[:, "year"] == 2010].loc[:,["state", "population", "area (sq. mi)"]]
print(df_usa_2010)
df_usa_2010 = pd.pivot_table(df_usa_2010, index="state", values=["population", "area (sq. mi)"], aggfunc="sum")
df_usa_2010["area (sq. mi)"] = df_usa_2010["area (sq. mi)"]/2
df_usa_2010["density"] = df_usa_2010.apply(lambda x: x["population"] / x["area (sq. mi)"], axis=1)
print(df_usa_2010)
df_usa_2010 = df_usa_2010.sort_values(by="density", axis=0)
print(df_usa_2010)
df_usa_2010.iloc[-1, :]
print(df_usa_2010)