Combining multiple list entries into a single entry

时间:2016-04-04 18:45:18

标签: list sorting python-3.x

I have a list object which contains multiple entries, each which contains the following: "park name", "visitors", "maintenance Hours", "events"

The list can contain multiple entries for the same park name, and different totals for visitors, maintenance hours, events, etc. I would like to iterate through the list object and create a new list with 1 entry for each park name, and the sum of each entry for visitors, maintenance, etc.

Current List Example:
park1, 200, 25, 4
park1, 24, 2, 10
park2, 12, 45, 2
park2, 100, 23, 5
park3, 2, 10, 5

Desired List after sorting:
park1, 224, 27, 14
park2, 112, 68, 7
etc...

Thanks!

1 个答案:

答案 0 :(得分:1)

这可以通过熊猫轻松完成。从列表数据中创建一个pandas DataFrame变量,然后让变量foo被分配给它。

print(foo) # print out the following.

  ParkName  Visitors  MaintenanceHours  Events
0    park1       200                25       4
1    park1        24                 2      10
2    park2        12                45       2
3    park2       100                23       5
4    park3         2                 5       5

bar = foo.groupby('ParkName').sum()
print(bar)

          Visitors  MaintenanceHours  Events
ParkName                                    
park1          224                27      14
park2          112                68       7
park3            2                 5       5