日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

【Python數(shù)據(jù)挖掘】第一篇

 highoo 2019-03-20
一、數(shù)據(jù)讀取

1. pandas 數(shù)據(jù)讀?。?/span>

1
2
import pandas as pd
df = pd.read_csv("G:\\...\\NBA.csv",encoding='gbk')

read_csv 的重要參數(shù):

復(fù)制代碼
filepath_or_buffer:  # 文件的路徑,URL或任何具有read()方法的對象。
sep :     # 分隔符,默認(rèn)為 , 
header:   # 列名 , 默認(rèn)為 header=0  取第0行做為數(shù)據(jù)集的列名
names:    # 指定數(shù)據(jù)集的列名稱,配合header=None 使用  
encoding: # 編碼格式
na_values:["Nope , ..."]      # 數(shù)據(jù)集中的字符串"Nope"被識別為NaN , ...
keep_defalut_na:   # 如果指定了na_values,并且keep_default_na是False默認(rèn)的NaN值被覆蓋
na_filter:         # 默認(rèn)True,對缺失值進(jìn)行檢測,F(xiàn)alse為不處理。
error_bad_lines:   # 默認(rèn)True,如果False,跳過錯誤行數(shù)據(jù)
warn_bad_lines:    # 默認(rèn)True,如果error_bad_lines為False,而warn_bad_lines為True,則會輸出每個“壞行”的警告
復(fù)制代碼

2、Missing data 處理

復(fù)制代碼
DataFrame.dropna()       # 返回沒有NaN值的數(shù)據(jù)集
DataFrame.fillna(X)      # 將X填充到數(shù)據(jù)集中的NaN值
DataFrame.replace([to_replace, value, ...])   # 將to_replace 替換為 value , 

# 例子:
df.replace(np.nan,'xx',regex=False)    # 將NaN值替換為xx , regex 若為True 將to_value 當(dāng)作正則進(jìn)行匹配!
復(fù)制代碼
 二、DataFrame與Series

1、DataFrame 是一個表格型數(shù)據(jù)結(jié)構(gòu),既有行索引又有列索引,看作由Series組成的字典。

1
df = pd.read_csv("G:\\....\\NBA.csv",encoding='gbk')

重要方法:

 

復(fù)制代碼
查看:
    head([n])           # 返回前n行
    tail([n])           # 返回最后n行
    df[' 列名 ']        # 返回某一列的數(shù)據(jù) 
    df.列名             # 返回某一列的數(shù)據(jù) 

添加 / 修改整列 :
    df[' 列名 '] = 'xxx '   # (添加/修改) 一列,內(nèi)容為xxx

刪除:
    del df[' 列名 ']    # 刪除某一列
    df.pop('列名')      # 返回項(xiàng)目并從DataFrame中刪除

列運(yùn)算:
    df[col3] = df[col1] + df[col2]

判斷:
    df[ ' 列名 ' ]  > 100     # 符合顯示 True , 否則False
復(fù)制代碼

 

重要屬性:

1.index

1
2
df.index
# RangeIndex(start=0, stop=3922, step=1)    # 3922文件總行數(shù) ,

2.columns    返回列名

1
2
df.columns
# Index(['序號', 'Player', 'height', 'weight', 'collage', 'born', 'birth_city','birth_state'],dtype='object')

3.shape

1
2
df.shape
# (3922, 8)   數(shù)據(jù)集一共3922行,8列

4.dtypes      返回每一列數(shù)據(jù)類型

1
2
3
4
5
6
7
8
9
10
df.dtypes
# 序號              int64
# Player           object
# height           float64
# weight           float64
# collage          object
# born             float64
# birth_city       object
# birth_state      object
# dtype: object

行選取 

1.切片

1
df[:5]  或  df [10]

2.特殊的索引選取方式

1
df.iloc[0]     # 返回索引為0的行信息

2、Series 一維數(shù)組對象,由一組數(shù)據(jù)和與之相關(guān)的數(shù)據(jù)標(biāo)簽(索引)組成。

1
2
3
4
5
series = df['列名']
series = df.列名
# 篩選
s2 = series[ series > 100 ]   # 返回大于100的數(shù)據(jù)集

屬性:

