Python DataFrame删除指定值行报错:TypeError: unhashable type: 'list'
Let's break down what's going wrong here and fix it step by step:
1. Why the TypeError: unhashable type: 'list' occurs
You wrapped your aircraft_CS list in an extra set of square brackets ([aircraft_CS]), turning it into a list that contains another list. Pandas' isin() method expects an iterable of hashable elements (like integers, strings, or tuples), but lists are unhashable—this is exactly what's triggering the error.
2. A hidden pitfall to watch for
You noted that the AIRCRAFT column is a string field, but range(4888, 4893) generates integers. Even after fixing the bracket issue, trying to match integers against string values will result in no rows being filtered out, since the types don't align.
The Corrected Code
First, convert your target values to strings to match the column's data type, then pass the list directly to isin() without extra wrapping:
# Generate string versions of 4888 to 4892 (range excludes the end value) aircraft_CS = [str(num) for num in range(4888, 4893)] # Filter out rows where AIRCRAFT matches any value in the target list df_adhoc_1_final = df_adhoc_1_final[~df_adhoc_1_final['AIRCRAFT'].isin(aircraft_CS)]
Extra Tip for Edge Cases
If your AIRCRAFT strings have leading or trailing whitespace (e.g., " 4888" or "4888 "), clean the column first to ensure accurate matches:
# Remove whitespace from the start/end of each AIRCRAFT string df_adhoc_1_final['AIRCRAFT'] = df_adhoc_1_final['AIRCRAFT'].str.strip()
内容的提问来源于stack exchange,提问作者PineNuts0

