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

如何修复DataFrame行删除时的TypeError: ufunc 'invert'不支持输入类型错误?

Fixing That TypeError When Filtering Your DataFrame Rows

Let's walk through what's causing this error and how to get your filtering working exactly as you want.

Why You're Getting This TypeError

The problem boils down to Python's operator precedence rules. The ~ (bitwise NOT) operator runs before the > comparison operator. So when you write ~df['Field:FacilityCode'].str.len()>8, Python tries to flip the bits of the integer length values first—something that doesn't make sense for integers, hence the error about unsupported input types for the invert operation.

Solution 1: Filter by Exact Values (Best for Your Stated Goal)

Since you specifically want to keep only rows where Field:FacilityCode is mama100 or mimba190, the clearest and most reliable way is to check for those exact values directly. This avoids any confusion with string lengths and hits your target perfectly:

# Keep only the rows with your desired FacilityCode values
df = df[df['Field:FacilityCode'].isin(['mama100', 'mimba190'])]

Solution 2: Fix the Length-Based Filter (If You Prefer That Approach)

If you still want to filter based on string length (your original approach), you need to fix the operator precedence by wrapping each comparison in parentheses. Also, let's clarify the logic: your target values (mama100, mimba190) are both 7 characters long, while the ones you want to remove are shorter.

To keep only rows with a 7-character FacilityCode:

# Keep rows where the FacilityCode length is exactly 7
df = df[df['Field:FacilityCode'].str.len() == 7]

If you intended your original logic (even though it doesn't align with your target), here's how to fix the expression with proper parentheses:

# Correct the operator precedence with parentheses
df = df[~(df['Field:FacilityCode'].str.len() > 8) | ~(df['Field:FacilityCode'].str.len() > 7)]
# This simplifies to keeping rows where length <=8 (since <=8 includes <=7)
df = df[df['Field:FacilityCode'].str.len() <= 8]

Just note this will keep more rows than your desired target, so only use this if length is actually the criteria you need.

Quick Tip for Future Pandas Filtering

When using bitwise operators (~, |, &) with boolean indexing, always group your comparison expressions in parentheses. This avoids precedence bugs like the one you hit. And for explicit value matching, isin() is your go-to tool—it's readable and efficient.

内容的提问来源于stack exchange,提问作者Sista-Night

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:02:26