1
2
series.index
series.value

方法:

1
2
3
series.value_counts()       # 出現(xiàn)頻數(shù)
series.unique()                 # 返回對象中的唯一值的np.ndarray。
len( series.unique )          # 查看長度

3、創(chuàng)建DataFrame 與 Series

1、創(chuàng)建Series

1
2
3
4
5
6
7
8
9
10
11
# 1. 字典形式 :
sdata = {"A":'123',"B":'456'}
series1 = pd.Series( sdata )
# 2. 數(shù)組形式 :
series2 = pd.Series([1,2,3,4,5] )   # 默認(rèn)索引從0 開始, ...
series2 = pd.Series([1,2,3,4,5] , index = ['a','b','c','d','e'] )
series2 = pd.Series([1,2,3,4,5] , index = list('abcde') )
# 3. 實(shí)數(shù)形式 :
series3 = pd.Series(11 , index = list('abc') )

2、創(chuàng)建DataFrame

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 1. 字典形式
# 一層字典:
data = {
    'state':['Ohio','Nevada','Ohio'],
    'year':[1999,1888,1777],
    'pop':[1.4,1.2,1.1]
}
df1 = pd.DataFrame(data)          # 列名:pop,year,stats(亂序) , 行索引默認(rèn)從0開始
df1 = pd.DataFrame(data , columns = ['pop','year','stats'])   # 指定數(shù)據(jù)表中列名順序
df1 = pd.DataFrame(data , index = ['one','two','three'] )   # 指定索引
# 兩層字典:
data = {
    'A':{'user':'alex','age':20},
    'B':{'user':'eric','age':10},
}
df2 = pd.DataFrame(data)        # 外層字典的key作為列 , 內(nèi)層key作為行索引
df2 = pd.DataFrame(data , index = ['user','age'])   # 顯式指出行索引
# 2. 二維數(shù)組
arr = [ [1,2,3,4] , [5,6,7,8] ]
pd.DataFrame(arr)

3、Series  =》 DataFrame

1
pd.DataFrame(Series)
三、分組 GroupBy
1
2
df2 = pd.read_csv("G://..../pokemon.csv",encoding='gbk')
g1 = df2.groupby(['Type 1' , ... ])

重要屬性:

1.groups 返回dict {group name -> group labels} , 分組里每個組對應(yīng)的索引項(xiàng)列表

重要方法:

1.first()  返回組中每一列的第一個值(非NaN)

2.size()  返回分組中類型的個數(shù)

3.describe()  生成各種匯總統(tǒng)計(jì),不包括NaN值

4.get_group('xxx')   獲取該分組下所有項(xiàng)內(nèi)容

Aggregation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 方式一 :
g1.sum()
# 方式二 :
import numpy as np
g1.agg(np.sum)
# 方式三 :
g1.agg(np.sum)[' 列名 ']      # 單獨(dú)計(jì)算某一列
g1[' 列名 '].agg(np.sum)
# 多重計(jì)算 :
g1.agg([ np.sum,np.mean,np.std,... ])
# 每一列 都使用不同統(tǒng)計(jì)量 (字典)
g1.agg( {"HP":[np.sum,np.mean],"Attack":np.std} )
# 重新命名返回的列
xxxx.rename(columns = {"HP":'aaa',"Attack":"bb"})

Transformation :

  • Transform返回發(fā)數(shù)據(jù)集與原數(shù)據(jù)集大小一樣

  • 每一個函數(shù)都是對每一個group進(jìn)行的操作,不是全部的數(shù)據(jù)集

  • 不會改變原有g(shù)roup的數(shù)據(jù),返回的是新數(shù)據(jù)

  • 每個函數(shù)是作用在每個group里面的column上

1
2
f = lambda s : ( s - s.mean() ) / s.std
g1.transform( f )   # transform 計(jì)算非字符型變量

Filtration :

  • 作用于整個group上 或者 作用于某個列

  • 返回DataFrame

1
2
3
df = g1.filter(lambda s : len(s) >= 80 )             # 分組內(nèi)項(xiàng)總數(shù)大于80
df = g1.filter(lambda s : np.mean(s['HP']) >= 60 )   # 分組中HP平均值大于60

  

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多