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

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 K9 followed 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:

  1. Only targets columns containing the "ball" keyword (no more matching K9 or other unrelated patterns)
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:12:55