【问题标题】:scipy.stats.pearsonr complaining about operand type -: 'tuple' and 'float'scipy.stats.pearsonr 抱怨操作数类型 -: 'tuple' 和 'float'
【发布时间】:2020-02-29 20:41:03
【问题描述】:

我正在尝试计算 numpy 二维数组的两列之间的相关性。数组看起来像:


a = np.array([[5.1, 3.5, 1.4, 0.2],
        [4.9, 3. , 1.4, 0.2],
        [4.7, 3.2, 1.3, 0.2],
        [4.6, 3.1, 1.5, 0.2]])

所以第 1 列和第 3 列之间的相关性计算为:


import scipy
x, y = scipy.stats.pearsonr(a[:,0], a[:,2])

但是,它抱怨:


unsupported operand type(s) for -: 'tuple' and 'float'

这意味着,例如,下面的事情正在发生:


print((0.1,0.2) - 0.3)
TypeError: unsupported operand type(s) for -: 'tuple' and 'float'

更新: 完整代码:


import pandas as pd
from scipy import stats
import numpy as np
a = pd.read_csv("src/iris.csv").drop('species', axis=1).values
def lengths():
    x, y = stats.pearsonr(a[:,0],a[:,2])
    return x, y
print(lengths())

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    您的数据似乎存在问题。将您的代码与来自vega-datasets 的另一个 Iris 数据帧一起使用,我在计算相关性方面没有问题:

    import pandas as pd
    from scipy import stats
    import numpy as np
    import vega_datasets as vd
    
    a = vd.data.iris().drop('species', axis=1).values
    def lengths():
        x, y = stats.pearsonr(a[:,0],a[:,2])
        return x, y
    print(lengths())
    

    返回

    (0.8717537758865832, 1.0386674194497525e-47)
    

    【讨论】:

    • 是的,加载数据时出现问题,现在可以正常工作了
    猜你喜欢
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2020-07-05
    相关资源
    最近更新 更多