【问题标题】:Problem with creating Pearson correlation coefficient in python在python中创建皮尔逊相关系数的问题
【发布时间】:2022-01-06 09:06:53
【问题描述】:

问题:根据第三列的值创建 Pearson 相关系数。

首先,我有一个包含 3 列的数据框。 A、B、C

上校。 A 和 B 包含 float64 类型,而在 C 中有对象。 我想得到 col A 和 B 的 Pearson 相关系数。

print(df['A'].corr(df['B'],method='pearson')) --> 这适用于整个列。

在下一步我挣扎。 C 列只有 2 个值。我们称它们为 c1 和 c2。 我现在想获得 c1 和 c2 的系数。 我试过了

print(df['A']&df['C']=='c1').corr((df['B']&df['C']=='c1'),method='pearson ')

对于 c2 也是一样的。 记录的错误是: TypeError: unsupported operand type(s) for &: 'float' and 'str' 如何在不拆分数据框的情况下获得两个系数?

提前致谢

【问题讨论】:

  • 为什么不创建一个包含所有系数的新列,然后使用df['new'][df['C']=='c1'] 选择您需要的行?

标签: python pearson-correlation pearson


【解决方案1】:

这应该可以实现您想要的:

print(df[df['C']=='c1']['A'].corr(df[df['C']=='c1']['B'],method='pearson'))

df[df['C']=='c1'] 检索数据框的子集,其中 C 列中的值为“c1”,然后您只需照常调用您想要的列。

【讨论】:

    猜你喜欢
    • 2011-08-20
    • 2021-08-29
    • 1970-01-01
    • 2011-09-10
    • 2014-04-11
    • 2014-11-13
    • 2011-09-13
    • 2012-11-19
    • 2013-10-12
    相关资源
    最近更新 更多