Compute percentage for each row in pandas dataframe

前端 未结 2 1070
梦如初夏
梦如初夏 2021-01-14 06:38
                  country_name  country_code  val_code  \\
   United States of America           231                     1   
   United States of America           2         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 06:55

    You can get the percentages of each column using a lambda function as follows:

    >>> df.iloc[:, 3:].apply(lambda x: x / x.sum())
           y191      y192      y193      y194      y195
    0  0.527231  0.508411  0.490517  0.500544  0.480236
    1  0.013305  0.014088  0.013463  0.013631  0.013713
    2  0.316116  0.324405  0.341373  0.319164  0.323259
    3  0.002006  0.002263  0.002678  0.003206  0.002872
    4  0.141342  0.150833  0.151969  0.163455  0.179920
    

    Your example does not have any duplicate values for val_code, so I'm unsure how you want your data to appear (i.e. show percent of total in column vs. total for each vval_code group.)

提交回复
热议问题