You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从DataFrame中移除首尾值为0的行(保留中间0值)

移除DataFrame首尾的0行(保留中间0行)

可以通过定位首尾非0值的索引,对DataFrame进行切片来实现,具体操作如下:

  1. 构造示例DataFrame(已有数据可跳过此步骤)
import pandas as pd

data = {'value': [0, 0, 0, 0, 1, 2, 0, 3, 0, 2, 5, 6, 0, 0, 0]}
df = pd.DataFrame(data)
  1. 定位首尾非0行索引并切片
# 获取第一个非0值的索引
first_idx = df[df['value'] != 0].index[0]
# 获取最后一个非0值的索引
last_idx = df[df['value'] != 0].index[-1]
# 切片得到目标结果
result = df.loc[first_idx:last_idx]

执行后result即为所需结果,输出如下:

value
4       1
5       2
6       0
7       3
8       0
9       2
10      5
11      6

也可以用更简洁的写法:

result = df.loc[df['value'].ne(0).idxmax():df['value'].ne(0)[::-1].idxmax()]

这里ne(0)等价于!=0,idxmax()返回第一个True值的索引;反转布尔序列后再调用idxmax(),就能得到原序列最后一个True值的索引。

内容的提问来源于stack exchange,提问作者KansaiRobot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:44:54