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

Python pandas:如何将df.drop删除的行赋值给新变量?及代码排查

Solution to Split DataFrame into Kept and Dropped Rows

Hey there! Let's fix your pandas issue and get those two DataFrames you need for logging.

First, why your original code didn't work

Your line df2 = df1.drop(df1.letter == "a", axis=0) is incorrect because the drop() method expects row/column labels (like index values or column names) as its first argument, not a boolean array. That's why the rows with "a" weren't fully removed—pandas didn't understand which rows you wanted to drop!

The correct approach to get both DataFrames

The cleanest way is to first create a boolean mask to identify the rows you want to remove, then use that mask to split your original DataFrame:

  1. Create the mask (marks rows where letter is "a"):

    mask = df1['letter'] == 'a'
    
  2. Get the dropped rows (df3) (filter rows where the mask is True):

    df3 = df1[mask]
    
  3. Get the remaining rows (df2) (filter rows where the mask is False, using ~ to invert the mask):

    df2 = df1[~mask]
    

Full working code example

import pandas as pd

L = ["a","b","c","d","a","a"]
df1 = pd.DataFrame(L)
df1.columns = ['letter']

# Create mask for rows to drop
mask = df1['letter'] == 'a'

# Split into dropped and kept DataFrames
df3 = df1[mask]  # Contains rows 0,4,5 with "a"
df2 = df1[~mask] # Contains rows 1,2,3 with "b","c","d"

print("Kept rows (df2):")
print(df2)
print("\nDropped rows (df3):")
print(df3)

Alternative using df.drop()

If you specifically want to use drop(), you can pass the indices of the rows to drop:

drop_indices = df1[mask].index
df2 = df1.drop(drop_indices, axis=0)
df3 = df1.loc[drop_indices]

This works the same way—you're just explicitly telling drop() which row indices to remove, then using those indices to grab the dropped rows for logging.

Either method will give you exactly what you need: two separate DataFrames, one with the rows you kept, and one with the rows you removed for your logs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:10:20