Python 如何根据两个数字之间的索引值从数据集中选择行

Python 如何根据两个数字之间的索引值从数据集中选择行,python,pandas,Python,Pandas,如何选择以下df中的第2行到第4行以获得如下所示的所需输出。 我尝试执行df=df.index.between(2,4),但出现以下错误:AttributeError:'Int64Index'对象没有属性'between' col 1 col 2 col 3 0 1 1 2 1 5 4 2 2 2 1 5 3 1 2 2 4 3 2 4 5 4 3 2 期望输出 col 1 col 2 co

如何选择以下df中的第2行到第4行以获得如下所示的所需输出。 我尝试执行
df=df.index.between(2,4)
,但出现以下错误:
AttributeError:'Int64Index'对象没有属性'between'

    col 1   col 2   col 3
0   1   1   2
1   5   4   2
2   2   1   5
3   1   2   2
4   3   2   4
5   4   3   2
期望输出

    col 1   col 2   col 3
2   2   1   5
3   1   2   2
4   3   2   4

尝试使用标签切片使用
loc
进行索引选择:

df.loc[2:4]
输出:

   col 1  col 2  col 3
2      2      1      5
3      1      2      2
4      3      2      4

尝试使用标签切片使用
loc
进行索引选择:

df.loc[2:4]
输出:

   col 1  col 2  col 3
2      2      1      5
3      1      2      2
4      3      2      4

从数据帧中选择行的最简单方法是使用.iloc[rows,columns]函数,例如,这里我选择第2行到第4行

df1=pd.DataFrame({"a":[1,2,3,4,5,6,7],"b":[4,5,6,7,8,9,10]})
df1.iloc[1:3] #

从数据帧中选择行的最简单方法是使用.iloc[rows,columns]函数,例如,这里我选择第2行到第4行

df1=pd.DataFrame({"a":[1,2,3,4,5,6,7],"b":[4,5,6,7,8,9,10]})
df1.iloc[1:3] #
与loc

min=2
max=4
between_range= range(min, max+1,1)
df.loc[between_range] 
与loc

min=2
max=4
between_range= range(min, max+1,1)
df.loc[between_range] 
使用以下命令

df.iloc[2:4]
使用以下命令

df.iloc[2:4]

您想使用.iloc[行,列]


df.iloc[2:4,:]
您想使用.iloc[行,列]

df.iloc[2:4,:]
不能作用于索引数据类型,而只能作用于
系列
。因此,如果要使用布尔掩码,首先需要使用以下命令将索引转换为序列:

df
#    col1  col2  col3
# 0     1     1     2
# 1     5     4     2
# 2     2     1     5
# 3     1     2     2
# 4     3     2     4
# 5     4     3     2

df[df.index.to_series().between(2,4)]
#    col1  col2  col3
# 2     2     1     5
# 3     1     2     2
# 4     3     2     4
无法对索引数据类型执行操作,只能对
系列执行操作。因此,如果要使用布尔掩码,首先需要使用以下命令将索引转换为序列:

df
#    col1  col2  col3
# 0     1     1     2
# 1     5     4     2
# 2     2     1     5
# 3     1     2     2
# 4     3     2     4
# 5     4     3     2

df[df.index.to_series().between(2,4)]
#    col1  col2  col3
# 2     2     1     5
# 3     1     2     2
# 4     3     2     4