Python pandas:如何将df.drop删除的行赋值给新变量?及代码排查
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:
Create the mask (marks rows where
letteris "a"):mask = df1['letter'] == 'a'Get the dropped rows (df3) (filter rows where the mask is
True):df3 = df1[mask]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

