为何触发too many indexers错误?用.iloc替代.ix遇问题求助
Hey there! Let's break down the issues in your code one by one to fix that too many indexers error and get your pairplot up and running.
First: Fix the iloc Syntax (Root Cause of the Error)
The too many indexers error happens because you're using iloc incorrectly. iloc requires separate row and column selections separated by a comma, like iloc[row_selection, column_selection]. Your original code mashed both into one selection, which Pandas can't interpret.
Instead of:
car.iloc[:[1,3,4,6]]
Use this to select all rows and the 1st, 3rd, 4th, 6th columns (remember iloc uses 0-based indexing):
car.iloc[:, [1,3,4,6]]
The : before the comma means "select all rows", and the list after targets your desired columns.
Second: Fix Typos and Case Sensitivity
Python and Pandas are strict about these:
pd.series→ should bepd.Series(capital S)dtypre→ should bedtype(spelling error)
Third: Ensure Length Matching for the group Column
Your car_t = car.iloc[:9].values only grabs the first 9 rows of your original DataFrame. If cars_df has more than 9 rows, this will throw a "value length mismatch" error. Make sure car_t has the same number of rows as cars_df. For example, if you want to group all rows based on a column in car, use something like:
# Replace 0 with the index of the column you want to use for grouping car_t = car.iloc[:, 0].values
Corrected Full Code
Here's the cleaned-up version with all fixes:
import pandas as pd import seaborn as sb # Fix iloc syntax to separate rows/columns cars_df = pd.DataFrame(car.iloc[:, [1,3,4,6]].values, columns=['mpg', 'disp', 'hp', 'wt']) # Fixed 'dip' to 'disp' (likely typo) # Ensure car_t matches the length of cars_df # Example: Use the first column of car for grouping car_t = car.iloc[:, 0].values # Fix Series case and dtype spelling cars_df['group'] = pd.Series(car_t, dtype='category') # Optional: Add hue to color points by group sb.pairplot(cars_df, hue='group')
Quick Recap
- Always use
iloc[row, col]for positional indexing—never mash row/col selections into one argument. - Double-check case sensitivity and spelling for Pandas methods/parameters.
- Make sure the data you assign to a new column matches the parent DataFrame's row count.
内容的提问来源于stack exchange,提问作者Josh Bennett

