You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas中.loc反向切片为何无法正常工作?

Pandas中.loc选取最后n行失效的原因与解决办法

在Pandas中有两种获取DataFrame子集的方式:

  • df['columns']['rows']
  • df.loc['rows', 'columns']

选取DataFrame某一列的前n行时两者都能正常工作,但选取后n行时,df.loc[-2:, 'Mean']会返回整个DataFrame,而df['Mean'][-2:]却能正确返回最后两行,以下是具体场景和问题解析:

测试用DataFrame创建代码

import pandas as pd
import numpy as np

male = [6, 14, 12, 13, 21, 14, 14, 14, 14, 18]
female = [9, 11, 6, 10, 11, 13, 12, 11, 9, 11]

df = pd.DataFrame({'Male': male,
                    'Female': female}, 
                    index = np.arange(1, 11))
df['Mean'] = df[['Male', 'Female']].mean(axis = 1).round(1)

前两行选取测试

print('Method A: \n', df['Mean'][:2])
print('Method B: \n', df.loc[:2, 'Mean'])

输出:

Method A: 
1     7.5
2    12.5

Method B: 
1     7.5
2    12.5

最后两行选取测试

print('Method A: \n', df['Mean'][-2:])
print('Method B: \n', df.loc[-2:, 'Mean'])

输出:

Method A: 
9     11.5
10    14.5

Method B: 
1      7.5
2     12.5
3      9.0
4     11.5
5     16.0
6     13.5
7     13.0
8     12.5
9     11.5
10    14.5

原因分析

  • 方法A中df['Mean']返回的是Series对象,Series的[-2:]属于位置索引,直接根据元素在序列中的位置取最后两行,和索引标签无关。
  • 方法B中的.loc是标签索引,df.loc[-2:, 'Mean']里的-2会被当作索引标签去匹配,但你的DataFrame索引是1到10,不存在-2这个标签。Pandas在标签索引遇到不存在的起始标签时,会默认从第一行开始返回所有行,因此得到了整个DataFrame的Mean列。

解决办法

1. 使用位置索引.iloc

.iloc是按位置定位的索引方式,和Series的切片逻辑一致:

# 取最后两行,Mean列
df.iloc[-2:, df.columns.get_loc('Mean')]

2. 获取最后两行的索引标签后用.loc

先拿到最后两行的索引值,再用.loc匹配:

last_two_labels = df.index[-2:]
df.loc[last_two_labels, 'Mean']

3. 直接使用tail()方法

tail(n)可以直接获取DataFrame的最后n行,再指定列即可:

df['Mean'].tail(2)
# 或者结合.loc
df.loc[df.tail(2).index, 'Mean']

内容的提问来源于stack exchange,提问作者Stxffan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:05:23