【问题标题】:How to calculate between the rows in pandas Dataframe?如何在 pandas Dataframe 中的行之间计算?
【发布时间】:2021-04-16 17:34:09
【问题描述】:

我想计算我的新值占原始值的百分比。 我想收到的是我的 Pandas DataFrame 中的新列。

我的 DataFrame 如下所示:

     Feature    Precision   Accuracy    Recall  Specificity F1 score
0   original    0.949367    0.911765    0.9375  0.818182    0.943396
1   new_feat1   0.949367    0.911765    0.9375  0.818182    0.943396
2   new_feat2   0.950617    0.931373    0.9625  0.818182    0.956522

期望的结果如下所示:

     Feature    Precision   Accuracy    Recall  Specificity F1 score Precision% Accuracy%   Recall% Specificity%    F1 score%
0   original    0.949367    0.911765    0.9375  0.818182    0.943396 100        100         100     100             100
1   new_feat1   0.949367    0.911765    0.9375  0.818182    0.943396 xxxxxx   xxxxxx       xxxxx    xxxxxx       xxxxxx
2   new_feat2   0.950617    0.931373    0.9625  0.818182    0.956522

计算so应该是这样的:

对于 new_feat1:

  • precision% = new_feat1_precision * 100 / original_precision
  • accuracy% = new_feat1_accuracy * 100 / original_accuracy
  • 等等

或者如果它更容易,因为它建议 Dataframe 可以有这种格式

            original    new_feat1   new_feat2
Precision   0.949367    0.950617    0.95122
Accuracy    0.911765    0.931373    0.941176    
Recall      0.9375      0.9625      0.975   
Specificity 0.818182    0.818182    0.818182    
F1 score    0.943396    0.956522    0.962963    

那么想要的输出是:

            original    new_feat1   new_feat2
Precision   0.949367    0.950617    0.95122
Accuracy    0.911765    0.931373    0.941176    
Recall      0.9375      0.9625      0.975   
Specificity 0.818182    0.818182    0.818182    
F1 score    0.943396    0.956522    0.962963
%Accuracy   100         xxxx        xxxx 

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    最简单的方法可能是转置您的数据框:

    df1_transposed = df1.T
    

    然后,一旦你像往常一样做你的事情,如果你愿意,你就可以转回去

    df1 = df1_transposed.T
    

    【讨论】:

      【解决方案2】:

      diviloc[0]除以第一行,用add_suffix为列名添加后缀,然后用join加入原始DataFrame:

      df.join(
          df.select_dtypes(float).div(
              df.select_dtypes(float).iloc[0]).add_suffix(' %'))
      

      输出:

           Feature  Precision  Accuracy  Recall  Specificity  F1_score  Precision %  \
      0  original   0.95       0.91      0.94    0.82         0.94      1.0           
      1  new_feat1  0.95       0.91      0.94    0.82         0.94      1.0           
      2  new_feat2  0.95       0.93      0.96    0.82         0.96      1.0           
      
         Accuracy %  Recall %  Specificity %  F1_score %  
      0  1.00        1.00      1.0            1.00        
      1  1.00        1.00      1.0            1.00        
      2  1.02        1.03      1.0            1.01        
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-02
        • 1970-01-01
        • 2020-05-17
        • 2021-08-05
        • 1970-01-01
        • 2013-12-16
        • 2021-07-26
        • 2016-04-04
        相关资源
        最近更新 更多