AttributeError: 'float' object has no attribute 'shape' when using seaborn

AttributeError: 'float' object has no attribute 'shape' when using seaborn

我创建了一个随机数据帧来模拟数据集 tips 来自 seaborn:

import numpy as np
import pandas as pd

time = ['day','night']
sex = ['female','male']
smoker = ['yes','no']
for t in range(0,len(time)):
    for s in range(0,len(sex)):
        for sm in range(0,len(smoker)):
            randomarray = np.random.rand(10)*10
            if t == 0 and s == 0 and sm == 0:
                df = pd.DataFrame(index=np.arange(0,len(randomarray)),columns=["total_bill","time","sex","smoker"])
                L = 0
                for i in range(0,len(randomarray)):
                    df.loc[i] = [randomarray[i], time[t], sex[s], smoker[sm]]
                    L = L + 1
            else:
                for i in range(0,len(randomarray)):
                    df.loc[i+L] = [randomarray[i], time[t], sex[s], smoker[sm]]
                    L = L + 1

我的数据帧 df 对于每一列,与来自 seaborn 数据集的数据帧 tips 具有相同类型的 class :

tips = sns.load_dataset("tips")
type(tips["total_bill"][0])
type(tips["time"][0])

numpy.float64

str

其他列依此类推。与我的数据框相同:

type(df["total_bill"][0])
type(tips["time"][0])

numpy.float64

str

但是,当我尝试在 documentation:

之后使用 seaborn 的 violinplotfactorplot
g = sns.factorplot(x="sex", y="total_bill", hue="smoker", col="time",  data=df, kind="violin", split=True, size=4, aspect=.7);

如果我使用 dataFrame tips,我没有问题,但是当我使用我的 dataFrame 时,我得到:

AttributeError: 'float' object has no attribute 'shape'

我想这是我将数组传递到 dataFrame 的方式的问题,但我找不到问题所在,因为我在互联网上发现的每个具有相同 AttributeError 的问题都说这是因为它不是class 类型相同,如上所示,我的数据帧与 seaborn 文档中的 class 类型相同。

有什么建议吗?

这是一种相当不寻常的创建数据框的方式。生成的数据框也有一些非常奇怪的属性,例如它的长度为 50,但最后一个索引为 88。我不打算调试这些嵌套循环。相反,我会建议从一些 numpy 数组创建数据框,例如喜欢

import numpy as np
import pandas as pd

time = ['day','night']
sex = ['female','male']
smoker = ['yes','no']

data = np.repeat(np.stack(np.meshgrid(time, sex, smoker), -1).reshape(-1,3), 10, axis=0)
df = pd.DataFrame(data, columns=["time","sex","smoker"])
df["total_bill"] = np.random.rand(len(df))*10

然后绘图也可以正常工作:

g = sns.factorplot(x="sex", y="total_bill", hue="smoker", col="time",  data=df, 
                   kind="violin", size=4, aspect=.7)

我遇到了同样的问题并试图找到解决方案但没有看到我正在寻找的答案。所以我想在这里提供一个答案可能会帮助像我这样的人。

这里的问题是df.total_bill的类型是object而不是float.

所以解决方案是在将数据帧传递给 seaborn 之前将其更改为浮动:

df.total_bill = df.total_bill.astype(float)

我的代码中有一个不同的问题产生了同样的错误:

'str' object has no attribute 'get'

对我来说,我在 seaborn 语法中有 ...data='df'...,但是 df 是一个对象,不应该用引号引起来。删除引号后,我的程序就完美运行了。我犯了错误,就像其他人可能犯的那样,因为 x= 和 y= 参数在引号中(对于数据框中的列)

将变量的数据类型从对象转换为 float/int。