pandas 是基于NumPy 的一種工具,pandas就是字典型的numpy,就是numpy像是一個列表,pandas就更像是一個字典。 利用pandas可以高效的操作大型數(shù)據集,因為其中包含了大量快速便捷的處理數(shù)據的函數(shù)和方法。
讀入數(shù)據
下面是常見的支持的可讀入數(shù)據

常用的方法為前兩個,所以以下例子就舉前兩個。
#注意read_table需要指定分隔符,用參數(shù) sep 指定
#read_table可讀取txt文件
iris_text = pd.read_table('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',
sep = ',')
#這里我是使用網頁鏈接讀取的uci數(shù)據集上的鳶尾花數(shù)據集,有興趣可以上uci數(shù)據集官網去看看
iris_csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data')
print(iris_text.head())
print('--------------------------------------')
print(iris_csv.head())
5.1 3.5 1.4 0.2 Iris-setosa
0 4.9 3.0 1.4 0.2 Iris-setosa
1 4.7 3.2 1.3 0.2 Iris-setosa
2 4.6 3.1 1.5 0.2 Iris-setosa
3 5.0 3.6 1.4 0.2 Iris-setosa
4 5.4 3.9 1.7 0.4 Iris-setosa
--------------------------------------
5.1 3.5 1.4 0.2 Iris-setosa
0 4.9 3.0 1.4 0.2 Iris-setosa
1 4.7 3.2 1.3 0.2 Iris-setosa
2 4.6 3.1 1.5 0.2 Iris-setosa
3 5.0 3.6 1.4 0.2 Iris-setosa
數(shù)據結構
Pandas有兩個主要的數(shù)據結構:Series和DataFrame。 Series類似Numpy中的一維數(shù)組,DataFrame則是使用較多的多維表格數(shù)據結構,這里主要介紹的是dataframe。
Series
一維數(shù)組,與Numpy中的一維array類似。二者與Python基本的數(shù)據結構List也很相近,其區(qū)別是:List中的元素可以是不同的數(shù)據類型,而Array和Series中則只允許存儲相同的數(shù)據類型,這樣可以更有效的使用內存,提高運算效率。 Pandas的數(shù)據類型實際上就是一個數(shù)據對應一個索引(行標),還可以有列標。對于一維的series是沒有columns的定義的。
#生成一個series
test_series1 = pd.Series([1,2,3])
#指定索引
test_series2 = pd.Series([1,2,3],index = ['a','b','c'])
#這里用enumerate函數(shù)做比較
test3 = list(enumerate([1,2,3])) #enumerate函數(shù)返回一個索引序列,同時列出數(shù)據和數(shù)據下標
print(test_series1)
print('-----------------------------')
print(test_series2 )
print('-----------------------------')
print(test3)
0 1
1 2
2 3
dtype: int64
-----------------------------
a 1
b 2
c 3
dtype: int64
-----------------------------
[(0, 1), (1, 2), (2, 3)]
DataFrame
二維的表格型數(shù)據結構,可以將DataFrame理解為Series的容器。 DataFrame可以跟Numpy一樣根據索引取出其中的數(shù)據,只是DataFrame索引方式更加多樣化。DataFrame不僅可以根據默認的行列編號來索引,還可以根據標簽序列來索引。行標簽index,列標簽columns。
上面鳶尾花數(shù)據集讀進來其實就是一個DataFrame。
#創(chuàng)建一個時間索引,periods指定長度
dates = pd.date_range('20180516',periods=6)
#以時間索引創(chuàng)建一個二維dataframe
df = pd.DataFrame(np.random.randint(6,size=(6,4)),index=dates,
columns=['a','b','c','d'])
print(df)
a b c d
2018-05-16 2 3 2 2
2018-05-17 2 0 0 2
2018-05-18 1 1 1 0
2018-05-19 1 5 5 4
2018-05-20 1 4 2 0
2018-05-21 5 4 3 1
還可以用字典的方式來創(chuàng)建dataframe,因為dataframe就像是一個字典。
df = pd.DataFrame({'a':1,'b':'hello python','c':np.arange(2),
'd':['o','k'],'e':['你','好']})
print(df)
a b c d e
0 1 hello python 0 o 你
1 1 hello python 1 k 好
Dataframe的屬性多樣,以下為幾種常用的:
- dtype:查看數(shù)據類型 。
- index:查看行序列或者索引 。
- columns:查看各列的標簽 。
- values:查看數(shù)據框內的數(shù)據,也即不含表頭索引的數(shù)據 。
- info:返回當前的信息,有無nan值和內存占用,數(shù)據類型等。
- describe() :查看數(shù)據的一些信息,如每一列的極值,均值,中位數(shù)之類 的,只能對數(shù)值型數(shù)據統(tǒng)計信息 。
- transpose() :轉置,也可用T來操作 。
- sort_index() :排序,可按行或列index排序輸出 。
- sort_values() : 按數(shù)據值來排序。
- cov():得到協(xié)方差矩陣。
- corr(): 得到相關性矩陣。
- value_counts(): 可統(tǒng)計不同值個數(shù)。
以下還是用鳶尾花數(shù)據集解釋
查看當前信息
# 查看當前信息
print(iris_csv.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 149 entries, 0 to 148
Data columns (total 5 columns):
5.1 149 non-null float64
3.5 149 non-null float64
1.4 149 non-null float64
0.2 149 non-null float64
Iris-setosa 149 non-null object
dtypes: float64(4), object(1)
memory usage: 5.9+ KB
None
查看統(tǒng)計信息
# 查看統(tǒng)計信息
print(iris_csv.describe())
#當然也可以直接用min(),mean()這些去得到返回值,用法和numpy相同
5.1 3.5 1.4 0.2
count 149.000000 149.000000 149.000000 149.000000
mean 5.848322 3.051007 3.774497 1.205369
std 0.828594 0.433499 1.759651 0.761292
min 4.300000 2.000000 1.000000 0.100000
25% 5.100000 2.800000 1.600000 0.300000
50% 5.800000 3.000000 4.400000 1.300000
75% 6.400000 3.300000 5.100000 1.800000
max 7.900000 4.400000 6.900000 2.500000
排序
#排序,分為按值排序和按索引排序
#按索引排序,默認是從小到大,可以指定ascending=false從大到小排序
"""按行標簽從大到小排序"""
print(iris_csv.sort_index(axis=0,ascending=False)[:5])
print('----------------------------------------')
#按值排序,默認是從小到大,可以指定ascending=false從小到大排序
'''按1.4列值從大到小排序'''
print(iris_csv.sort_values(by="1.4")[:5])
5.1 3.5 1.4 0.2 Iris-setosa
148 5.9 3.0 5.1 1.8 Iris-virginica
147 6.2 3.4 5.4 2.3 Iris-virginica
146 6.5 3.0 5.2 2.0 Iris-virginica
145 6.3 2.5 5.0 1.9 Iris-virginica
144 6.7 3.0 5.2 2.3 Iris-virginica
----------------------------------------
5.1 3.5 1.4 0.2 Iris-setosa
21 4.6 3.6 1.0 0.2 Iris-setosa
12 4.3 3.0 1.1 0.1 Iris-setosa
34 5.0 3.2 1.2 0.2 Iris-setosa
13 5.8 4.0 1.2 0.2 Iris-setosa
37 4.4 3.0 1.3 0.2 Iris-setosa
協(xié)方差矩陣
print(iris_csv.cov()) #協(xié)方差矩陣和相關性矩陣在分析中可是很重要的
5.1 3.5 1.4 0.2
5.1 0.686568 -0.037279 1.270362 0.515347
3.5 -0.037279 0.187921 -0.316731 -0.115749
1.4 1.270362 -0.316731 3.096372 1.289124
0.2 0.515347 -0.115749 1.289124 0.579566
相關系數(shù)矩陣
這個相關系數(shù)矩陣可是很重要的,相關矩陣第i行第j列的元素就是原矩陣第i列和第j列的相關系數(shù),值的絕對值越大相關性越高,為0則不相關。
print(iris_csv.corr()) #值的絕對值越大相關性越高,為0則不相關
5.1 3.5 1.4 0.2
5.1 1.000000 -0.103784 0.871283 0.816971
3.5 -0.103784 1.000000 -0.415218 -0.350733
1.4 0.871283 -0.415218 1.000000 0.962314
0.2 0.816971 -0.350733 0.962314 1.000000
value_counts()
iris_csv['Iris-setosa'].value_counts()
"""value_counts()可以清楚看出某一列的分布情況,可以指定ascending = True變?yōu)榈剐颍?還可添加bins將數(shù)據自動分為幾類"""
Iris-versicolor 50
Iris-virginica 50
Iris-setosa 49
Name: Iris-setosa, dtype: int64
統(tǒng)計值從小到大排序
iris_csv['3.5'].value_counts(ascending = True)
4.0 1
2.0 1
4.4 1
4.1 1
4.2 1
3.9 2
3.7 3
2.2 3
2.4 3
3.6 3
2.3 4
2.6 5
3.5 5
3.3 6
3.8 6
2.5 8
2.7 9
2.9 10
3.1 12
3.4 12
3.2 13
2.8 14
3.0 26
Name: 3.5, dtype: int64
設置bins
#如下,指定bins為5,自動歸為了五類,當一列有很多值的情況下,我們可以考慮用這個方法將其分為幾類
iris_csv['3.5'].value_counts(ascending = True,bins = 5)
(3.92, 4.4] 4
(1.997, 2.48] 11
(3.44, 3.92] 19
(2.48, 2.96] 46
(2.96, 3.44] 69
Name: 3.5, dtype: int64
數(shù)據選取
先使用一些切片的方法
# 可以直接取指定的一列,取出來就是一個series
Iris_setosa = iris_csv['Iris-setosa']
print(Iris_setosa[:5])
print('--------------------------------')
#當然,也可指定多列
df_iris1 = iris_csv[['1.4','Iris-setosa']]
print(df_iris1[:5])
print('--------------------------------')
#還可以直接切片,不過這里我只會橫著切
df_iris2 = iris_csv[:2]
print(df_iris2)
0 Iris-setosa
1 Iris-setosa
2 Iris-setosa
3 Iris-setosa
4 Iris-setosa
Name: Iris-setosa, dtype: object
--------------------------------
1.4 Iris-setosa
0 1.4 Iris-setosa
1 1.3 Iris-setosa
2 1.5 Iris-setosa
3 1.4 Iris-setosa
4 1.7 Iris-setosa
--------------------------------
5.1 3.5 1.4 0.2 Iris-setosa
0 4.9 3.0 1.4 0.2 Iris-setosa
1 4.7 3.2 1.3 0.2 Iris-setosa
高級索引方式
- loc():根據標簽選取列,DataFrame行的表示方式有兩種,一種是通過顯式的行標簽來索引,另一種是通過默認隱式的行號來索引。loc方法是通過行標簽來索引選取目標行,可以配合列標簽來選取特定位置的數(shù)據。
- iloc():根據序列選取行,使用隱式(即為從0到無窮的數(shù)據索引)的行序列號來選取數(shù)據使用iloc,可以搭配列序列號來更簡單的選取特定位點的數(shù)據
- ix():組合使用索引和標簽來選取特定位置,loc只能使用顯式標簽來選取數(shù)據,而iloc只能使用隱式序列號來選取數(shù)據,ix則能將二者結合起來使用,ix可以混用顯式標簽與隱式序列號。
注意:ix方法已經要被淘汰了,所以就不使用它了
上面說的這么復雜,其實就是兩句話
- loc 用label來去定位
- iloc 用position來去定位
#以下我們換一個泰坦尼克的數(shù)據集
df = pd.read_csv('titanic.csv')
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
PassengerId 891 non-null int64
Survived 891 non-null int64
Pclass 891 non-null int64
Name 891 non-null object
Sex 891 non-null object
Age 714 non-null float64
SibSp 891 non-null int64
Parch 891 non-null int64
Ticket 891 non-null object
Fare 891 non-null float64
Cabin 204 non-null object
Embarked 889 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 83.6+ KB
None
iloc方法
索引方式和numpy差不多
print(df.iloc[0])
PassengerId 1
Survived 0
Pclass 3
Name Braund, Mr. Owen Harris
Sex male
Age 22
SibSp 1
Parch 0
Ticket A/5 21171
Fare 7.25
Cabin NaN
Embarked S
Name: 0, dtype: object
切片
print(df.iloc[0:2])
PassengerId Survived \
Name
Braund, Mr. Owen Harris 1 0
Cumings, Mrs. John Bradley (Florence Briggs Tha... 2 1
Pclass Sex Age \
Name
Braund, Mr. Owen Harris 3 male 22.0
Cumings, Mrs. John Bradley (Florence Briggs Tha... 1 female 38.0
SibSp Parch Ticket \
Name
Braund, Mr. Owen Harris 1 0 A/5 21171
Cumings, Mrs. John Bradley (Florence Briggs Tha... 1 0 PC 17599
Fare Cabin Embarked
Name
Braund, Mr. Owen Harris 7.2500 NaN S
Cumings, Mrs. John Bradley (Florence Briggs Tha... 71.2833 C85 C
兩邊切
print(df.iloc[0:4,0:4])
PassengerId Survived \
Name
Braund, Mr. Owen Harris 1 0
Cumings, Mrs. John Bradley (Florence Briggs Tha... 2 1
Heikkinen, Miss. Laina 3 1
Futrelle, Mrs. Jacques Heath (Lily May Peel) 4 1
Pclass Sex
Name
Braund, Mr. Owen Harris 3 male
Cumings, Mrs. John Bradley (Florence Briggs Tha... 1 female
Heikkinen, Miss. Laina 3 female
Futrelle, Mrs. Jacques Heath (Lily May Peel) 1 female
loc方法
用于標簽索引
df = df.set_index('Name') #將name設為索引用于loc遍歷
df.loc['Braund, Mr. Owen Harris']
PassengerId 1
Survived 0
Pclass 3
Sex male
Age 22
SibSp 1
Parch 0
Ticket A/5 21171
Fare 7.25
Cabin NaN
Embarked S
Name: Braund, Mr. Owen Harris, dtype: object
指定行和列索引
df.loc['Braund, Mr. Owen Harris','Sex'] #指定行和列索引
'male'
切片
df.loc['Braund, Mr. Owen Harris':'Heikkinen, Miss. Laina',:] #一樣可以切片

bool類型索引
其實和前面numpy的操作是一樣的,這里就舉個例子
首先,得到一個bool列表
print(df['Sex'] == 'female') #得到bool列表
Name
Braund, Mr. Owen Harris False
Cumings, Mrs. John Bradley (Florence Briggs Thayer) True
Heikkinen, Miss. Laina True
Futrelle, Mrs. Jacques Heath (Lily May Peel) True
Allen, Mr. William Henry False
Moran, Mr. James False
McCarthy, Mr. Timothy J False
Palsson, Master. Gosta Leonard False
Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) True
Nasser, Mrs. Nicholas (Adele Achem) True
Sandstrom, Miss. Marguerite Rut True
Bonnell, Miss. Elizabeth True
Saundercock, Mr. William Henry False
Andersson, Mr. Anders Johan False
Vestrom, Miss. Hulda Amanda Adolfina True
Hewlett, Mrs. (Mary D Kingcome) True
Rice, Master. Eugene False
Williams, Mr. Charles Eugene False
Vander Planke, Mrs. Julius (Emelia Maria Vandemoortele) True
Masselmani, Mrs. Fatima True
Fynney, Mr. Joseph J False
Beesley, Mr. Lawrence False
McGowan, Miss. Anna "Annie" True
Sloper, Mr. William Thompson False
Palsson, Miss. Torborg Danira True
Asplund, Mrs. Carl Oscar (Selma Augusta Emilia Johansson) True
Emir, Mr. Farred Chehab False
Fortune, Mr. Charles Alexander False
O'Dwyer, Miss. Ellen "Nellie" True
Todoroff, Mr. Lalio False
...
Giles, Mr. Frederick Edward False
Swift, Mrs. Frederick Joel (Margaret Welles Barron) True
Sage, Miss. Dorothy Edith "Dolly" True
Gill, Mr. John William False
Bystrom, Mrs. (Karolina) True
Duran y More, Miss. Asuncion True
Roebling, Mr. Washington Augustus II False
van Melkebeke, Mr. Philemon False
Johnson, Master. Harold Theodor False
Balkic, Mr. Cerin False
Beckwith, Mrs. Richard Leonard (Sallie Monypeny) True
Carlsson, Mr. Frans Olof False
Vander Cruyssen, Mr. Victor False
Abelson, Mrs. Samuel (Hannah Wizosky) True
Najib, Miss. Adele Kiamie "Jane" True
Gustafsson, Mr. Alfred Ossian False
Petroff, Mr. Nedelio False
Laleff, Mr. Kristo False
Potter, Mrs. Thomas Jr (Lily Alexenia Wilson) True
Shelley, Mrs. William (Imanita Parrish Hall) True
Markun, Mr. Johann False
Dahlberg, Miss. Gerda Ulrika True
Banfield, Mr. Frederick James False
Sutehall, Mr. Henry Jr False
Rice, Mrs. William (Margaret Norton) True
Montvila, Rev. Juozas False
Graham, Miss. Margaret Edith True
Johnston, Miss. Catherine Helen "Carrie" True
Behr, Mr. Karl Howell False
Dooley, Mr. Patrick False
Name: Sex, Length: 891, dtype: bool
然后去找到值
df[df['Sex'] == 'female'][:5]

得到特定列的結果
df.loc[df['Sex'] == 'male','Age'][:5] #得到性別為女性的年齡
Name
Braund, Mr. Owen Harris 22.0
Allen, Mr. William Henry 35.0
Moran, Mr. James NaN
McCarthy, Mr. Timothy J 54.0
Palsson, Master. Gosta Leonard 2.0
Name: Age, dtype: float64
此外,還有where操作
where(cond,other = nan) 我這里只介紹前兩個參數(shù),有興趣的可以去pandas官方文檔上去查,cond就是傳入的矩陣,other指定不滿足條件的值等于什么。
不使用other參數(shù)
df.where(df>2)[:5]

使用other參數(shù)
df.where(df>2,0)[:5]

還有query操作
使用布爾表達式查詢DataFrame的列。
df1 = pd.DataFrame(np.random.randn(5, 2), columns=list('ab'))
print(df1.query('a > b')) #其實就等于 df1[df1.a > df1.b]
a b
1 1.164991 -1.354645
3 0.993299 0.188703
合并操作
這里就將concat和merge操作,這兩個操作在做特征工程時時常會用到
- concat([df1,df2,…],axis=[ ]) 將矩陣按行或列合并,指定axis。
- merge(df1,df2,on = '',how = '') 將矩陣按某個鍵和怎樣的方式融合,on指定融合的鍵,可以是一個元組;how指定融合方式,有l(wèi)eft(左),right(右),outer(全連接),默認為左連接。
left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
print(left)
print(right)
A B key
0 A0 B0 K0
1 A1 B1 K1
2 A2 B2 K2
3 A3 B3 K3
C D key
0 C0 D0 K0
1 C1 D1 K1
2 C2 D2 K2
3 C3 D3 K3
concat操作
res = pd.concat([left,right],axis = 1)
print(res)
A B key C D key
0 A0 B0 K0 C0 D0 K0
1 A1 B1 K1 C1 D1 K1
2 A2 B2 K2 C2 D2 K2
3 A3 B3 K3 C3 D3 K3
merge操作
res = pd.merge(left, right, on = 'key')
print(res)
A B key C D
0 A0 B0 K0 C0 D0
1 A1 B1 K1 C1 D1
2 A2 B2 K2 C2 D2
3 A3 B3 K3 C3 D3
另外還有一種join方法,可以按鍵添加矩陣進去,不過要設置其的索引與要加入的矩陣的鍵有關系.
right.set_index('key',inplace = True)
res = left.join(right, on = 'key')
print(res)
A B key C D
0 A0 B0 K0 C0 D0
1 A1 B1 K1 C1 D1
2 A2 B2 K2 C2 D2
3 A3 B3 K3 C3 D3
這些就是我覺得比較基礎和常用的pandas方法,不理解的地方一定要查api文檔然后自己練習一下。
下一篇介紹一些高級的用法。