【问题标题】:Getting A Correlation Column Based on Two Columns with A List Value基于具有列表值的两列获取相关列
【发布时间】:2021-11-14 08:59:21
【问题描述】:

我有以下数据集:

df = pd.DataFrame({'A': [[10, 11, 12], [13, 14, 15]], 
                   'B': [[17, 18, 12], [21, 22, 13]]})
df

          A               B
0   [10, 11, 12]    [17, 18, 12]
1   [13, 14, 15]    [21, 22, 13]

现在我想使用scipy.stats.pearsonr 方法基于AB 列创建一个新列Correlation。我正在尝试这个:

# Creating a function for correlation
def correlation(row):
    correlation, p_value = stats.pearsonr(row['A'], row['B'])
    return correlation

# Applying the function
df['Correlation'] = df.apply(correlation, axis = 1)
df

          A               B         Correlation
0   [10, 11, 12]    [17, 18, 12]    -0.777714
1   [13, 14, 15]    [21, 22, 13]    -0.810885

如果我的列太多,上面的脚本就不是理想的了。我在想是否可以直接在lambda 中使用stats.pearsonr 来获得相同的结果?

任何建议将不胜感激。谢谢!

【问题讨论】:

  • 你想要df.apply(lambda row: stats.pearsonr(row['A'], row['B'])[0], axis = 1)如果我有太多列,上面的脚本就不是理想的是什么意思?
  • @Ben.T:是的,这就是切片[0]。我完全忘了。谢谢你:)

标签: pandas dataframe scipy statistics


【解决方案1】:

我会推荐使用 zip 和 for 循环

df['out'] = [stats.pearsonr(x, y)[0] for x, y in zip(df.A, df.B)]
df
Out[163]: 
              A             B       out
0  [10, 11, 12]  [17, 18, 12] -0.777714
1  [13, 14, 15]  [21, 22, 13] -0.810885

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2022-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多