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

我将如何选择以下 df 的第 2 行到第 4 行以获得如下所示的所需输出。我尝试这样做df = df.index.between(2,4),但出现以下错误:AttributeError: 'Int64Index' object has no attribute '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


胡说叔叔
浏览 177回答 6
6回答

翻阅古今

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

侃侃尔雅

从数据框中选择行的最简单方法是使用 .iloc[rows, columns] 函数 pandas 例如这里我选择第 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使用标签切片进行索引选择:df.loc[2:4]输出:   col 1  col 2  col 32      2      1      53      1      2      24      3      2      4

holdtom

使用以下内容df.iloc[2:4]

万千封印

between不能作用于索引数据类型,只能作用于Series. to_series因此,如果您想使用布尔掩码,您首先需要使用以下命令将索引转换为序列: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     2df[df.index.to_series().between(2,4)]#    col1  col2  col3# 2     2     1     5# 3     1     2     2# 4     3     2     4

烙印99

与洛克min=2max=4between_range= range(min, max+1,1)df.loc[between_range] 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python