开发者社区> 问答> 正文

在数据框中查找通讯记录以进行计算

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

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

例如,艾迪生和卡登的重量都是0.杰克和诺亚没有重量。我想将它们排除在外进行计算。

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

如何仅包含具有非零值的人员进行计算?

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)

展开
收起
一码平川MACHEL 2019-01-18 11:25:29 1534 0
1 条回答
写回答
取消 提交回答
  • 掩盖并取非零值和共同指数:

    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'])


    使用map了添加新列,删除0的行boolean indexing和持续适用于相同的数据帧的解决方案:

    df_wt['Score'] = df_wt['Name'].map(df_sc.set_index('Name')['Score'])

    df_wt = df_wt[df_wt['Weight'].ne(0)]
    print (df_wt)

        Name  Weight  Score

    0 Abigail 10 360
    2 Aiden 12 345
    3 Amelia 20 601
    4 Aria 25 604
    5 Ava 10 313
    7 Charlotte 18 531
    8 Chloe 16 507
    9 Elijah 13 473

    print (df_wt.Weight.corr(df_wt.Score))
    0.923425144491911

    2019-07-17 23:25:53
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
用计算和数据去改变整个世界 立即下载
4个迭代,从批量交...1573957773.pdf 立即下载
RowKey与索引设计:技巧与案例分析 立即下载