【问题标题】:Is there a simple way to convert a pandas series to a crosstab of ratios for values in the series?有没有一种简单的方法可以将熊猫系列转换为系列中值的比率交叉表?
【发布时间】:2021-11-12 13:32:14
【问题描述】:

输入

name    score
bob     2           
fred    4           
jim     1           
anne    5   

期望输出(分数比率:例如第 1 行中的 bob*fred = 2/4 等)

name    bob fred    jim anne
bob     1   0.5     2   0.4
fred    2   1       4   0.8
jim     0.5 0.2     1   0.2
anne    2.5 1.25    5   1

【问题讨论】:

    标签: python pandas matrix crosstab


    【解决方案1】:

    我们可以尝试外部np.divide.outer 来计算score 列的外部划分

    n, s = df.to_numpy().T
    pd.DataFrame(np.divide.outer(s, s), n, n)
    

          bob  fred  jim anne
    bob   1.0   0.5  2.0  0.4
    fred  2.0   1.0  4.0  0.8
    jim   0.5  0.25  1.0  0.2
    anne  2.5  1.25  5.0  1.0
    

    【讨论】:

      【解决方案2】:

      您可以使用df.corr 来计算自定义关系函数。请注意,对角线不是计算的,而是设置为1.0

      仅当数据框中的列超过两列时,才需要选择相关列。

      df[['name','score']].set_index('name').T.corr(lambda x,y: x/y)
      

      输出

      name  bob  fred  jim  anne
      name                      
      bob   1.0   0.5  2.0   0.4
      fred  0.5   1.0  4.0   0.8
      jim   2.0   4.0  1.0   0.2
      anne  0.4   0.8  0.2   1.0
      

      测试此解决方案的日期范围

      import pandas as pd
      import io
      
      t = '''
      name    score
      bob     2           
      fred    4           
      jim     1           
      anne    5   
      '''
      
      df = pd.read_csv(io.StringIO(t), sep='\s+')
      

      【讨论】:

      • 在关联方法中使用自定义可调用的好主意 +1
      • 这是个好主意。 +1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2019-03-10
      • 2019-10-12
      • 2019-03-27
      • 1970-01-01
      • 2020-09-27
      相关资源
      最近更新 更多