Python DataFrame删除含斜杠的event_name列行问题求助
Hey there! Let's get this sorted out. You're right to suspect regex might be playing a role here, but there are a couple of key tweaks to your code to make it work exactly how you want (removing rows with "/" instead of selecting them):
1. Invert the Condition to Target Rows for Deletion
Your original code was selecting rows that contain "/" — to delete those rows instead, you need to flip the condition using the tilde ~ operator:
df2 = Cov[~Cov['event_name'].str.contains("/")] display(df2)
2. Handle Missing Values and Regex Edge Cases
Even though "/" isn't a special regex character, if your dataset has any missing values (NaN) in the event_name column, str.contains() will return NaN for those rows, which can break the filtering. Fix this by adding the na=False parameter to treat missing values as not matching the condition:
df2 = Cov[~Cov['event_name'].str.contains("/", na=False)] display(df2)
Alternative: Explicit Literal Matching (Optional)
If you want to avoid regex entirely just to be extra safe, set regex=False to tell pandas to treat "/" as a plain literal character:
df2 = Cov[~Cov['event_name'].str.contains("/", regex=False, na=False)] display(df2)
Testing this with your sample event_name data:
Natalie Cvackova v Josephine Boualem、E Ymer v Khachanov、Karen Khachanov、Kuzmanov/Lazov v Koolhof/Middelkoop、Kuzmanov/Lazov、Kuzmanov/Lazov v Koolhof/Middelkoop、Koolhof/Middelkoop
The resulting df2 will exclude all rows with "/" (the 4th, 5th, 6th, and 7th entries), leaving only the first three rows.
内容的提问来源于stack exchange,提问作者tomoc4

