教你十分鍾學會使用pandas。
pandas是python數據分析的一個最重要的工具。
基本使用
# 一般以pd作為pandas的縮寫
import pandas as pd
# 讀取文件
df = pd.read_csv('file.csv')
# 返回數據的大小
df.shape
# 顯示數據的一些對象信息和內存使用
df.info()
# 顯示數據的統計量信息
df.describe()
花式索引
我們的主要數據結構就是DataFrame了,DataFrame有兩部分構成,一個是列(columns)。列是有名稱的或者說有標簽的。另一個是索引(index),這里我們為了避孕歧義稱之為行(rows),行一般沒有名稱,但是也可以有名稱。
如圖所示:
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
>>> df
age animal priority visits
a 2.5 cat yes 1
b 3.0 cat yes 3
c 0.5 snake no 2
d NaN dog yes 3
e 5.0 dog no 2
f 2.0 cat no 3
g 4.5 snake no 1
h NaN cat yes 1
i 7.0 dog no 2
j 3.0 dog no 1
原始索引
原始索引就是類list的索引方式。
當索引對象是切片時就是行索引。
>>> df[1:3]
age animal priority visits
b 3.0 cat yes 3
c 0.5 snake no 2
當索引對象是list時就是列索引。
>>> df[['age', 'animal']]
age animal
a 2.5 cat
b 3.0 cat
c 0.5 snake
d NaN dog
e 5.0 dog
f 2.0 cat
g 4.5 snake
h NaN cat
i 7.0 dog
j 3.0 dog
跟上面等效,上面是用了列名稱,這里用了列序號。
>>> df[[0,1]]
age animal
a 2.5 cat
b 3.0 cat
c 0.5 snake
d NaN dog
e 5.0 dog
f 2.0 cat
g 4.5 snake
h NaN cat
i 7.0 dog
j 3.0 dog
位置索引
>>> df.iloc[0:2, 0:2]
age animal
a 2.5 cat
b 3.0 cat
標簽索引
loc
與iloc
的主要區別就是索引要用標簽不能用序號。
>>> df.loc[['a', 'b'], ['animal', 'age']]
animal age
a cat 2.5
b cat 3.0
混合索引
其實就是位置索引和標簽索引的混合使用方式。
>>> df.ix[0:2, ['animal', 'age']]
animal age
a cat 2.5
b cat 3.0
條件索引
>>> df[(df['animal'] == 'cat') & (df['age'] < 3)]
age animal priority visits
a 2.5 cat yes 1
f 2.0 cat no 3
數據清洗
找到缺失值。
>>> df[df['age'].isnull()]
age animal priority visits
d NaN dog yes 3
h NaN cat yes 1
填充缺失值。
>>> df['age'].fillna(0, inplace=True)
>>> df
age animal priority visits
a 2.5 cat yes 1
b 3.0 cat yes 3
c 0.5 snake no 2
d 0.0 dog yes 3
e 5.0 dog no 2
f 2.0 cat no 3
g 4.5 snake no 1
h 0.0 cat yes 1
i 7.0 dog no 2
j 3.0 dog no 1
將字符值替換成布爾值
>>> df['priority'] = df['priority'].map({'yes': True, 'no': False})
>>> df
age animal priority visits
a 2.5 cat True 1
b 3.0 cat True 3
c 0.5 snake False 2
d 0.0 dog True 3
e 5.0 dog False 2
f 2.0 cat False 3
g 4.5 snake False 1
h 0.0 cat True 1
i 7.0 dog False 2
j 3.0 dog False 1
速查表
練習
老樣子,來寫點習題吧。
100道pandas練習題
pandas練習庫