Python Data Analysis Library(Pandas)是基于NumPy 的一種工具,該工具是為了解決數(shù)據(jù)分析任務而創(chuàng)建的莹桅。Pandas 納入了大量庫和一些標準的數(shù)據(jù)模型倦春,提供了高效地操作大型數(shù)據(jù)集所需的工具涩拙。通過Pandas讀取和保存數(shù)據(jù)蚊丐,可以大大方便數(shù)據(jù)的統(tǒng)計與查看飘蚯。
一些有用的鏈接:
項目地址:http://pandas.pydata.org/
官方文檔:http://pandas.pydata.org/pandas-docs/stable/
快速入門:10 Minutes to pandas
翻譯版快速入門:十分鐘搞定pandas
Panda速查手冊:Pandas速查手冊中文版
安裝
直接通過pip安裝:(通過-i參數(shù)使用豆瓣的鏡像馍迄,下載較快)
pip install pandas -i https://pypi.douban.com/simple/
在數(shù)據(jù)分析和科學計算領(lǐng)域,有很多包是非常實用的局骤,然而用原生Python安裝這些包坑比較多攀圈,特別是在Windows環(huán)境下。大家可以嘗試Python的一個發(fā)行包——Anaconda或者Miniconda峦甩,已經(jīng)集成了numpy赘来、scipy等等常用的庫现喳。然后就可以使用它們自身的包管理工具conda進行安裝:
conda install pandas
安裝完成后,在Python中引入一下犬辰,驗證是否安裝成功嗦篱,一種常用的引入寫法是:
import pandas as pd
對象創(chuàng)建
在pandas中,我們常用的有兩種對象:Series和Dataframe幌缝【拇伲可以簡單理解為:Series是一維的數(shù)組,而Dataframe是二維的表格涵卵。
Series
Series的創(chuàng)建支持多種方式浴栽,常用的方式為通過python的list構(gòu)建,這種方式下如果不指定index轿偎,會自動對每個元素生成int類型的index典鸡。
In [4]: s = pd.Series([1,3,5,np.nan,6,8])
In [5]: s
Out[5]:
0 1.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64
另外一種方式是通過Python的字典進行構(gòu)建,key值會自動作為index坏晦。
In [6]: sd = {"python":8000, "c++":8100, "c#":4000}
In [7]: s = pd.Series(sd)
In [8]: s
Out[8]:
c# 4000
c++ 8100
python 8000
Dataframe
Dataframe的創(chuàng)建萝玷,一般有以下幾種方式:
- 通過Python的字典創(chuàng)建,字典的key值為column的標簽英遭,value值為對應column的序列:
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df
col1 col2
0 1 3
1 2 4
- 通過字典的字典構(gòu)建,各內(nèi)層字典會成為一列亦渗,每個字典的鍵會被合并成結(jié)果的index:
In [227]: nest_dict={'shanghai':{2015:100,2016:101},'beijing':{2015:102,2016:103}}
In [228]: nest_dict
Out[228]: {'beijing': {2015: 102, 2016: 103}, 'shanghai': {2015: 100, 2016: 101}}
In [229]: df1=DataFrame(nest_dict)
In [230]: df1
Out[230]:
beijing shanghai
2015 102 100
2016 103 101
- 通過Series組成的字典創(chuàng)建挖诸,每個Series會成為Dataframe的一列,不指定索引的話法精,每個series的索引會合并(也就是自動對齊)多律。
In [2]: Shanghai_data = pd.Series({"2015":102,"2016":103})
In [3]: Beijing_data = pd.Series({"2015":105,"2016":106})
In [4]: nest_dict = {"Beijing":Beijing_data, "Shanghai":Shanghai_data}
In [5]: df = pd.DataFrame(nest_dict)
In [6]: df
Out[6]:
Beijing Shanghai
2015 105 102
2016 106 103
- 字典或者Series的list,各個項會成為Dataframe的一行搂蜓。字典鍵或Series的索引的并集成為Dataframe的列標狼荞。
In [9]: nest_list = [Beijing_data, Shanghai_data]
In [10]: df = pd.DataFrame(nest_list)
In [11]: df = pd.DataFrame(nest_list, index=["Beijing", "Shanghai"])
In [12]: df
Out[12]:
2015 2016
Beijing 105 106
Shanghai 102 103
數(shù)據(jù)查看
pandas提供了非常方便地查看數(shù)據(jù)的方式,常用的方式有:
- 查看頭尾的數(shù)據(jù)
In [33]: finance.head(5)
Out[33]:
Open High Low Close Adj Close \
Date
2017-10-10 181.649994 184.460007 181.360001 183.119995 183.119995
2017-10-11 183.000000 184.699997 182.600998 184.690002 184.690002
2017-10-12 184.039993 184.389999 180.348007 180.529999 180.529999
2017-10-13 180.960007 181.399994 177.970001 178.449997 178.449997
2017-10-16 180.000000 180.050003 178.509995 179.559998 179.559998
In [34]: finance.tail(5)
Out[34]:
Open High Low Close Adj Close \
Date
2017-10-31 183.570007 185.119995 181.811005 184.889999 184.889999
2017-11-01 187.880005 188.880005 183.580002 186.080002 186.080002
2017-11-02 190.990005 191.220001 183.309998 184.809998 184.809998
2017-11-03 186.509995 186.929993 182.059998 183.210007 183.210007
2017-11-06 184.070007 188.250000 184.000000 187.839996 187.839996
- 查看索引帮碰、列
In [35]: finance.index
Out[35]:
DatetimeIndex(['2017-10-10', '2017-10-11', '2017-10-12', '2017-10-13',
'2017-10-16', '2017-10-17', '2017-10-18', '2017-10-19',
'2017-10-20', '2017-10-23', '2017-10-24', '2017-10-25',
'2017-10-26', '2017-10-27', '2017-10-30', '2017-10-31',
'2017-11-01', '2017-11-02', '2017-11-03', '2017-11-06'],
dtype='datetime64[ns]', name=u'Date', freq=None)
In [36]: finance.columns
Out[36]: Index([u'Open', u'High', u'Low', u'Close', u'Adj Close', u'Volume'], dtype='object')
- describe快速統(tǒng)計
In [38]: finance.describe()
Out[38]:
Open High Low Close Adj Close \
count 20.000000 20.000000 20.000000 20.000000 20.000000
mean 180.204551 181.721499 177.627500 179.423000 179.423000
std 5.166460 5.015834 4.803680 5.185056 5.185056
min 170.619995 171.449997 168.580002 170.220001 170.220001
25% 177.067749 179.142502 174.790001 175.942497 175.942497
50% 179.790001 180.759995 177.779998 179.585000 179.585000
75% 183.687503 184.804997 181.873253 183.580006 183.580006
max 190.990005 191.220001 184.000000 187.839996 187.839996
- 按值進行排序
In [41]: finance.sort_values(by=["Open"])
Out[41]:
Open High Low Close Adj Close \
Date
2017-10-26 170.619995 171.449997 168.580002 170.320007 170.320007
2017-10-27 173.190002 177.000000 171.110001 176.149994 176.149994
2017-10-24 174.000000 175.979996 173.259995 173.699997 173.699997
2017-10-25 174.690002 175.440002 169.300003 170.220001 170.220001
2017-10-19 177.001007 179.610001 175.449997 177.929993 177.929993
2017-10-18 177.089996 180.000000 176.279999 179.610001 179.610001
2017-10-23 177.800003 178.009995 173.050003 173.130005 173.130005
2017-10-30 178.429993 181.899994 177.589996 181.580002 181.580002
2017-10-20 179.020004 179.520004 177.080002 177.320007 177.320007
2017-10-17 179.580002 180.119995 175.300003 175.320007 175.320007
2017-10-16 180.000000 180.050003 178.509995 179.559998 179.559998
2017-10-13 180.960007 181.399994 177.970001 178.449997 178.449997
2017-10-10 181.649994 184.460007 181.360001 183.119995 183.119995
2017-10-11 183.000000 184.699997 182.600998 184.690002 184.690002
2017-10-31 183.570007 185.119995 181.811005 184.889999 184.889999
2017-10-12 184.039993 184.389999 180.348007 180.529999 180.529999
2017-11-06 184.070007 188.250000 184.000000 187.839996 187.839996
2017-11-03 186.509995 186.929993 182.059998 183.210007 183.210007
2017-11-01 187.880005 188.880005 183.580002 186.080002 186.080002
2017-11-02 190.990005 191.220001 183.309998 184.809998 184.809998
數(shù)據(jù)選擇
1.選擇特定列和行的數(shù)據(jù)
a['x'] 那么將會返回columns為x的列相味,注意這種方式一次只能返回一個列。a.x與a['x']意思一樣殉挽。取行數(shù)據(jù)丰涉,通過切片[]來選擇
如:a[0:3] 則會返回前三行的數(shù)據(jù)。2.loc是通過標簽來選擇數(shù)據(jù)
a.loc['one']則會默認表示選取行為'one'的行斯碌;a.loc[:,['a','b'] ] 表示選取所有的行以及columns為a,b的列一死;
a.loc[['one','two'],['a','b']] 表示選取'one'和'two'這兩行以及columns為a,b的列;
a.loc['one','a']與a.loc[['one'],['a']]作用是一樣的傻唾,不過前者只顯示對應的值投慈,而后者會顯示對應的行和列標簽。
3.iloc則是直接通過位置來選擇數(shù)據(jù)
這與通過標簽選擇類似
a.iloc[1:2,1:2] 則會顯示第一行第一列的數(shù)據(jù);(切片后面的值取不到)a.iloc[1:2] 即后面表示列的值沒有時,默認選取行位置為1的數(shù)據(jù);
a.iloc[[0,2],[1,2]] 即可以自由選取行位置伪煤,和列位置對應的數(shù)據(jù)加袋。
4.使用條件來選擇
使用單獨的列來選擇數(shù)據(jù)
a[a.c>0] 表示選擇c列中大于0的數(shù)據(jù)使用where來選擇數(shù)據(jù)
a[a>0] 表直接選擇a中所有大于0的數(shù)據(jù)使用isin()選出特定列中包含特定值的行
a1=a.copy()
a1[a1['one'].isin(['2','3'])] 表顯示滿足條件:列one中的值包含'2','3'的所有行。作者:是藍先生
鏈接:http://www.reibang.com/p/682c24aef525
來源:簡書
著作權(quán)歸作者所有带族。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán)锁荔,非商業(yè)轉(zhuǎn)載請注明出處。
缺失值處理
初始化過后蝙砌,缺失的值會暫時以np.nan代替(Numpy中的空值)阳堕,可能會妨礙進一步的運算,一般通過fillna()進行處理择克。
df.fillna(value=0)
導入導出文件
推薦導入導出均使用csv文件恬总,參考:IO Tools
寫入csv文件:
df.to_csv("foo.csv")
從csv文件讀取:
pd.read_csv("foo.csv")
作業(yè)
- 閱讀“十分鐘搞定pandas”肚邢,了解pandas的一些基礎(chǔ)用法
- 讀取阿里巴巴股票數(shù)據(jù)壹堰,并對該Dataframe進行基本操作的練習(查看數(shù)據(jù)、選擇數(shù)據(jù))PS. 需要多安裝一個庫:pandas-datareader
讀取示例代碼:
In [1]: import pandas
In [2]: from pandas_datareader import data
In [3]: sym = "BABA"
In [4]: finance = data.DataReader(sym, "yahoo", start="2017/10/11")
- 從Python S1培訓的大作業(yè)數(shù)據(jù)中骡湖,選出詞頻前100的單詞贱纠,整理成(單詞、詞頻數(shù)量响蕴、排名前百分之幾)的形式谆焊,保存為csv格式文件。