pandas删除含NaN行报错:TypeError无效切片键问题求助
Ah, I see the issue here! Your error comes from using numpy-style 2D slicing (data[:59,:]) with pandas' drop() method, which doesn't accept that kind of key. The drop() function expects row labels (indices) or a boolean mask, not a slice like that. Let's fix this with a few straightforward solutions:
Solution 1: Drop rows by index range
Since you know exactly which rows (0 to 58) need removal, you can pass the range of indices directly to drop():
# Drop rows 0 to 58 (inclusive) data.drop(index=range(59), inplace=True) print(data)
If you prefer not to modify the original DataFrame in-place:
data = data.drop(index=range(59))
Solution 2: Slice the DataFrame directly (simpler!)
A more concise way to keep only rows from index 59 onwards is to use pandas' row slicing:
# Keep all rows starting from index 59 data = data[59:] print(data)
This works because data[start:] returns every row from the start index to the end of the DataFrame, effectively removing the first 59 rows.
Solution 3: Drop rows with NaN in specific columns (more robust)
If you want to ensure any row with NaN in Real Lower Band or Real Upper Band is removed (not just the first 59 rows), use dropna() with the subset parameter:
# Remove rows where either of these columns has NaN data.dropna(subset=['Real Lower Band', 'Real Upper Band'], inplace=True) print(data)
This is a better approach if there might be other rows beyond index 58 that also contain NaN values in those columns.
内容的提问来源于stack exchange,提问作者Samar Pratap Singh

