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

pythonserver side programmingprogramming更新于 2025/10/27 18:20:17

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

步骤

  • 创建一个二维、大小可变、可能异构的表格数据,df。
  • 打印输入 DataFrame,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

相关文章


有用资源