Spyder中双向重复测量ANOVA报错:TypeError: list indices must be integers or slices, not numpy.float64
Hey there! Let's work through this error you're hitting while trying to run a 2×2 repeated measures ANOVA in Python with statsmodels. That TypeError: list indices must be integers or slices, not numpy.float64 usually pops up when you're trying to use a floating-point number to index a list (or pandas DataFrame/Series) — which doesn't work, since indices need to be whole numbers or slices.
Here are the most common fixes tailored to your repeated measures ANOVA scenario:
1. Fix your MATCH variable type
First, check what data type your MATCH column is. If it's stored as a float64 (even if the values are whole numbers like 0.0 or 1.0), statsmodels might treat it as a continuous variable instead of a categorical factor — leading to indexing errors under the hood.
Convert it to an integer or categorical type first:
import pandas as pd # Load your data (adjust the path/load method to match your data) df = pd.read_csv("your_data_file.csv") # Check current data types print(df.dtypes) # Option 1: Convert MATCH to integer df["MATCH"] = df["MATCH"].astype(int) # Option 2: Convert MATCH to categorical type (better for ANOVA factors) df["MATCH"] = df["MATCH"].astype("category") # Verify the change print(df.dtypes)
2. Double-check your AnovaRM setup
When initializing the AnovaRM model, make sure:
- The
subjectcolumn uses integer/string identifiers (not floats) for each participant - The
withinparameter points to your categorical independent variable (now fixed to integer/category type)
Here's a sample corrected setup for your 2×2 repeated measures ANOVA:
from statsmodels.stats.anova import AnovaRM # Initialize and fit the model model = AnovaRM( data=df, depvar="your_dependent_variable_name", # Replace with your DV column subject="participant_id", # Replace with your subject ID column within=["MATCH"] # Your fixed categorical IV ) results = model.fit() # Print the ANOVA results print(results)
3. Debug your "view data" step
If the error happens when you're trying to inspect your data (e.g., slicing/subsetting), make sure you're using integer indices or column names, not floats. For example:
- ❌ Wrong:
df[1.0]ordf.iloc[0.0:5.0] - ✅ Correct:
df.iloc[0:5](slice) ordf["MATCH"](column name)
Run print(df.head()) to quickly inspect the first few rows and confirm your data is structured correctly (long format is required for AnovaRM, not wide format like SPSS sometimes uses).
内容的提问来源于stack exchange,提问作者ticl

