首先导入文件,并查看数据样本
In [54]:
abbr = pd.read_csv("./usapop/state-abbrevs.csv")
abbr.head()
Out[54]:
In [55]:
areas = pd.read_csv("./usapop/state-areas.csv")
areas.head()
Out[55]:
In [56]:
pop = pd.read_csv("./usapop/state-population.csv")
pop.head()
Out[56]:
合并pop与abbrevs两个DataFrame,分别依据state/region列和abbreviation列来合并。
为了保留所有信息,使用外合并。
In [57]:
pop2 = pop.merge(abbr,left_on="state/region",right_on="abbreviation",how="outer")
# 用外连接(或者左链接)
pop2
Out[57]:
去除abbreviation的那一列(axis=1)
In [58]:
pop2.drop("abbreviation",axis=1,inplace=True)
# 默认axis=0删除行
# inplace是否在原表上删除,默认是False不在原表上删除
In [59]:
pop2.head()
Out[59]:
查看存在缺失数据的列。
使用.isnull().any(),只有某一列存在一个缺失数据,就会显示True。
In [60]:
cond = pop2.isnull().any(axis=1)
cond
Out[60]:
In [61]:
pop2[cond]
Out[61]:
In [ ]:
查看缺失数据
根据数据是否缺失情况显示数据,如果缺失为True,那么显示
In [62]:
cond_state = pop2["state"].isnull()
找到有哪些state/region使得state的值为NaN,使用unique()查看非重复值
扫描二维码关注公众号,回复:
1809561 查看本文章
In [63]:
pop2[cond_state]["state/region"].unique()
Out[63]:
为找到的这些state/region的state项补上正确的值,从而去除掉state这一列的所有NaN!
记住这样清除缺失数据NaN的方法!
In [64]:
cond_pr = pop2["state/region"] == "PR"
cond_usa = pop2["state/region"] == "USA"
In [65]:
pop2["state"][cond_pr] = "Puerto Rico"
pop2["state"][cond_usa] = "United State"
In [66]:
pop2.head()
Out[66]:
In [67]:
pop2.isnull().any()
Out[67]:
合并各州面积数据areas,使用左合并。
思考一下为什么使用外合并?
In [68]:
areas.head()
Out[68]:
In [69]:
pop3 = pop2.merge(areas,how="outer")
pop3.head()
Out[69]:
In [ ]:
继续寻找存在缺失数据的列
In [70]:
pop3.isnull().any()
Out[70]:
In [71]:
cond_area = pop3["area (sq. mi)"].isnull()
In [72]:
pop3[cond_area]
Out[72]:
我们会发现area(sq.mi)这一列有缺失数据,为了找出是哪一行,我们需要找出是哪个state没有数据
In [73]:
# usa面积缺失,就可以吧所有的州面积求和
usa_area = areas["area (sq. mi)"].sum()
In [74]:
# 把美国的面积赋值到pop3中
pop3["area (sq. mi)"][cond_area] = usa_area
In [75]:
pop3
Out[75]:
去除含有缺失数据的行
In [76]:
pop3.isnull().any()
Out[76]:
查看数据是否缺失
In [77]:
pop3.dropna(inplace=True)
In [78]:
pop3.isnull().any()
Out[78]:
找出2010年的全民人口数据,df.query(查询语句)
In [79]:
pop3.head()
Out[79]:
In [80]:
pop3.query("year==2010 & ages=='total' & state=='United State'")
Out[80]:
In [81]:
pop_2010 = pop3.query("year==2010 & ages=='total'")
pop_2010
Out[81]:
对查询结果进行处理,以state列作为新的行索引:set_index
In [82]:
pop_2010.set_index("state",inplace=True)
In [83]:
pop_2010.shape
Out[83]:
计算人口密度。注意是Series/Series,其结果还是一个Series。
In [84]:
pop_dense = pop_2010["population"] / pop_2010["area (sq. mi)"]
pop_dense
Out[84]:
排序,并找出人口密度最高的五个州sort_values()
In [85]:
pop_dense.sort_values(inplace=True)
pop_dense
Out[85]:
In [86]:
pop_dense.tail()
Out[86]:
找出人口密度最低的五个州
In [87]:
pop_dense.head()
Out[87]:
要点总结:
- 统一用loc()索引
- 善于使用.isnull().any()找到存在NaN的列
- 善于使用.unique()确定该列中哪些key是我们需要的
- 一般使用外合并、左合并,目的只有一个:宁愿该列是NaN也不要丢弃其他列的信息