需求:dom
import numpy as np
from pandas import DataFrame,Series
import pandas as pd函數
abb = pd.read_csv('./data/state-abbrevs.csv')
pop = pd.read_csv('./data/state-population.csv')
area = pd.read_csv('./data/state-areas.csv')excel
將人口數據和各州簡稱數據進行合併
abb_pop = pd.merge(abb,pop,left_on='abbreviation',right_on='state/region',how='outer')
abb_pop.head(3)code
將合併的數據中重複的abbreviation列進行刪除
abb_pop.drop(labels='abbreviation',axis=1,inplace=True)排序
查看存在缺失數據的列
abb_pop.isnull().any(axis=0) # notnull()和all() 裏面還得填axis啊索引
找到有哪些state/region使得state的值爲NaN,進行去重操做
abb_pop.head(5)數據分析
abb_pop['state'].isnull()數學
abb_pop.loc[abb_pop['state'].isnull()]pandas
abb_pop.loc[abb_pop['state'].isnull()]['state/region'].unique()it
結果--->array(['USA','PR'], dtype=object)
爲找到的這些state/region的state項補上正確的值,從而去除掉state這一列的全部NaN
給state的NAN補United States
abb_pop['state/region'] == 'USA'
abb_pop.loc[abb_pop['state/region'] == 'USA']
indexs = abb_pop.loc[abb_pop['state/region'] == 'USA'].index
abb_pop.loc[indexs,'state'] = 'United States'
同理處理'PR'
abb_pop['state/region'] == 'PR'
abb_pop.loc[abb_pop['state/region'] == 'PR']
indexs = abb_pop.loc[abb_pop['state/region'] == 'PR'].index
abb_pop.loc[indexs,'state'] = 'ppprrr'
<u># 提醒不要忘了loc取行,不能直接取(df)
合併各州面積數據areas
abb_pop_area = pd.merge(abb_pop,area,how='outer')
<u># 提醒不要忘了how
咱們會發現area(sq.mi)這一列有缺失數據,找出是哪些行
去除含有缺失數據的行
abb_pop_area['area (sq. mi)'].isnull()
abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()]
indexs = abb_pop_area.loc[abb_pop_area['area (sq. mi)'].isnull()].indexabb_pop_area.drop(labels=indexs,axis=0,inplace=True)
找出2010年的全民人口數據
df_2010 = abb_pop_area.query('year == 2010 & ages == "total"')
query篩選
計算各州的人口密度
abb_pop_area['midu'] = abb_pop_area['population'] / abb_pop_area['area (sq. mi)']
abb_pop_area.head(1)
排序,並找出人口密度最高的五個州 df.sort_values()
abb_pop_area.sort_values(by='midu',ascending=False)['state'].unique()[0:5]
練習7:
簡述None與NaN的區別
假設張三李四參加模擬考試,但張三由於忽然想明白人生放棄了英語考試,所以記爲None,請據此建立一個DataFrame,命名爲ddd3
老師決定根據用數學的分數填充張三的英語成績,如何實現? 用李四的英語成績填充張三的英語成績?
============================================
import random
ddd = DataFrame(data =np.random.randint(90,130,size=(2,2)),index=['英語','數學'],columns=['張三','李四'])
ddd
ddd.loc['數學','張三'] = np.nan
ddd
ddd.fillna(method='ffill',axis=0)
ddd.fillna(method='bfill',axis=1)
練習20:
新增兩列,分別爲張3、李四的成績狀態,若是分數低於90,則爲"failed",若是分數高於120,則爲"excellent",其餘則爲"pass"
df chengji(s): if s<90: return 'failed' if s>120: return 'excellent' else: return 'pass' 【提示】使用函數做爲map的參數
def kaoshi(s):
if s<6000:
return 'failed'
if s>7200:
return 'excellent'
else:
return 'pass'
df['after_sal'] = df['salary'].map(kaoshi)# 也是
df