gpt4 book ai didi

python - 在数据框中查找通讯员进行计算

转载 作者:行者123 更新时间:2023-11-30 22:00:52 24 4
gpt4 key购买 nike

如下两个数据框,我想计算相关系数。

当两列都使用实际值完成时,它可以正常工作。但如果不是,则在计算相关系数时取零值。

例如,Addison 和 Caden 的权重为 0。Jack 和 Noah 没有权重。我想在计算中排除它们。

(在尝试中,似乎只考虑相同的长度,即 Jack 和 Noah 被自动排除 - 是吗?)

如何只包含非零值的人进行计算?

谢谢。

import pandas as pd

Weight = {'Name': ["Abigail","Addison","Aiden","Amelia","Aria","Ava","Caden","Charlotte","Chloe","Elijah"],
'Weight': [10, 0, 12, 20, 25, 10, 0, 18, 16, 13]}

df_wt = pd.DataFrame(Weight)

Score = {'Name': ["Abigail","Addison","Aiden","Amelia","Aria","Ava","Caden","Charlotte","Chloe","Elijah", "Jack", "Noah"],
'Score': [360, 476, 345, 601, 604, 313, 539, 531, 507, 473, 450, 470]}

df_sc = pd.DataFrame(Score)

print df_wt.Weight.corr(df_sc.Score)

最佳答案

屏蔽并取非零值和公共(public)索引:

df_wt.set_index('Name', inplace=True)
df_sc.set_index('Name', inplace=True)

mask = df_wt['Weight'].ne(0)
common_index = df_wt.loc[mask, :].index
df_wt.loc[common_index, 'Weight'].corr(df_sc.loc[common_index, 'Score'])

0.923425144491911

如果两个数据帧都包含零,则:

mask1 = df_wt['Weight'].ne(0)
mask2 = df_sc['Score'].ne(0)
common_index = df_wt.loc[mask1, :].index.intersection(df_sc.loc[mask2, :].index)
df_wt.loc[common_index, 'Weight'].corr(df_sc.loc[common_index, 'Score'])

关于python - 在数据框中查找通讯员进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54211290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com