【问题标题】:I want to calculate the percentage but all i am getting is the sum in pandas data frame我想计算百分比,但我得到的只是熊猫数据框中的总和
【发布时间】:2020-04-30 17:46:48
【问题描述】:

我想计算百分比,但我得到的只是总和。请帮我获取单元格中的百分比值,而不是 pandas 数据框中 python 中的计数。

代码:

ds_data = data[(data.JobTitle == 'Data Analyst') | (data.JobTitle == 'Data Engineer')  | (data.JobTitle == 'Data Scientist')]
agg_func = {'Education':{'Masters': lambda x: \
    sum(i == 'Masters' for i in x),
    'Bachelor': lambda x : sum(i == 'Bachelors (4 years)' for i in x),
    'None': lambda x : sum(i == 'None (no degree completed)' for i in x),
    'Doctorates': lambda x : sum(i == 'Doctorate/PhD' for i in x),
    'Associates': lambda x : sum(i == 'Associates (2 years)' for i in x)}}
function = ds_data.groupby(['JobTitle']).agg(agg_func).reset_index()
function.columns = function.columns.droplevel(0)
function

【问题讨论】:

  • 如果您可以将输入和预期输出与解释一起提供,您将更有可能快速获得解决方案
  • JobTilte 硕士 学士 博士/博士 无 0 数据分析师 156 381 4 71 91 1 数据工程师 48 145 2 23 52 2 数据科学家 19 13 10 2 4
  • JobTilte 硕士 学士 博士/博士 无 0 数据分析师 156 381 4 71 91 1 数据工程师 48 145 2 23 52 2 数据科学家 19 13 10 2 现在我想要 (156 / (156+381+ 4+71+91) )* 100 对每个单元格条目类似。

标签: python database pandas dataframe jupyter-notebook


【解决方案1】:

如果我们使用 dict 重命名(不推荐使用),可以计算总行数,然后在 lambda 函数中使用它来获取百分比:

ds_data = data[(data.JobTitle == 'Data Analyst') | (data.JobTitle == 'Data Engineer') 
               | (data.JobTitle == 'Data Scientist')]
ds_data_nrows = ds_data.shape[0]
agg_func = {'Education':{'Masters': lambda x: \
    (sum(i == 'Masters' for i in x) / ds_data_nrows) * 100,
    'Bachelor': lambda x : (sum(i == 'Bachelors (4 years)' for i in x) / ds_data_nrows) * 100,
    'None': lambda x : (sum(i == 'None (no degree completed)' for i in x) / ds_data_nrows) * 100,
    'Doctorates': lambda x : (sum(i == 'Doctorate/PhD' for i in x) / ds_data_nrows) * 100,
    'Associates': lambda x : (sum(i == 'Associates (2 years)' for i in x) / ds_data_nrows) * 100}}
function = ds_data.groupby(['JobTitle']).agg(agg_func).reset_index()
function.columns = function.columns.droplevel(0)
function

【讨论】:

    【解决方案2】:

    我冒昧地定义了一个包含数学的函数,因为它比复制/粘贴代码更简洁。

    为了得到百分比,你需要除以总数,或者列表的长度。

    def calc_percentage(data, degree):
      return (sum(i == degree for i in x) / len(x)) * 100
    
    agg_func = {
        'Education': {
            'Masters': lambda x : calc_percentage(x, 'Masters'),
            'Bachelor': lambda x : calc_percentage(x, 'Bachelors (4 years)'),
            'None': lambda x : calc_percentage(x, 'None (no degree completed)'),
            'Doctorates': lambda x : calc_percentage(x, 'Doctorate/PhD'),
            'Associates': lambda x : calc_percentage(x, 'Associates (2 years)')
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-07
      • 2020-04-17
      • 1970-01-01
      • 2020-09-21
      • 2021-10-17
      • 2022-08-06
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多