本教程的知識點為:機器學習(常用科學計算庫的使用)基礎(chǔ)定位 機器學習概述 機器學習概述 1.5 機器學習算法分類 1 監(jiān)督學習 機器學習概述 1.7 Azure機器學習模型搭建實驗 Azure平臺簡介 Matplotlib 3.2 基礎(chǔ)繪圖功能 — 以折線圖為例 1 完善原始折線圖 — 給圖形添加輔助功能 Matplotlib 3.3 常見圖形繪制 1 常見圖形種類及意義 Numpy 4.2 N維數(shù)組-ndarray 1 ndarray的屬性 Numpy 4.4 ndarray運算 問題 Pandas 5.1Pandas介紹 1 Pandas介紹 Pandas 5.3 基本數(shù)據(jù)操作 1 索引操作 Pandas 5.6 文件讀取與存儲 1 CSV Pandas 5.8 高級處理-數(shù)據(jù)離散化 1 為什么要離散化 Pandas 5.12 案例 1 需求
完整筆記資料代碼:https://gitee.com/yinuo112/AI/tree/master/機器學習/嘿馬機器學習(科學計算庫)/note.md
感興趣的小伙伴可以自取哦~
全套教程部分目錄:
部分文件圖片:
Pandas
學習目標
- 了解Numpy與Pandas的不同
- 說明Pandas的Series與Dataframe兩種結(jié)構(gòu)的區(qū)別
- 了解Pandas的MultiIndex與panel結(jié)構(gòu)
- 應(yīng)用Pandas實現(xiàn)基本數(shù)據(jù)操作
- 應(yīng)用Pandas實現(xiàn)數(shù)據(jù)的合并
- 應(yīng)用crosstab和pivot_table實現(xiàn)交叉表與透視表
- 應(yīng)用groupby和聚合函數(shù)實現(xiàn)數(shù)據(jù)的分組與聚合
- 了解Pandas的plot畫圖功能
- 應(yīng)用Pandas實現(xiàn)數(shù)據(jù)的讀取和存儲
5.6 文件讀取與存儲
學習目標
-
目標
- 了解Pandas的幾種文件讀取存儲操作
- 應(yīng)用CSV方式、HDF方式和json方式實現(xiàn)文件的讀取和存儲
我們的數(shù)據(jù)大部分存在于文件當中硕并,所以pandas會支持復雜的IO操作法焰,pandas的API支持眾多的文件格式,如CSV倔毙、SQL埃仪、XLS、JSON普监、HDF5贵试。
注:最常用的HDF5和CSV文件
1 CSV
1.1 read_csv
-
pandas.read_csv(filepath_or_buffer, sep =',', usecols )
- filepath_or_buffer:文件路徑
- sep :分隔符,默認用","隔開
- usecols:指定讀取的列名凯正,列表形式
舉例:讀取之前的股票的數(shù)據(jù)
# 讀取文件,并且指定只獲取'open', 'close'指標
data = pd.read_csv("./data/stock_day.csv", usecols=['open', 'close'])
open close
2018-02-27 23.53 24.16
2018-02-26 22.80 23.53
2018-02-23 22.88 22.82
2018-02-22 22.25 22.28
2018-02-14 21.49 21.92
1.2 to_csv
-
DataFrame.to_csv(path_or_buf=None, sep=', ’, columns=None, header=True, index=True, mode='w', encoding=None)
- path_or_buf :文件路徑
- sep :分隔符毙玻,默認用","隔開
- columns :選擇需要的列索引
- header :boolean or list of string, default True,是否寫進列索引值
- index:是否寫進行索引
- mode:'w':重寫, 'a' 追加
-
舉例:保存讀取出來的股票數(shù)據(jù)
- 保存'open'列的數(shù)據(jù),然后讀取查看結(jié)果
# 選取10行數(shù)據(jù)保存,便于觀察數(shù)據(jù)
data[:10].to_csv("./data/test.csv", columns=['open'])
# 讀取廊散,查看結(jié)果
pd.read_csv("./data/test.csv")
Unnamed: 0 open
0 2018-02-27 23.53
1 2018-02-26 22.80
2 2018-02-23 22.88
3 2018-02-22 22.25
4 2018-02-14 21.49
5 2018-02-13 21.40
6 2018-02-12 20.70
7 2018-02-09 21.20
8 2018-02-08 21.79
9 2018-02-07 22.69
會發(fā)現(xiàn)將索引存入到文件當中桑滩,變成單獨的一列數(shù)據(jù)。如果需要刪除允睹,可以指定index參數(shù),刪除原來的文件运准,重新保存一次。
# index:存儲不會講索引值變成一列數(shù)據(jù)
data[:10].to_csv("./data/test.csv", columns=['open'], index=False)
2 HDF5
2.1 read_hdf與to_hdf
HDF5文件的讀取和存儲需要指定一個鍵缭受,值為要存儲的DataFrame
- pandas.read_hdf(path_or_buf胁澳,key =None,** kwargs)
從h5文件當中讀取數(shù)據(jù)
path_or_buffer:文件路徑
key:讀取的鍵
return:Theselected object
DataFrame.to_hdf(path_or_buf, key, **kwargs)
2.2 案例
- 讀取文件
day_close = pd.read_hdf("./data/day_close.h5")
如果讀取的時候出現(xiàn)以下錯誤
需要安裝安裝tables模塊避免不能讀取HDF5文件
pip install tables
- 存儲文件
day_close.to_hdf("./data/test.h5", key="day_close")
再次讀取的時候, 需要指定鍵的名字
new_close = pd.read_hdf("./data/test.h5", key="day_close")
注意:優(yōu)先選擇使用HDF5文件存儲
- HDF5在存儲的時候支持壓縮米者,使用的方式是blosc吻商,這個是速度最快的也是pandas默認支持的
- 使用壓縮可以提磁盤利用率刑棵,節(jié)省空間
- HDF5還是跨平臺的,可以輕松遷移到hadoop 上面
3 JSON
JSON是我們常用的一種數(shù)據(jù)交換格式,前面在前后端的交互經(jīng)常用到乐横,也會在存儲的時候選擇這種格式跷究。所以我們需要知道Pandas如何進行讀取和存儲JSON格式肴掷。
3.1 read_json
-
pandas.read_json(path_or_buf=None, orient=None, typ='frame', lines=False)
將JSON格式準換成默認的Pandas DataFrame格式
-
orient : string,Indication of expected JSON string format.
-
'split' : dict like {index -> [index], columns -> [columns], data -> [values]}
- split 將索引總結(jié)到索引块蚌,列名到列名,數(shù)據(jù)到數(shù)據(jù)蒲祈。將三部分都分開了
-
'records' : list like [{column -> value}, ... , {column -> value}]
- records 以
columns:values
的形式輸出
- records 以
-
'index' : dict like {index -> {column -> value}}
- index 以
index:{columns:values}...
的形式輸出
- index 以
-
'columns' : dict like {column -> {index -> value}},默認該格式
- colums 以
columns:{index:values}
的形式輸出
- colums 以
-
'values' : just the values array
- values 直接輸出值
-
-
lines : boolean, default False
- 按照每行讀取json對象
typ : default ‘frame’甘萧, 指定轉(zhuǎn)換成的對象類型series或者dataframe
3.2 read_josn 案例
- 數(shù)據(jù)介紹
這里使用一個新聞標題諷刺數(shù)據(jù)集萝嘁,格式為json。is_sarcastic
:1諷刺的扬卷,否則為0酿愧;headline
:新聞報道的標題;article_link
:鏈接到原始新聞文章邀泉。存儲格式為:
{"article_link": " "headline": "former versace store clerk sues over secret 'black code' for minority shoppers", "is_sarcastic": 0}
{"article_link": " "headline": "the 'roseanne' revival catches up to our thorny political mood, for better and worse", "is_sarcastic": 0}
- 讀取
orient指定存儲的json格式嬉挡,lines指定按照行去變成一個樣本
json_read = pd.read_json("./data/Sarcasm_Headlines_Dataset.json", orient="records", lines=True)
結(jié)果為:
3.3 to_json
-
DataFrame.to_json(path_or_buf=None, orient=None, lines=False)
- 將Pandas 對象存儲為json格式
- path_or_buf=None:文件地址
- orient:存儲的json形式,{‘split’,’records’,’index’,’columns’,’values’}
- lines:一個對象存儲為一行
3.4 案例
- 存儲文件
json_read.to_json("./data/test.json", orient='records')
結(jié)果
[{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/versace-black-code_us_5861fbefe4b0de3a08f600d5","headline":"former versace store clerk sues over secret 'black code' for minority shoppers","is_sarcastic":0},{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/roseanne-revival-review_us_5ab3a497e4b054d118e04365","headline":"the 'roseanne' revival catches up to our thorny political mood, for better and worse","is_sarcastic":0},{"article_link":"https:\/\/local.theonion.com\/mom-starting-to-fear-son-s-web-series-closest-thing-she-1819576697","headline":"mom starting to fear son's web series closest thing she will have to grandchild","is_sarcastic":1},{"article_link":"https:\/\/politics.theonion.com\/boehner-just-wants-wife-to-listen-not-come-up-with-alt-1819574302","headline":"boehner just wants wife to listen, not come up with alternative debt-reduction ideas","is_sarcastic":1},{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/jk-rowling-wishes-snape-happy-birthday_us_569117c4e4b0cad15e64fdcb","headline":"j.k. rowling wishes snape happy birthday in the most magical way","is_sarcastic":0},{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/advancing-the-worlds-women_b_6810038.html","headline":"advancing the world's women","is_sarcastic":0},....]
- 修改lines參數(shù)為True
json_read.to_json("./data/test.json", orient='records', lines=True)
結(jié)果
{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/versace-black-code_us_5861fbefe4b0de3a08f600d5","headline":"former versace store clerk sues over secret 'black code' for minority shoppers","is_sarcastic":0}
{"article_link":"https:\/\/www.huffingtonpost.com\/entry\/roseanne-revival-review_us_5ab3a497e4b054d118e04365","headline":"the 'roseanne' revival catches up to our thorny political mood, for better and worse","is_sarcastic":0}
{"article_link":"https:\/\/local.theonion.com\/mom-starting-to-fear-son-s-web-series-closest-thing-she-1819576697","headline":"mom starting to fear son's web series closest t