如何总结选择性字典值

时间:2017-03-07 10:13:29

标签: python-3.x

我想过滤特定部门的工资和总结,我已经做了上半年,但是加上那些工资,可以通过看下面的代码来建议任何一个....

/usr/local/lib

3 个答案:

答案 0 :(得分:0)

我建议使用pandas(http://pandas.pydata.org/

import pandas as pd
# Creating the dataframe
dataset = pd.DataFrame(employ)
print (dataset)
#Out[3]: 
#    Age  Department  Salary    name
#0    39       Sales      20   Kumar
#1    53     Finance      35  Suresh
#2    28          QC      10    Babu
#3    34  Production      15  Satish
#4    45  Management      23     Dev
#5    46   Marketing      25    Rani
#6    24  Production       5    Devi
#7    26  Production      12  Sarath
#8    25  Production       8    Senu
#9    37  Management      20  Kumari
#10   52   Marketing      30  Sanjay

# Production Salary
dataset1 = dataset[dataset['Department'] == 'Production'].Salary
print (dataset1)
#Out[6]: 
#3    15
#6     5
#7    12
#8     8
#Name: Salary, dtype: int64

# Sum Salaries
dataset2 = dataset[dataset['Department'] == 'Production'].Salary.sum()
print (dataset2)
# 40 

上面的代码看起来并不那么漂亮,但是pandas非常强大。 以下是按部门划分总薪水的方法:

dataset3 = dataset.groupby('Department').sum()['Salary']
print (dataset3)
#Out[8]:
#Department
#Finance       35
#Management    43
#Marketing     55
#Production    40
#QC            10
#Sales         20
#Name: Salary, dtype: int64

答案 1 :(得分:0)

如果你不想使用熊猫,试试这个,

from collections import defaultdict
salary = defaultdict(int)
# for specific departments
required_departments = ["Production"]
for i in employ:
    if i["Department"] in required_departments:
        salary[i["Department"]] += i["Salary"]
print(salary)
# for all departments
salary = defaultdict(int)
for i in employ:
    salary[i["Department"]] += i["Salary"]

print(salary)

答案 2 :(得分:0)

如果你想要一个单线

result = sum(d.get("Salary", 0) for d in employ if d.get("Department") == "Production")

也可以总和为多个。

departments = {"Production", "Marketing"}
result = sum(d.get("Salary", 0) for d in employ if d.get("Department") in departments)