python數據清洗實戰入門筆記(三)表處理


數據集地址:https://pan.baidu.com/s/1kMH1AhE8RUyaT73rvJsVPQ
提取碼:aai6

數據篩選

image-20200513232539386

練習

import pandas as pd
import numpy as np
import os
# 更改文件路勁
os.chdir(r'G:\pythonProject\pc\Python數據清洗\data')
df = pd.read_csv('baby_trade_history.csv', encoding='utf-8',dtype={'user_id':str})
#數據篩選
#查看數據

df.info()

image-20200515202226847
image-20200515202248780
image-20200515202306124
image-20200515202321219

簡單索引
df['user_id']

image-20200515202411045

df['user_id'][1:5]# 第二行到第五行(左開右閉)

image-20200515202434402

# 多個變量選擇
df[:5][['user_id','buy_mount','day']]

image-20200515202458395

# loc和iloc 的使用
df.loc[3:4]# 選擇行索引標籤

image-20200515202535469

df.loc[:,['user_id','buy_mount']]#選擇某兩列

image-20200515202614515

df.loc[1:3,['user_id','buy_mount']] #loc在這裏選擇的是行索引標籤

image-20200515202650278

df.loc[df.user_id =='786295544',['user_id','buy_mount','day']]

image-20200515203208364

df.loc[(df.user_id =='786295544') | (df.user_id =='444069173'),['user_id','buy_mount','day']]# 多個條件選擇

image-20200515203304135

#注意iloc是位置
df.iloc[:,1:4] #按照位置來選擇第二列到第四列(左開右閉和df的選擇一樣)

image-20200515203412642

df.iloc[:,[0,2]] # 按照位置來選擇第1列和第3列,這和上面不一樣,左開右開,如果加了[]中間用,號

image-20200515203452242

df.iloc[3,[1,2]] #選擇第4行,第2列和第3列數據, 這裏的3代表的不是索引標籤而是位置

image-20200515203514901

df.iloc[2:7,[1,2]] #選擇第3行到第7行,第2列和第3列數據

image-20200515203535879

  • 注意loc和iloc的區別
df.loc[1:5]#索引,就是1行到5行

image-20200515203725167

df.iloc[1:5]#位置,第二行到第五行(左開右閉)

image-20200515203909804

數據增加和刪除

image-20200515201900095

image-20200515201921675

練習

#增加一列,購買量,購買量超過3的爲高,低於3的爲底
df['購買量'] = np.where(df['buy_mount'] >3,'高','低')
df
# 增加行在dataframe中不常用,後面會用其他方法實現
# 可以使用append方法在 dataframe末尾實現

image-20200515204229952

  • 可以使用insert方法
  • df.insert(位置,變量名稱,值)
  • 將auction_id取出來,放在一列
# 先將這一列取出來,賦值給對象auction_id,然後在數據中刪除這一列,再將其添加進去
auction_id = df['auction_id']
del df['auction_id']
df.insert(0, 'auction_id', auction_id)
df.head(5)

image-20200515204352255

  • 刪除
# 刪除這兩列,加inplace代表是否在原數據上操作,1代表沿着列的方向
# 同時刪除多個變量,需要以列表的形式
# 注意inplace =True,代表是否對原數據操作, 否則返回的是視圖,並沒有對原數據進行操作
# labels表示刪除的數據, axis表示作用軸,inplace=True表示是否對原數據生效,
# axis=0按行操作, axis=1按列操作
df.drop(labels = ['property', '購買量'],axis = 1,inplace=True) #刪除這兩列,加inplace代表是否在原數據上操作, 1代表沿着列的方向
df.head(5)

image-20200515204509141

# 按行刪除法
df.drop(labels = [3,4],inplace = True,axis= 0) # 刪除索引標籤3和4對應的行
df.drop(labels= range(6,11),axis=0,inplace=True)  #刪除索引名稱1到10,注意range迭代器產生的是1到100
df.head(10)

image-20200515204532029

數據的修改和查找

image-20200515201944185

練習

df1 = pd.read_csv('sam_tianchi_mum_baby.csv',encoding = 'utf-8',dtype =str)
df1.head(5)

