Python数据分析 知识量:13 - 56 - 232
选择某一行时,可以使用普通索引和位置索引。使用普通索引时,需要利用loc方法;使用位置索引时,需要利用iloc方法。为了更好的演示,读取exam_new时,将Name列指定为行索引。
import pandas as pd df=pd.read_excel(r"D:\PythonTestFile\exam_new.xlsx",index_col='Name') print(df,'\n') print(df.loc['Bob'],'\n') print(df.iloc[2])
运行结果为:
Sex Chinese English Math Name Noah male 90 50 66 Emma female 56 56 55 Bob male 99 84 89 Olivia female 86 87 44 Jeff male 48 87 65 Liam male 55 88 69 Sophia female 90 66 96 Isabella female 66 85 55 Sex male Chinese 99 English 84 Math 89 Name: Bob, dtype: object Sex male Chinese 99 English 84 Math 89 Name: Bob, dtype: object
对于iloc方法来说,因为在选择时,总是先选择行,再选择列,当默认选择所有列时,可以省略第2个参数。
选择多行的方法与选择多列相似,只是使用普通索引时需要使用loc方法。
import pandas as pd df=pd.read_excel(r"D:\PythonTestFile\exam_new.xlsx",index_col='Name') print(df,'\n') print(df.loc[['Bob','Jeff']],'\n') print(df.iloc[[2,4]])
运行结果为:
Sex Chinese English Math Name Noah male 90 50 66 Emma female 56 56 55 Bob male 99 84 89 Olivia female 86 87 44 Jeff male 48 87 65 Liam male 55 88 69 Sophia female 90 66 96 Isabella female 66 85 55 Sex Chinese English Math Name Bob male 99 84 89 Jeff male 48 87 65 Sex Chinese English Math Name Bob male 99 84 89 Jeff male 48 87 65
与选择连续列一样,通过区间(切片索引)可以选择连续行。
import pandas as pd df=pd.read_excel(r"D:\PythonTestFile\exam_new.xlsx",index_col='Name') print(df,'\n') print(df.iloc[1:4])
运行结果为:
Sex Chinese English Math Name Noah male 90 50 66 Emma female 56 56 55 Bob male 99 84 89 Olivia female 86 87 44 Jeff male 48 87 65 Liam male 55 88 69 Sophia female 90 66 96 Isabella female 66 85 55 Sex Chinese English Math Name Emma female 56 56 55 Bob male 99 84 89 Olivia female 86 87 44
要选择满足某些条件的行时,在数据表名称后面指明条件即可,这种方式称为布尔索引。可以设置单个条件,也可以设置多个条件,并利用逻辑运算符进行连接。
import pandas as pd df=pd.read_excel(r"D:\PythonTestFile\exam_new.xlsx",index_col='Name') print(df,'\n') print(df[df['Chinese']>60],'\n') print(df[(df['Chinese']>60) & (df['Sex']=='male')])
运行结果为:
Sex Chinese English Math Name Noah male 90 50 66 Emma female 56 56 55 Bob male 99 84 89 Olivia female 86 87 44 Jeff male 48 87 65 Liam male 55 88 69 Sophia female 90 66 96 Isabella female 66 85 55 Sex Chinese English Math Name Noah male 90 50 66 Bob male 99 84 89 Olivia female 86 87 44 Sophia female 90 66 96 Isabella female 66 85 55 Sex Chinese English Math Name Noah male 90 50 66 Bob male 99 84 89
注意:使用布尔索引时,需要确保最外层方括号中的结果总是布尔值。
Copyright © 2017-Now pnotes.cn. All Rights Reserved.
编程学习笔记 保留所有权利
MARK:3.0.0.20240214.P35
From 2017.2.6