首页 > 解决方案 > 类型错误:使用 scipy 进行 shapiro 测试时,“float”和“str”实例之间不支持“<”

问题描述

我正在尝试根据列“代码”为熊猫数据框中的每一列运行 shapiro 测试。

这就是我的 df 的样子:

>>>name  code   2020-10-22   2020-10-23   2020-10-24 ...
0  a      1      0.05423      0.1254      0.1432
1  b      1      0.57289      0.0092      0.2314
2  c      2      0.1205       0.0072      0.12
3  d      3      0.3234       0.231       0.231
...

我有 80 行,有 6 个不同的代码(1、2、3、4、5、6)。

我想对每一列,对于每个代码运行夏皮罗测试,例如,取 2020-10-22 的列,只取处理号为的行。1 并对它们运行 shapiro 测试。

我尝试使用以下循环来做到这一点:

shapiros=[]

for variable in df.columns[2:]:
    tmp=df[['code',variable]]
    tmp=tmp[tmp[variable].notnull()]
    
    for i in tmp.code.unique().tolist():
        shapiro_test = stats.shapiro(tmp[tmp['code'] == i])
        shapiros.append(shapiro_test)

但后来我得到错误:

---> 13         shapiro_test = stats.shapiro(tmp[tmp['code'] == i])

TypeError:“float”和“str”的实例之间不支持“<”

我看到这个错误可能是由于有空值而发生的,但我已经使用 notnull() 摆脱了这个错误。我通过在每次迭代中打印“tmp”的长度来检查 notnull 的工作,它确实发生了变化。

此外,似乎两者的类型都是相同的对象:

for variable in df.columns[2:]:
    tmp=df[['code',variable]]
    print(tmp.dtypes)
    tmp=tmp[tmp[variable].notnull()]
    
    for i in tmp.code.unique().tolist():
        print(type(i))


>>>code           object
2020-10-22    float64
dtype: object
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
... 

(它整天打印相同)。

可能是什么问题?如何计算每个代码每列的 shapiro?

标签: pythonpandasfor-loopscipyscipy.stats

解决方案


您必须将列 Code 转换为 float/int 才能比较,根据您的代码,它当前是 str。尝试做:

df['code'] = df['code'].astype(float)

推荐阅读