import pandas as pd
from pandas import DataFrame
import numpy as np
Index
Index對象保存着索引標籤數據,它可以快速找到標籤對應的整數下標,其功能與Python的字典類似。
dict1={"Province":["Guangdong","Beijing","Qinghai","Fujiang"],
"year":[2018]*4,
"pop":[1.3,2.5,1.1,0.7]}
df1=DataFrame(dict1)
df1
代碼結果
Province | pop | year | |
---|---|---|---|
0 | Guangdong | 1.3 | 2018 |
1 | Beijing | 2.5 | 2018 |
2 | Qinghai | 1.1 | 2018 |
3 | Fujiang | 0.7 | 2018 |
- 調用.columns返回DataFrame對象的列索引(即所有列標籤):
col_index=df1.columns
col_index.values
代碼結果:
array(['Province', 'pop', 'year'], dtype=object)
ind_index=df1.index
ind_index.values
代碼結果:
array([0, 1, 2, 3], dtype=int64)
- Index對象可當做一維數組,適合Numpy數組的下標運算,但Index對象只是可讀,創建後不可修改。
print(col_index[[1,2]])
print(ind_index[ind_index>1])
代碼結果:
Index(['pop', 'year'], dtype='object')
Int64Index([2, 3], dtype='int64')
- index對象具有字典的映射功能,.get_loc(value)獲得單值得下標,.get_indexer(values)獲得一組值得下標,當值不存在則返回-1:
print(col_index.get_loc('pop'))
print(col_index.get_indexer(['pop','year']))
代碼結果:
1
[1 2]
- Index對象調用Index()來創建,可傳遞給DataFrame對象的參數index和columns。因爲Index是不可變的,因此多個DataFrame對象的索引可以是同個Index對象。
index=pd.Index(['a','b','c'])
df2=DataFrame(np.random.randint(1,10,(3,3)),index=index,columns=index)
df2
代碼結果:
a | b | c | |
---|---|---|---|
a | 4 | 6 | 1 |
b | 8 | 6 | 9 |
c | 9 | 1 | 6 |
謝謝大家的瀏覽,
希望我的努力能幫助到您,
共勉!