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

使用Seaborn时出现AttributeError:float对象无shape属性的问题

Fixing the AttributeError: 'float' object has no attribute 'shape' in Your Seaborn + Pandas Code

Let's break down why you're running into this error and fix your simulated tips dataset code properly.

What's Causing the Error?

The AttributeError pops up because Seaborn expects valid pandas Series or numpy arrays for plotting, but your DataFrame likely has columns with messed-up data types—like categorical columns such as time/sex/smoker accidentally getting converted to float.

Looking at your code snippet, the main issues are:

  • You only initialize the DataFrame for the first combination (t=0, s=0, sm=0) and never properly add data from other category combinations.
  • Using df.loc[i] in nested loops is error-prone; it’s easy to mess up row indexing or accidentally assign the wrong data type to columns.

Corrected Code to Simulate the Tips Dataset

Instead of clunky nested loops with manual row assignments, we can generate all your data in a clean, scalable way:

import numpy as np
import pandas as pd

# Define all possible values for categorical variables
time_options = ['day', 'night']
sex_options = ['female', 'male']
smoker_options = ['yes', 'no']

# Generate all combinations of the categorical variables
category_combinations = [(t, s, sm) for t in time_options 
                         for s in sex_options 
                         for sm in smoker_options]

# Collect all rows of data
all_data = []
for time_val, sex_val, smoker_val in category_combinations:
    # Generate 10 random total_bill values (range 0-10)
    total_bills = np.random.rand(10) * 10
    # Append each bill with its corresponding category labels
    for bill in total_bills:
        all_data.append([bill, time_val, sex_val, smoker_val])

# Create the DataFrame in one go (far less error-prone!)
df = pd.DataFrame(all_data, columns=["total_bill", "time", "sex", "smoker"])

# Verify data types to ensure no unexpected floats in categorical columns
print(df.dtypes)

Why This Works

  • We generate all category combinations upfront, then build a list of rows to avoid incremental DataFrame modifications (which are slow and easy to botch).
  • Categorical columns (time, sex, smoker) are explicitly stored as strings, so Seaborn can correctly interpret them as categorical data without hitting type errors.
  • You can easily adjust the number of samples per combination (just change 10 to any number) without rewriting the entire loop logic.

Quick Fix If You Still Run Into Issues

If you ever see this error again, first check your DataFrame's data types with df.dtypes. If a categorical column shows up as float, convert it back to string with:

df['time'] = df['time'].astype(str)
df['sex'] = df['sex'].astype(str)
df['smoker'] = df['smoker'].astype(str)

内容的提问来源于stack exchange,提问作者lanadaquenada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:55:16