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

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

我们可以切片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 "输入的DataFrame为:\n", df

index_lower_limit = 1
index_upper_limit = 3

print("在两个索引值之间的DataFrame为:\n", df[index_lower_limit: index_upper_limit])

输出

输入的DataFrame为:
 x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1

在两个索引值之间的DataFrame为:
 x y z
1 2 7 3
2 7 5 5

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程