數據分析篇(五)
- 2019 年 10 月 6 日
- 筆記
實例:
# 導入模組
import pandas as pd
import numpy as np
# pandas創建一個二維數組
attr = pd.DataFrame(np.arange(12).reshape(3,4))
print(attr)
輸出:
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
# 和numpy不同的是在第一行和第一列的地方多了索引。
# 行索引叫做index,是0軸
# 列索引叫做columns,是1軸
我們試著添加兩個參數:
attr = pd.DataFrame(np.arange(12).reshape(3,4),index=list('qwe'),columns=list('zxcv'))
就會是另一種結果。
z x c v
q 0 1 2 3
w 4 5 6 7
e 8 9 10 11
DataFrame也是可以傳入字典的。
dict = {'name':['張三','李四'],'age':[18,20],'tel':[10010,10086]}
attr1 = pd.DataFrame(dict)
pritnt(attr1)
會輸出:
name age tel
0 張三 18 10010
1 李四 20 10086
同樣,放入列表也是一樣的。
屬性:
# 獲取行索引
attr2.index
# 獲取列索引
attr2.columns
# 獲取值
attr2.values
# 查看幾行幾列
attr2.shape
# 查看類型
attr2.dtype
# 查看數據的維度
attr2.ndim
# 顯示前幾行數據,默認為5行
attr2.head(2) # 取前兩行數據
# 顯示末尾幾行數據,默認為5行
attr2.tail(2) # 取末尾兩行數據
# 查看詳細資訊,行,列,索引,類型,記憶體等
attr2.info()
# 快速統計均值,標準差,最大值,最小值,四分位
attr2.describe()
# 當然只會統計數字類型的。
DataFrame排序
# 按照年齡排序(從小到大)
attr2 = attr2.sort_values(by="age")
# 從大到小
attr2 = attr2.sort_values(by="age",ascending=False)
# 取行或取列
# 以下我們認為attr3中有很多數據,欄位還是和上面的一樣
# 取前50行數據
attr3[:50]
# 取前20行的name欄位
attr3[:20]['name']
# 單獨取某一列的數據
attr3['name']
# 通過標籤取某個值
# attr4數據假如是這樣
name age tel
0 張三 18 10010
1 李四 20 10086
attr4.loc['0','name'] # 李四
attr4.loc['1'] # 李四 20 10086
attr4.loc['1',:] # 李四 20 10086
attr4.loc[:,'age'] # 18 20
取多行
attr4.loc[['0','1']]
取多列
attr4.loc[:,['name','age']]
# 通過索引來取值
attr4.iloc[1,:] # 取第二行
attr4.iloc[:,1] # 取第二列
attr4.iloc[:,[0,2]] # 取第一列和第三列
attr4.iloc[[0,1],[0,2]] # 取第一行和第二行的第一列和第三列
# 布爾索引
# 取出年齡大於10的
attr4[attr4['age']>10]
# 取出年齡大於10,小於20的
attr4[(10<attr4['age'])&(attr4['age']<20)]
# &表示and |表示或
pandas中字元串的方法
# 這裡只介紹常用幾種
# 模糊查詢名字含有三的是str.contains()
a = attr1.loc[attr1['name'].str.contains('三')]
print(a)
# str.lower(),str.upper() 轉換大小寫
# str.replace() 替換字元串
# str.split() 分割
# str.len() 獲取長度
等等,還有很多。
缺失數據的處理
我們如果讀取爬去到的大量數據,可能會存在NaN值。
出現NaN和numpy中是一樣的,表示不是一個數字。
我們需要把他修改成0獲取其他中值,來減少我們計算的誤差。
# 判斷是否為NaN
pd.isbull(attr4) # 還有一個pd.notbull(attr4) 剛好相反
# 取值不為空的name列
attr4[pdnotnull(attr4['name'])]
# 刪除存在NaN的行
attr4.deopna(axis=0) # 列就是axis = 1
# 想刪除某一列全部為NaN的行
attr4.deopna(axis=0,how='all')
# 只要有一個NaN就刪除,也就是默認的
attr4.deopna(axis=0,how='any')
# 把所有NaN填充為0
attr4.fillna(0)
# 填充均值
attr4.fillna(attr4.mean())
# 賦值為NaN值
att4['age'][0] = np.nan
# 賦值為0的數據為NaN
attr4[attr4==0] = np.nan
nan是不會參與平均值等計算的,0會參與計算。
pandas 連接MongoDB資料庫
# 導入操作MongoDB的模組
from pymongo import MongoClient
import pandas as pd
# 鏈接
client = pymongo.MongoClient()
# 讀取
db = client['xxx']['xxxx']
data = pd.DataFrame(list(db.find()))
即可。
# 平均數(age)
attr4['age'].mean()
# max,mix等都是一樣的
# 假如name中有重複的,我們想獲取有多人人,重複的去除
len(attr4['name'].unique())