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

如何快速系统迭代删除数据框中每类的最后一行?

Solution for Iteratively Removing Last Row of Each Category in a DataFrame

Got it, let's break down how to solve this problem step by step. First, let's align on the context: you have a 620-row single-column DataFrame, split into 20 categories each with exactly 31 rows (starting with category A, then B, and so on through the 20th category). You need to repeatedly delete the last row of every category in each iteration.

Step 1: (If Needed) Add a Category Column

First, if your DataFrame doesn’t already have a column marking which category each row belongs to, we need to add this to group rows easily. Here’s how to generate and attach category labels:

import pandas as pd
import numpy as np

# 模拟你的单列DataFrame(替换成你实际的df即可)
df = pd.DataFrame({'your_column_name': np.arange(620)})

# 生成20个类别标签(A到T),每个重复31次匹配你的数据结构
category_labels = [chr(ord('A') + i) for i in range(20)]
df['category'] = np.repeat(category_labels, 31)

Step 2: Iteratively Remove Last Row of Each Category

You can choose between a fixed number of iterations or looping until no rows remain.

Option 1: Fixed Number of Iterations

If you know exactly how many times you want to run the deletion:

# 设置迭代次数,比如执行15次
number_of_iterations = 15

for idx in range(number_of_iterations):
    # 按类别分组,保留每组除最后一行外的所有行
    df = df.groupby('category').apply(lambda group: group.iloc[:-1]).reset_index(drop=True)
    # 可选:打印迭代进度,验证效果
    print(f"After iteration {idx+1}: {len(df)} rows remaining")

Option 2: Loop Until No Rows Are Left

If you want to keep deleting until every category is fully removed:

while not df.empty:
    # 执行一次删除操作
    df = df.groupby('category').apply(lambda group: group.iloc[:-1]).reset_index(drop=True)
    # 打印当前剩余行数
    print(f"Rows remaining: {len(df)}")
    # 当所有类别被删完时,df会为空,循环自动终止

How This Works

  • groupby('category'): Groups rows by their category label, so we can handle each category independently.
  • lambda group: group.iloc[:-1]: For each group, this retains all rows except the last one (iloc[:-1] selects up to but not including the final index).
  • reset_index(drop=True): Cleans up the index after grouping to avoid multi-level index issues.

Notes

  • If your original DataFrame already has a category column, skip Step 1 and use that column name in the groupby call.
  • Each iteration removes 20 rows (one per category), so after n iterations you’ll have 620 - 20*n rows left—until categories start getting fully deleted once their row count hits 0.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:26:39