我有一个数据框,我想将“管理器”(列标题)下的每个“名称”(列标题)的所有“小时数”(列标题)汇总为“总和”。然后,我想删除所有重复项,然后再根据总小时数对数据框进行排序,并逐行打印出来。但是我一直在逐行打印出Manager的重复项吗?
|---------------------|------------------|---------------------|------------------|
| Department | Name | Manager | Hours |
|---------------------|------------------|---------------------|------------------|
| Department name | person Name | Manager Name |no of hours |
|---------------------|------------------|---------------------|------------------|
def total_group(csv_file):
df = pd.read_csv(csv_file)
df['Total Hours'] = df.groupby(['Manager'])['Hours'].transform('sum')
new_df = df.drop_duplicates(subset=['Department', 'name', 'Manager']).sort_values('Total Hours')
for index, row in new_df.iterrows():
manager_value = row['Manager']
total_hours = row['Total Hours']
print("manager: {}, has: {} Total hours".format(manager_value, total_hours))
print(total_group(csv_file))
数据框打印
df1 = df['Total Hours'] = df.groupby(['Direct Manager'])['Labor Hours'].transform('sum')
print(df1)
结果
0 450.0
1 450.0
2 450.0
3 450.0
4 450.0
...
43929 320.5
43930 320.5
43931 320.5
43932 320.5
43933 320.5
Name: Hours, Length: 43934, dtype: float64
新数据框打印:
new_df = df.drop_duplicates(subset=['Department', 'Direct Manager']).sort_values('Total Hours')
print(new_df)
结果:
Department Name Hours Total Hours
9554 Europe Dri, Bas ... 8.0 72.000000
34498 Product & Design Sun, Sunn ... 5.0 81.000000
19140 Product & Design Oers, Len ... 8.0 122.000000
我想要的是这样的数据框:
Department Manager Total Hours
9554 Europe Last, First ... 72.000000
34498 Product Last, first ... 81.000000
19140 Design Last, First ... 122.000000
答案 0 :(得分:1)
您要尝试这个吗
df.groupby('Manager').agg({'Hours':['sum','count']}).sort_values(('Hours','sum'), ascending=False)