文章目錄
- 索引對象
- 多個數據結構之間共享index類對象
- is與==的區別
- 重置索引——reindex()
- 索引操作
- Series的索引操作
- 切片
- 不連續索引
- 布爾型索引
- DataFrame的索引操作
- 獲取不連續的Series對象
- 切片
- Pandas庫中的操作索引方法
索引對象
Index類對象,該對象不可以進行修改(不可變性),以保證數據的安全。
多個數據結構之間共享index類對象
基于Index類對象的不可變性,實現兩個以上數據結構共享一個索引
import pandas as pd
import numpy as npser_obj1 = pd.Series(range(3), index=['a', 'b', 'c'])
ser_obj2 = pd.Series(['a', 'b', 'c'], index=ser_obj1.index)
print(ser_obj2.index is ser_obj1.index)
print(ser_obj1)
print(ser_obj2)
輸出結果:
Truea 0
b 1
c 2
dtype: int64a a
b b
c c
dtype: object
is與==的區別
is比較的是兩個對象的地址值,也就是說兩個對象是否為同一個實例對象;而==比較的是對象的值是否相等。
重置索引——reindex()
該方法的作用時對原索引和新索引進行匹配,新索引含有原索引的數據,而原索引數據按照新索引排序。
語法格式:
DataFrame.reindex(labels = None, index = None, columns = None, axis = None, method = None,
copy = None, level = None, fill_value = nan, limit = None, tolerance = None)
上述方法的部分參數含義如下:
index:用作索引的新序列
method:插值填充方式
fill_value:引入缺失值時使用的替代值
limit:前向或者后向填充時的最大填充量
如果新索引中沒有原索引的數據,那么將新添加的索引的值填充為NaN。
ser_obj5 = pd.Series(range(1, 6, 1), index=['c', 'd', 'a', 'b', 'e'])
print("ser_obj5", ser_obj5)
ser_obj6 = ser_obj5.reindex(['a', 'b', 'c', 'd', 'e', 'f'])
print("ser_obj6", ser_obj6)
輸出結果:
ser_obj5
c 1
d 2
a 3
b 4
e 5
dtype: int64ser_obj6
a 3.0
b 4.0
c 1.0
d 2.0
e 5.0
f NaN
dtype: float64
如果不想填充為NaN,則可使用fill_value參數來指定缺失值。
ser_obj7 = ser_obj5.reindex(['a', 'b', 'c', 'd', 'e', 'f'], fill_value=6)
print("ser_obj7", ser_obj7)
輸出結果:
ser_obj7
a 3
b 4
c 1
d 2
e 5
f 6
dtype: int64
fill_value參數會讓所有的缺失值都填充為同一個值。
如果期望使用相鄰的元素值(上或下一個元素的值)進行填充,則可使用method參數。
參數 | 說明 |
---|---|
ffill 或 pad | 前向填充值 |
bfill 或 backfill | 后向填充值 |
nearest | 從最近的索引值填充(先后再前) |
ser_obj3 = pd.Series([1, 3, 5, 7], index=[0, 2, 3, 6])
print("ser_obj3", ser_obj3)
ser_obj4 = ser_obj3.reindex(range(7), method="nearest")
print("ser_obj4", ser_obj4)
輸出結果:
ser_obj3
0 1
2 3
3 5
6 7
dtype: int64ser_obj4
0 1
1 3
2 3
3 5
4 5
5 7
6 7
dtype: int64
索引操作
Series的索引操作
兩種索引方式:
print("ser_obj1[2]:", ser_obj1[2]) # 使用索引位置獲得數據
print("ser_obj1['c']:", ser_obj1['c']) # 使用索引名稱獲取數據
ser_obj1
a 0
b 1
c 2
dtype: int64
輸出結果:
ser_obj1[2]: 2
ser_obj1['c']: 2
切片
位置索引進行切片,切片結果包含起始位置不包括結束位置(前閉后開)
索引名稱進行切片,切片結果包含起始位置包括結束位置(前閉后閉)
print("ser_obj5[2:4]:\n", ser_obj5[2:4]) # 使用位置索引進行切片
print("ser_obj7['b':'d']:\n", ser_obj7['b':'d']) # 使用索引名稱進行切片
ser_obj5
c 1
d 2
a 3
b 4
e 5
dtype: int64
ser_obj7
a 3
b 4
c 1
d 2
e 5
f 6
dtype: int64
輸出結果:
ser_obj5[2:4]:a 3
b 4
dtype: int64ser_obj7['b':'d']:b 4
c 1
d 2
dtype: int64
不連續索引
print("ser_obj5[[0, 2, 4]]:\n", ser_obj5[[0, 2, 4]]) # 通過不連續位置索引獲取數據集
print("ser_obj7[['a', 'c', 'e']]:\n", ser_obj7[['a', 'c', 'e']]) # 通過不連續索引名稱獲取數據集
輸出結果:
ser_obj5[[0, 2, 4]]:c 1
a 3
e 5
dtype: int64
ser_obj7[['a', 'c', 'e']]:a 3
c 1
e 5
dtype: int64
布爾型索引
將布爾型的數組索引作為模板篩選數據,返回與模板中True位置對應的元素
ser_bool = ser_obj7 > 2 # 創建布爾型Series對象
print("ser_bool:\n", ser_bool)
print("ser_obj7[ser_bool]:\n", ser_obj7[ser_bool]) # 獲取結果為True的數據
輸出結果:
ser_bool:a True
b True
c False
d False
e True
f True
dtype: boolser_obj7[ser_bool]:a 3
b 4
e 5
f 6
dtype: int64
DataFrame的索引操作
DataFrame中每列的數據都是一個Series對象,可以使用列索引獲取
arr1 = np.arange(12).reshape(3, 4)
df_obj1 = pd.DataFrame(arr1, columns=['a', 'b', 'c', 'd'])
# 創建DataFrame對象,并為其指定列索引
print("df_obj1:\n", df_obj1)
print("df_obj1['b']:\n", df_obj1['b']) # 獲取b列的數據
輸出結果:
df_obj1:a b c d
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11df_obj1['b']:0 1
1 5
2 9
Name: b, dtype: int32
獲取不連續的Series對象
print("df_obj1[['b', 'd']]:\n", df_obj1[['b', 'd']])
輸出結果:
df_obj1[['b', 'd']]:b d
0 1 3
1 5 7
2 9 11
切片
print("df_obj1[:2]:\n", df_obj1[:2]) # 使用切片獲取第0~1行的數據
print("df_obj1[:3][['b', 'd']]:\n", df_obj1[:3][['b', 'd']])
# 使用切片先通過行索引獲取0~2行的數據,再通過不連續列索引獲取b、d列的數據
輸出結果:
df_obj1[:2]:a b c d
0 0 1 2 3
1 4 5 6 7df_obj1[:3][['b', 'd']]:b d
0 1 3
1 5 7
2 9 11
Pandas庫中的操作索引方法
loc:基于標簽索引(索引名稱,如:a、b等),用于按標簽選取數據。當執行切片操作時,既包含起始索引,也包含結束索引。(前閉后閉)
iloc:基于位置索引(整數索引,如:0~length-1),用于按位置選取數據。當執行切片操作時,只包含起始索引,不包含結束索引。(前閉后開)
iloc方法主要使用整數來索引數據,而不能使用字符標簽來索引數據。
loc方法只能使用字符標簽來索引數據,而不能使用整數來索引數據。不過,當DataFrame對象的行索引或者列索引使用的是整數時,則其就可以使用整數來索引。
print("df_obj1.loc[:, [“d”, “b”]]:\n", df_obj1.loc[:, ["d", "b"]])
print("df_obj1.iloc[:, 3, 1]:\n", df_obj1.iloc[:, [3, 1]])
輸出結果:
df_obj1.loc[:, [“d”, “b”]]d b
0 3 1
1 7 5
2 11 9df_obj1.iloc[:, 3, 1]:d b
0 3 1
1 7 5
2 11 9
花式索引【數組索引】
print("df_obj1.loc[:1, [“c”, “a”]]:\n", df_obj1.loc[0:1, ["c", "a"]])
print("df_obj1.iloc[:2, [2, 0]]:\n", df_obj1.iloc[0:2, [2, 0]])
輸出結果:
df_obj1.loc[:1, [“c”, “a”]]:c a
0 2 0
1 6 4df_obj1.iloc[:2, [2, 0]]:c a
0 2 0
1 6 4