07. 行选择与切片1. 概述行选择是数据筛选的核心操作。Pandas 提供了多种行选择方式按位置选择、按标签选择、切片操作等。理解loc和iloc的区别是掌握行选择的关键。importpandasaspdimportnumpyasnp# 创建示例数据dfpd.DataFrame({姓名:[张三,李四,王五,赵六,钱七,孙八,周九,吴十],年龄:[25,30,28,32,35,27,29,31],城市:[北京,上海,广州,深圳,杭州,成都,武汉,西安],工资:[8000,12000,10000,15000,11000,9500,10500,12500],部门:[技术,销售,技术,市场,销售,技术,市场,销售]},index[a,b,c,d,e,f,g,h])print(原始数据:)print(df)print(f\n索引:{df.index.tolist()})2. 行选择的核心loc vs iloc方法全称使用方式说明loclocationdf.loc[行标签, 列标签]基于标签index/columnsilocinteger locationdf.iloc[行位置, 列位置]基于整数位置0,1,2…# loc 和 iloc 的区别示例print(loc[a] (基于标签):)print(df.loc[a])print(\niloc[0] (基于位置):)print(df.iloc[0])3. 使用 loc 选择行3.1 选择单行# 使用标签选择单行row_adf.loc[a]print(选择标签 a 的行:)print(row_a)print(f类型:{type(row_a)})# Series3.2 选择多行# 使用标签列表选择多行rowsdf.loc[[a,c,e]]print(选择标签 a, c, e:)print(rows)# 使用切片选择连续行包含结束标签rows_slicedf.loc[a:d]print(\n选择标签 a 到 d (包含 d):)print(rows_slice)注意loc的切片包含结束标签这与 Python 常规切片不同。3.3 使用布尔数组选择# 使用布尔列表mask[True,False,True,False,True,False,True,False]rows_booldf.loc[mask]print(使用布尔数组选择:)print(rows_bool)4. 使用 iloc 选择行4.1 选择单行# 使用位置索引选择单行row_0df.iloc[0]print(选择位置 0 的行:)print(row_0)4.2 选择多行# 使用位置列表选择多行rowsdf.iloc[[0,2,4]]print(选择位置 0, 2, 4:)print(rows)# 使用切片选择连续行不包含结束位置rows_slicedf.iloc[0:3]print(\n选择位置 0 到 2 (不包含3):)print(rows_slice)注意iloc的切片不包含结束位置与 Python 列表切片一致。4.3 负索引# 使用负索引从末尾开始last_rowdf.iloc[-1]print(最后一行:)print(last_row)last_threedf.iloc[-3:]print(\n最后三行:)print(last_three)5. 同时选择行和列5.1 loc 同时选择# loc[行标签, 列标签]subsetdf.loc[a:c,姓名:工资]print(loc 同时选择行和列:)print(subset)# 选择特定行和特定列subset2df.loc[[a,c,e],[姓名,工资]]print(\n选择特定行和列:)print(subset2)# 使用切片选择所有列: 表示全部subset3df.loc[a:c,:]print(\n选择行切片所有列:)print(subset3)5.2 iloc 同时选择# iloc[行位置, 列位置]subsetdf.iloc[0:3,0:3]print(iloc 同时选择行和列:)print(subset)# 选择特定行和特定列subset2df.iloc[[0,2,4],[0,3]]print(\n选择特定行和列:)print(subset2)# 使用切片选择所有列subset3df.iloc[0:3,:]print(\n选择行切片所有列:)print(subset3)6. 使用方括号选择行6.1 切片语法# 使用方括号进行行切片按位置first_threedf[0:3]print(df[0:3] 前3行:)print(first_three)# 注意这等价于 df.iloc[0:3]6.2 布尔索引下一章详细介绍# 条件筛选简写形式high_salarydf[df[工资]10000]print(工资 10000 的行:)print(high_salary)7. 行选择方法对比方法语法基于切片行为使用场景df.loc[]df.loc[a:c]标签包含结束知道索引标签df.iloc[]df.iloc[0:3]位置不包含结束知道行号df[]df[0:3]位置不包含结束快速切片# 对比示例print(loc[a:c]:)print(df.loc[a:c])print(\niloc[0:3]:)print(df.iloc[0:3])print(\ndf[0:3]:)print(df[0:3])8. 常见陷阱8.1 标签不存在# 标签不存在会报错try:df.loc[x]exceptKeyErrorase:print(f错误:{e})# 使用 get 方法安全访问rowdf.loc[a]ifaindf.indexelseNone8.2 整数标签与位置混淆# 当索引是整数时loc 和 iloc 行为不同df_int_indexpd.DataFrame({A:[1,2,3]},index[10,20,30])print(整数索引 DataFrame:)print(df_int_index)print(\ndf_int_index.loc[10]:)# 按标签 10print(df_int_index.loc[10])print(\ndf_int_index.iloc[0]:)# 按位置 0print(df_int_index.iloc[0])8.3 切片包含行为# loc 包含结束iloc 不包含dfpd.DataFrame({A:range(5)},indexrange(5))print(loc[1:3]:)print(df.loc[1:3])# 包含索引 3print(\niloc[1:3]:)print(df.iloc[1:3])# 不包含位置 39. 完整示例销售数据分析# 创建销售数据np.random.seed(42)salespd.DataFrame({日期:pd.date_range(2024-01-01,periods30,freqD),销售额:np.random.randint(5000,20000,30),订单数:np.random.randint(20,100,30),客户数:np.random.randint(15,80,30)})sales.set_index(日期,inplaceTrue)print(*60)print(销售数据分析)print(*60)print(sales.head())# 1. 选择前5行print(\n1. 前5行 (iloc):)print(sales.iloc[:5])# 2. 选择后5行print(\n2. 后5行 (iloc):)print(sales.iloc[-5:])# 3. 选择特定日期范围 (loc)print(\n3. 1月5日到1月10日:)print(sales.loc[2024-01-05:2024-01-10])# 4. 选择特定行和列print(\n4. 1月1日到1月7日的销售额和订单数:)print(sales.loc[2024-01-01:2024-01-07,[销售额,订单数]])# 5. 跳行选择print(\n5. 每隔5天取一天:)print(sales.iloc[::5])# 6. 按条件选择布尔索引print(\n6. 销售额 15000 的日子:)high_salessales[sales[销售额]15000]print(high_sales)# 7. 复杂条件print(\n7. 销售额 15000 且 订单数 60:)high_sales_high_orderssales[(sales[销售额]15000)(sales[订单数]60)]print(high_sales_high_orders)10. 总结需求方法示例按标签选择单行df.loc[label]df.loc[a]按标签选择多行df.loc[[a,b]]df.loc[[a,c]]按标签切片包含结束df.loc[a:c]df.loc[2024-01-01:2024-01-07]按位置选择单行df.iloc[pos]df.iloc[0]按位置选择多行df.iloc[[0,2]]df.iloc[[0,2,4]]按位置切片不包含结束df.iloc[0:3]df.iloc[:5]选择最后 n 行df.iloc[-n:]df.iloc[-5:]步长选择df.iloc[::n]df.iloc[::7]同时选择行和列df.loc[行, 列]df.loc[a:c, [A,B]]11. 快速参考# 常见行选择模式# 前5行df.head()# 等价于 df.iloc[:5]# 后5行df.tail()# 等价于 df.iloc[-5:]# 随机抽样df.sample(3)# 随机3行# 按索引标签选择df.loc[a]# 单行df.loc[a:d]# 连续多行包含ddf.loc[[a,c]]# 不连续多行# 按位置选择df.iloc[0]# 第一行df.iloc[0:3]# 前3行不包含3df.iloc[[0,2,4]]# 第0,2,4行