pandas-DataFrame通过标签索引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
'''

猜你喜欢

转载自blog.csdn.net/caoxinjian423/article/details/112567970
今日推荐