You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pandas中列出指定单列与其余所有列的最高相关系数对

解决方案

你可以通过以下两种方式修改代码实现需求,两种方式都只会返回指定单列和其余所有列的相关系数,不会生成其他列之间的相关配对结果:

方式1:基于原有代码逻辑修改(适合小数据集)

直接从生成的相关矩阵中提取目标列的结果即可,示例代码如下:

import pandas as pd

d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [7,3]}
df = pd.DataFrame(data=d)

# 指定需要计算相关系数的目标列
target_col = "col1"
# 提取目标列与所有列的相关系数,再删除目标列自身的相关结果
result = df.corr()[target_col].drop(target_col)
# 如果需要排序可追加.sort_values()
print(result)

方式2:用corrwith方法(更适合大数据集,算力消耗更低)

不需要计算全量相关矩阵,直接计算目标列和其余列的相关系数,性能更好:

import pandas as pd

d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [7,3]}
df = pd.DataFrame(data=d)

target_col = "col1"
result = df.corrwith(df[target_col]).drop(target_col)
print(result)

两种方式的输出结果一致,以示例数据为例输出如下:

col2    1.0
col3   -1.0
dtype: float64

内容的提问来源于stack exchange,提问作者Undertaker2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:06:05