image-20200515204753446

# 將gender爲0的改爲女性,1改爲男性,2改爲未知
df1.loc[df1['gender'] =='0','gender'] ="女性"
df1.loc[df1['gender'] =='1','gender'] ='男性'
df1.loc[df1['gender'] =='2','gender'] ='未知'
df1.head(10)

image-20200515204813849

  • 修改列名稱
  • basic.rename(columns={},index={})
# 修改列標籤和行索引名稱
df1.rename(columns = {'user_id':'用戶ID','birthday':'出生日期','gender':'性別'},inplace = True)
df1.rename(index = {1:'one',10:'ten' },inplace = True) #修改行索引名稱
df1.head(11)

image-20200515204847899

df1.reset_index(drop=True,inplace=True)# 重置索引
df1.head(11)

image-20200515204913743

  • 查詢
# 條件查詢
df[df.buy_mount > 3] #性別等於未知

image-20200515204956481

df[~(df.buy_mount > 3)] # ~代表非

image-20200515205026921

df[ (df.buy_mount > 3) &  (df.day > 20140101)] # 多條件查詢

image-20200515205110295

#使用between,inclusive=True代表包含
df[ df['buy_mount'].between(4,10,inclusive=True)]

image-20200515205137548

# 使用pd.isin()方法
# 包含
df[df['auction_id'].isin([41098319944, 17916191097,21896936223])]

image-20200515205200230

數據整理

橫向堆疊在數據清洗中不常用,縱向堆疊可以理解爲把不同的表,字段名稱一樣整合在一起

image-20200515202010381

image-20200515202022866

image-20200515202041549

image-20200515202100050

練習

import xlrd
workbook = xlrd.open_workbook('meal_order_detail.xlsx')
sheet_name = workbook.sheet_names() #返回所有sheet的列表
sheet_name

image-20200515205409004

order1 = pd.read_excel('meal_order_detail.xlsx',sheet_name ='meal_order_detail1')
order2 = pd.read_excel('meal_order_detail.xlsx',sheet_name ='meal_order_detail2')
order3 = pd.read_excel('meal_order_detail.xlsx',sheet_name ='meal_order_detail3')
order = pd.concat([order1,order2,order3],axis=0,ignore_index=False)# 忽略原來的索引
print(order1.shape)
print(order2.shape)
print(order3.shape)
print(order.shape)

image-20200515205432748

# 通過循環方式進行合併
basic = pd.DataFrame()
for i in sheet_name:
    basic_i = pd.read_excel('meal_order_detail.xlsx', header = 0,sheet_name=i,encoding='utf-8')
    basic = pd.concat([basic,basic_i],axis=0)
basic.shape

image-20200515205452384

  • 關聯
  • 關聯字段必須類型一致
df3 = pd.read_csv('baby_trade_history.csv', encoding='utf-8',dtype={'user_id':str})# 交易數據
df4 = pd.read_csv('sam_tianchi_mum_baby.csv',encoding = 'utf-8',dtype =str)#嬰兒信息
df5 = pd.merge(left = df3, right=df4,  how='inner',  left_on='user_id', right_on = 'user_id')# 內連接
df5.head(10)

image-20200515205547715

層次化索引

image-20200515202117401

練習

df = pd.read_csv('baby_trade_history.csv', encoding='utf-8',dtype={'user_id':str},index_col=[3,1])#將數據第4列和第1列當成索引
df.head()

image-20200515205804701

df.loc[28]#第一層引用

image-20200515205837749

df.loc[28].loc[17916191097]#第二層引用

image-20200515205945122

  • 直接引用兩層
  • df3.loc[(a,b),:] #a和b分別代表第一層和第二層的索引
  • 接受tuple
df.loc[(28,[17916191097,532110457]),:]# 第二層索引選擇,多個選擇
df

image-20200515210016005

df.loc[(28,[17916191097,532110457]),['auction_id','cat_id']]# 第二層索引選擇,選擇2個變量

image-20200515210041309

df.loc[([28,50014815])] #第一層索引爲28和50014815

image-20200515210103901

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章