如何以Pythonic方式从DataFrame中删除列值出现次数符合条件的行?
Got it, let's work through these two filtering tasks with Pandas. First, here's the original DataFrame we're starting with:
import pandas as pd data = [['bob', 1], ['james', 4], ['joe', 4], ['joe', 1], ['bob', 3], ['wendy', 5], ['joe', 7]] df = pd.DataFrame(data, columns=['name', 'score']) print(df)
Which outputs:
name score 0 bob 1 1 james 4 2 joe 4 3 joe 1 4 bob 3 5 wendy 5 6 joe 7
Task 1: Remove Rows Where Name Only Appears Once
The most Pythonic way to handle this is using either value_counts() with isin(), or a more streamlined approach with groupby() + transform(). Here's both options:
Option 1: Using value_counts()
# Get all names that show up more than once valid_names = df['name'].value_counts()[df['name'].value_counts() > 1].index # Filter the DataFrame to keep only those names filtered_df = df[df['name'].isin(valid_names)] print(filtered_df)
Option 2: Concise transform() Version
This avoids creating an intermediate variable and keeps everything in one line:
filtered_df = df[df.groupby('name')['name'].transform('count') > 1]
Either way, you'll get your desired result:
name score 0 bob 1 2 joe 4 3 joe 1 4 bob 3 6 joe 7
How this works: The transform('count') method adds a temporary column where each row has the total number of times its name appears in the DataFrame. We then filter out any rows where that count is <=1.
Task 2: Remove Rows Where Name Appears 1 or 2 Times
This is just a small tweak to the previous logic—we now want to keep only names that appear 3 or more times. Here's how to do it:
Option 1: Using value_counts()
valid_names = df['name'].value_counts()[df['name'].value_counts() >= 3].index filtered_df = df[df['name'].isin(valid_names)]
Option 2: Concise transform() Version
filtered_df = df[df.groupby('name')['name'].transform('count') >= 3]
Running this will leave you with only the rows for 'joe', which is the only name that appears 3+ times:
name score 2 joe 4 3 joe 1 6 joe 7
How this works: We just adjust the threshold from >1 to >=3, so any name with 1 or 2 occurrences gets filtered out.
内容的提问来源于stack exchange,提问作者lordy

