Pandas DataFrame truncate() 方法

定义和用法

truncate() 方法移除指定索引或标签之前和之后的元素。

使用 axis='columns' 参数来删除指定的列。

实例

移除 DataFrame 位置 3 之前和位置 5 之后的行:

import pandas as pd

data = {
  "age": [50, 40, 30, 40, 20, 10, 30],
  "qualified": [True, False, False, False, False, True, True]
}
df = pd.DataFrame(data)

newdf = df.truncate(before=3, after=5)

print(newdf)

亲自试一试

语法

dataframe.truncate(before, after, axis, copy)

参数

beforeafteraxiscopy 参数是关键字参数

参数 描述
before
  • Number
  • Label
  • Date
可选。移除此值之前的所有内容。
after
  • Number
  • Label
  • Date
可选。移除此值之后的所有内容。
axis
  • 0
  • 1
  • 'index'
  • 'columns'

可选。要截断的轴。

默认为 0。

copy
  • True
  • False

可选。指定是否返回 DataFrame 的副本。

默认为 True。

返回值

包含结果的 DataFrame