Pandas的索引操作
索引對象Index
1. Series和DataFrame中的索引都是Index對象
示例代碼:
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')
2. 索引對象不可變,保證了數據的安全
示例代碼:
# 索引對象不可變 df_obj2.index[0] = 2
運行結果:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-23-7f40a356d7d1> in <module>() 1 # 索引對象不可變 ----> 2 df_obj2.index[0] = 2 /Users/Power/anaconda/lib/python3.6/site-packages/pandas/indexes/base.py in __setitem__(self, key, value) 1402 1403 def __setitem__(self, key, value): -> 1404 raise TypeError("Index does not support mutable operations") 1405 1406 def __getitem__(self, key): TypeError: Index does not support mutable operations
常見的Index種類
- Index,索引
- Int64Index,整數索引
- MultiIndex,層級索引
- DatetimeIndex,時間戳類型
Series索引
1. index 指定行索引名
示例代碼:
ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e']) print(ser_obj.head())
運行結果:
a 0 b 1 c 2 d 3 e 4 dtype: int64
2. 行索引
ser_obj[‘label’], ser_obj[pos]
示例代碼:
# 行索引 print(ser_obj['b']) print(ser_obj[2])
運行結果:
1 2
3. 切片索引
ser_obj[2:4], ser_obj[‘label1’: ’label3’]
注意,按索引名切片操作時,是包含終止索引的。
示例代碼:
# 切片索引 print(ser_obj[1:3]) print(ser_obj['b':'d'])
運行結果:
b 1 c 2 dtype: int64 b 1 c 2 d 3 dtype: int64
4. 不連續索引
ser_obj[[‘label1’, ’label2’, ‘label3’]]
示例代碼:
# 不連續索引 print(ser_obj[[0, 2, 4]]) print(ser_obj[['a', 'e']])
運行結果:
a 0 c 2 e 4 dtype: int64 a 0 e 4 dtype: int64
5. 布爾索引
示例代碼:
# 布爾索引 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索引
1. columns 指定列索引名
示例代碼:
import numpy as np df_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd']) print(df_obj.head())
運行結果:
a b c d
0 -0.241678 0.621589 0.843546 -0.383105
1 -0.526918 -0.485325 1.124420 -0.653144
2 -1.074163 0.939324 -0.309822 -0.209149
3 -0.716816 1.844654 -2.123637 -1.323484
4 0.368212 -0.910324 0.064703 0.486016

2. 列索引
df_obj[[‘label’]]
示例代碼:
# 列索引 print(df_obj['a']) # 返回Series類型 print(df_obj[[0]]) # 返回DataFrame類型 print(type(df_obj[[0]])) # 返回DataFrame類型
運行結果:
0 -0.241678 1 -0.526918 2 -1.074163 3 -0.716816 4 0.368212 Name: a, dtype: float64 <class 'pandas.core.frame.DataFrame'>
3. 不連續索引
df_obj[[‘label1’, ‘label2’]]
示例代碼:
# 不連續索引 print(df_obj[['a','c']]) print(df_obj[[1, 3]])
運行結果:
a c 0 -0.241678 0.843546 1 -0.526918 1.124420 2 -1.074163 -0.309822 3 -0.716816 -2.123637 4 0.368212 0.064703 b d 0 0.621589 -0.383105 1 -0.485325 -0.653144 2 0.939324 -0.209149 3 1.844654 -1.323484 4 -0.910324 0.486016
高級索引:標簽、位置和混合
Pandas的高級索引有3種
1. loc 標簽索引
DataFrame 不能直接切片,可以通過loc來做切片
loc是基於標簽名的索引,也就是我們自定義的索引名
示例代碼:
# 標簽索引 loc # Series print(ser_obj['b':'d']) print(ser_obj.loc['b':'d']) # DataFrame print(df_obj['a']) # 第一個參數索引行,第二個參數是列 print(df_obj.loc[0:2, 'a'])
運行結果:
b 1 c 2 d 3 dtype: int64 b 1 c 2 d 3 dtype: int64 0 -0.241678 1 -0.526918 2 -1.074163 3 -0.716816 4 0.368212 Name: a, dtype: float64 0 -0.241678 1 -0.526918 2 -1.074163 Name: a, dtype: float64
2. iloc 位置索引
作用和loc一樣,不過是基於索引編號來索引
示例代碼:
# 整型位置索引 iloc # Series print(ser_obj[1:3]) print(ser_obj.iloc[1:3]) # DataFrame print(df_obj.iloc[0:2, 0]) # 注意和df_obj.loc[0:2, 'a']的區別
運行結果:
b 1 c 2 dtype: int64 b 1 c 2 dtype: int64 0 -0.241678 1 -0.526918 Name: a, dtype: float64
3. ix 標簽與位置混合索引
ix是以上二者的綜合,既可以使用索引編號,又可以使用自定義索引,要視情況不同來使用,
如果索引既有數字又有英文,那么這種方式是不建議使用的,容易導致定位的混亂。
示例代碼:
# 混合索引 ix # Series print(ser_obj.ix[1:3]) print(ser_obj.ix['b':'c']) # DataFrame print(df_obj.loc[0:2, 'a']) print(df_obj.ix[0:2, 0])
運行結果:
b 1 c 2 dtype: int64 b 1 c 2 dtype: int64 0 -0.241678 1 -0.526918 2 -1.074163 Name: a, dtype: float64
注意
DataFrame索引操作,可將其看作ndarray的索引操作
標簽的切片索引是包含末尾位置的
