Python如何删除含'ball'的千列,仅保留'K15 - balls'列?
Fixing the Regex to Drop "ball" Columns But Keep "K15 - balls"
Let's break down what's going wrong with your current regex and fix it to meet your exact needs:
What's Wrong With the Original Regex
Your current code df.index.str.contains(K9\s|"ball") (I assume you meant to wrap the regex in quotes like r'K9\s|"ball"') has two key issues:
- It matches two separate patterns: any column with
K9followed by a space, AND any column with "ball". That's why you're accidentally deleting K9-related columns (and even K11 columns, which shouldn't match unless there's a typo—regardless, we don't want to touch these at all). - It doesn't exclude the specific "K15 - balls" column you want to keep.
The Correct Regex Solution
We need a regex that:
- Only targets columns containing the "ball" keyword (no more matching K9 or other unrelated patterns)
- Explicitly excludes the exact column name "K15 - balls"
Here's the adjusted regex and code:
# Identify columns to drop: any with "ball" except "K15 - balls" cols_to_drop = df.columns[df.columns.str.contains(r'^(?!K15 - balls$).*ball.*', regex=True)] # Drop the selected columns df = df.drop(cols_to_drop, axis=1)
Regex Breakdown
Let's unpack what this regex does:
^and$: Anchor the match to the start and end of the column name, ensuring we're checking the full name (not just a substring) for the exclusion.(?!K15 - balls$): This is a negative lookahead assertion—it tells the regex "don't match if the entire string is exactly 'K15 - balls'"..*ball.*: Matches any string that contains "ball" anywhere (the.*means any characters before or after).
Optional: Case Insensitivity
If your column names might have mixed case (like "Ball", "BALL", or "k15 - Balls"), add the case=False parameter to make the match case-insensitive:
cols_to_drop = df.columns[df.columns.str.contains(r'^(?!K15 - balls$).*ball.*', regex=True, case=False)]
This will ensure you catch all variations of "ball" while still preserving your specific "K15 - balls" column, and leave K9/K11 columns untouched.
内容的提问来源于stack exchange,提问作者user9238790
相关产品推荐
相关产品推荐

