在 Python Pandas 中选择两个索引值之间的 DataFrame 行

我们可以切片 Pandas DataFrame 来选择两个索引值之间的行。让我们举一个例子,看看它是如何完成的。

步骤

  • 创建二维、大小可变、潜在异构的表格数据df

  • 打印输入数据帧df

  • 为索引的下限初始化一个变量。

  • 为索引的上限初始化另一个变量。

  • 使用df[index_lower_limit: index_upper_limit]打印范围索引中的 DataFrame。

示例

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)
print "Input DataFrame is:\n", df

index_lower_limit = 1
index_upper_limit = 3

print("DataFrame between two index values:\n",
df[index_lower_limit: index_upper_limit])
输出结果
Input DataFrame is:
  x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1

DataFrame between two index values:
  x y z
1 2 7 3
2 7 5 5