一個強大的分析結構化數據的工具集
基礎是NumPy,提供了高性能矩陣的運算
pandas 數據結構
Series
類似一維數組的對象
通過list構建Series
ser_obj = pd.Series(range(10))
# 通過list構建Series
ser_obj = pd.Series(range(10, 20))
print(type(ser_obj))
獲取數據和索引
ser_obj.index, ser_obj.values
# 獲取數據
print(ser_obj.values)
# 獲取索引
print(ser_obj.index)
預覽數據
ser_obj.head(n)
通過索引獲取數據
ser_obj[idx]
索引與數據的對應關系仍保持在數組運算的結果中
#通過索引獲取數據
print(ser_obj[0])
print(ser_obj[8])
# 索引與數據的對應關系仍保持在數組運算的結果中
print(ser_obj * 2)
print(ser_obj > 15)
"""
0 20
1 22
2 24
3 26
4 28
5 30
6 32
7 34
8 36
9 38
dtype: int64
0 False
1 False
2 False
3 False
4 False
5 False
6 True
7 True
8 True
9 True
dtype: bool
"""
通過dict構建Series
# 通過dict構建Series
year_data = {2001: 17.8, 2002: 20.1, 2003: 16.5}
ser_obj2 = pd.Series(year_data)
print(ser_obj2.head())
print(ser_obj2.index)
"""
2001 17.8
2002 20.1
2003 16.5
dtype: float64
Int64Index([2001, 2002, 2003], dtype='int64')
"""
name屬性
ser_obj.name, ser_obj.index.name
# name屬性
ser_obj2.name = 'temp'
ser_obj2.index.name = 'year'
print(ser_obj2.head())
"""
year
2001 17.8
2002 20.1
2003 16.5
Name: temp, dtype: float64
"""
DataFrame
類似多維數組/表格數據 (如,excel, R中的data.frame)
每列數據可以是不同的類型
索引包括列索引和行索引
通過ndarray構建DataFrame
import numpy as np
# 通過ndarray構建DataFrame
array = np.random.randn(5,4)
print(array)
"""
[[ 0.24080667 -0.52446211 -2.00060545 1.58069728]
[-0.25096401 0.18001484 -0.66252232 0.20919581]
[ 1.06301792 0.25150653 -0.67519772 -1.16752965]
[-0.61844643 0.60141776 -0.11604881 1.05742347]
[-0.63934044 -0.52350101 0.13534844 0.77631123]]
"""
df_obj = pd.DataFrame(array)
print(df_obj.head())
通過dict構建DataFrame
# 通過dict構建DataFrame
dict_data = {'A': 1.,
'B': pd.Timestamp('20161217'),
'C': pd.Series(1, index=list(range(4)),dtype='float32'),
'D': np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["Python","Java","C++","C#"]),
'F' : 'ChinaHadoop' }
print (dict_data) #無序
df_obj2 = pd.DataFrame(dict_data)
print(df_obj2.head())
"""
A B C D E F
0 1.0 2016-12-17 1.0 3 Python ChinaHadoop
1 1.0 2016-12-17 1.0 3 Java ChinaHadoop
2 1.0 2016-12-17 1.0 3 C++ ChinaHadoop
3 1.0 2016-12-17 1.0 3 C# ChinaHadoop
"""
通過列索引獲取列數據(Series類型 )
df_obj[col_idx] 或 df_obj.col_idx
# 通過列索引獲取列數據
print(df_obj2['A'])
print(type(df_obj2['A'])) #<class 'pandas.core.series.Series'>
print(df_obj2.A)
增加列數據,類似dict添加key-value
df_obj[new_col_idx] = data
# 增加列
df_obj2['G'] = df_obj2['D'] + 4
print(df_obj2.head())
刪除列
del df_obj[col_idx]
# 刪除列
del(df_obj2['G'] )
print(df_obj2.head())
索引對象Index
Series和DataFrame中的索引都是Index對象 不可變(immutable 保證了數據的安全)
常見的Index種類
• Index
• Int64Index
• MultiIndex,“層級”索引
• DatetimeIndex,時間戳類型
print(type(ser_obj.index))
print(type(df_obj2.index))
print(df_obj2.index)
"""
<class 'pandas.indexes.range.RangeIndex'>
<class 'pandas.indexes.numeric.Int64Index'>
Int64Index([0, 1, 2, 3], dtype='int64')
"""
# 索引對象不可變
df_obj2.index[0] = 2 #報錯
Pandas的數據操作
索引操作
Series索引操作
行索引,ser_obj[‘label’], ser_obj[pos]
切片索引,ser_obj[2:4], ser_obj[‘label1’: ’label3’]
# 切片索引
print(ser_obj[1:3])
print(ser_obj['b':'d']) #含 d
不連續索引,ser_obj[[‘label1’, ’label2’, ‘label3’]]
ser_obj[[pos1, pos2, pos3]]
# 不連續索引
print(ser_obj[[0, 2, 4]])
print(ser_obj[['a', 'e']])
布爾索引
ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e'])
print(ser_obj.head())
# 布爾索引
ser_bool = ser_obj > 2
print(ser_bool)
print(ser_obj[ser_bool])
print(ser_obj[ser_obj > 2])
"""
a False
b False
c False
d True
e True
dtype: bool
d 3
e 4
dtype: int64
d 3
e 4
dtype: int64
"""
DataFrame索引操作
列索引 df_obj[‘label’]
不連續索引 df_obj[[‘label1’, ‘label2’]]
# 列索引
print('列索引')
print(df_obj['a']) # 返回Series類型
print(type(df_obj[[0]])) # 返回DataFrame類型 #df_obj[['a']]
# 不連續索引
print('不連續索引')
print(df_obj[['a','c']])
print(df_obj[[1, 3]])
Pandas的索引操作
可歸納為3種
.loc,標簽索引
.iloc,位置索引
.ix,標簽與位置混合索引(先按標簽索引嘗試操作,然后再按位置索引嘗試操作)
DataFrame索引時可將其看作ndarray操作
• 標簽的切片索引是包含末尾位置的
# DataFrame
print(df_obj['a'])
print(df_obj.loc[0:2, 'a'])#標簽的切片索引是包含末尾位置的
"""
0 -0.236778
1 0.045082
2 -1.522824
3 1.232838
4 1.054741
Name: a, dtype: float64
0 -0.236778
1 0.045082
2 -1.522824
Name: a, dtype: float64
"""
# 整型位置索引 iloc
print(ser_obj[1:3]) #不含 ]
print(ser_obj.iloc[1:3])
# DataFrame
print(df_obj.iloc[0:2, 0])# 位置索引 0:2 不含2
# 注意和df_obj.loc[0:2, 'a']的區別
# 標簽的切片索引 是包含末尾位置
# 混合索引 ix
print(ser_obj.ix[1:3])
print(ser_obj.ix['b':'c'])
# DataFrame
print(df_obj.ix[0:2, 0]) # 先按標簽索引嘗試操作,然后再按位置索引嘗試操作
"""
0 -0.236778
1 0.045082
2 -1.522824
Name: a, dtype: float64
"""
運算與對齊
索引對齊運算,沒對齊的位置補NaN
Series 按行索引對齊
DataFrame按行、列索引對齊
import numpy as np
df1 = pd.DataFrame(np.ones((2,2)), columns = ['a', 'b'])
df2 = pd.DataFrame(np.ones((3,3)), columns = ['a', 'b', 'c'])
print('df1: ')
print(df1)
print('')
print('df2: ')
print(df2)
"""
df1:
a b
0 1.0 1.0
1 1.0 1.0
df2:
a b c
0 1.0 1.0 1.0
1 1.0 1.0 1.0
2 1.0 1.0 1.0
"""
填充未對齊的數據進行運算
使用add, sub, div, mul
同時通過fill_value指定填充值
填充NaN
df3 = df1 + df2
print(df3)
"""
a b c
0 2.0 2.0 NaN
1 2.0 2.0 NaN
2 NaN NaN NaN
"""
df3.fillna(100, inplace = True)
print(df3)
"""
a b c
0 2.0 2.0 100.0
1 2.0 2.0 100.0
2 100.0 100.0 100.0
"""
函數應用
# 使用apply應用行或列數據
#f = lambda x : x.max()
print(df.apply(lambda x : x.max()))
"""
0 0.149288
1 0.211810
2 0.725562
3 -0.223388
dtype: float64
"""
# 指定軸方向 行
print(df.apply(lambda x : x.max(), axis=1))
"""
0 0.725562
1 -0.423329
2 0.242500
3 -0.223388
4 -0.236904
dtype: float64
"""
使用applymap應用到每個數據
f2 = lambda x : '%.2f' % x
print(df.applymap(f2))
"""
0 1 2 3
0 -2.35 -1.36 0.73 -0.91
1 -2.37 -1.35 -0.59 -0.42
2 0.15 0.21 0.24 -0.68
3 -2.88 -1.44 -0.92 -0.22
4 -0.69 -0.24 -1.12 -1.17
"""
排序
sort_index,索引排序
(對DataFrame操作時注意軸方向)
按值排序
sort_values(by=‘label’)
處理缺失數據
判斷是否存在缺失值
ser_obj.isnull(), df_obj.isnull()
dropna 丟棄缺失數據
fillna 填充缺失數據