1. 程式人生 > 其它 >pandas-DataFrame通過標籤索引loc和位置索引 iloc獲取資料

pandas-DataFrame通過標籤索引loc和位置索引 iloc獲取資料

技術標籤:pandasPython基礎知識pandas標籤索引--loc位置索引--iloc

程式碼示例:

import pandas as pd

df = pd.read_csv('test.csv')
print(df)
'''
列印:
   userId  score  age
0       1     45   18
1       2     65   19
2       3     58   17
3       4     92   16
4       5     78   18
'''

'''
df.loc[]  通過標籤索引獲取資料
df.iloc[] 通過位置索引獲取資料
'''

df.index = list("qwert")
print(df.loc['w','age'])    #列印:19
print(df.loc['w']) 
print(df.loc['w',:]) 
'''
以上兩個均為列印一行,型別為Series結果如下:
userId     2
score     65
age       19
Name: w, dtype: int64
'''
print(df.loc[['w','r']])
print(df.loc[['w','r'],:])
'''
以上兩個均為列印一行,型別為DataFrame,結果如下:
   userId  score  age
w       2     65   19
r       4     92   16
'''
print(df.loc[['w','r'],['userId','score']])
'''
獲取多行多列,列印:
   userId  score
w       2     65
r       4     92
'''
age_18 = df.loc[df['age']==18]
print(age_18)
'''
選取年齡為18歲的同學,列印:
   userId  score  age
q       1     45   18
t       5     78   18
'''
print(age_18['score'])
'''
列印:
q    45
t    78
Name: score, dtype: int64
'''
#iloc與loc類似,取位置索引
print(df.iloc[[0,3],:])
'''
列印:
   userId  score  age
q       1     45   18
r       4     92   16
'''import pandas as pd

df = pd.read_csv('test.csv')
print(df)
'''
列印:
   userId  score  age
0       1     45   18
1       2     65   19
2       3     58   17
3       4     92   16
4       5     78   18
'''

'''
df.loc[]  通過標籤索引獲取資料
df.iloc[] 通過位置索引獲取資料
'''

df.index = list("qwert")
print(df.loc['w','age'])    #列印:19
print(df.loc['w']) 
print(df.loc['w',:]) 
'''
以上兩個均為列印一行,型別為Series結果如下:
userId     2
score     65
age       19
Name: w, dtype: int64
'''
print(df.loc[['w','r']])
print(df.loc[['w','r'],:])
'''
以上兩個均為列印一行,型別為DataFrame,結果如下:
   userId  score  age
w       2     65   19
r       4     92   16
'''
print(df.loc[['w','r'],['userId','score']])
'''
獲取多行多列,列印:
   userId  score
w       2     65
r       4     92
'''
age_18 = df.loc[df['age']==18]
print(age_18)
'''
選取年齡為18歲的同學,列印:
   userId  score  age
q       1     45   18
t       5     78   18
'''
print(age_18['score'])
'''
列印:
q    45
t    78
Name: score, dtype: int64
'''
#iloc與loc類似,取位置索引
print(df.iloc[[0,3],:])
'''
列印:
   userId  score  age
q       1     45   18
r       4     92   16
'''