Python如何实现数据的累加与统计
这篇文章主要讲解了Python如何实现数据的累加与统计,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
问题
你需要处理一个很大的数据集并需要计算数据总和或其他统计量。
解决方案
对于任何涉及到统计、时间序列以及其他相关技术的数据分析问题,都可以考虑使用 Pandas库 。
为了让你先体验下,下面是一个使用Pandas来分析芝加哥城市的 老鼠和啮齿类动物数据库 的例子。 在我写这篇文章的时候,这个数据库是一个拥有大概74,000行数据的CSV文件。
>>> import pandas>>> # Read a CSV file, skipping last line>>> rats = pandas.read_csv('rats.csv', skip_footer=1)>>> rats<class 'pandas.core.frame.DataFrame'>Int64Index: 74055 entries, 0 to 74054Data columns:Creation Date 74055 non-null valuesStatus 74055 non-null valuesCompletion Date 72154 non-null valuesService Request Number 74055 non-null valuesType of Service Request 74055 non-null valuesNumber of Premises Baited 65804 non-null valuesNumber of Premises with Garbage 65600 non-null valuesNumber of Premises with Rats 65752 non-null valuesCurrent Activity 66041 non-null valuesMost Recent Action 66023 non-null valuesStreet Address 74055 non-null valuesZIP Code 73584 non-null valuesX Coordinate 74043 non-null valuesY Coordinate 74043 non-null valuesWard 74044 non-null valuesPolice District 74044 non-null valuesCommunity Area 74044 non-null valuesLatitude 74043 non-null valuesLongitude 74043 non-null valuesLocation 74043 non-null valuesdtypes: float64(11), object(9)>>> # Investigate range of values for a certain field>>> rats['Current Activity'].unique()array([nan, Dispatch Crew, Request Sanitation Inspector], dtype=object)>>> # Filter the data>>> crew_dispatched = rats[rats['Current Activity'] == 'Dispatch Crew']>>> len(crew_dispatched)65676>>>>>> # Find 10 most rat-infested ZIP codes in Chicago>>> crew_dispatched['ZIP Code'].value_counts()[:10]60647 383760618 353060614 328460629 325160636 280160657 246560641 223860609 220660651 215260632 2071>>>>>> # Group by completion date>>> dates = crew_dispatched.groupby('Completion Date')<pandas.core.groupby.DataFrameGroupBy object at 0x10d0a2a10>>>> len(dates)472>>>>>> # Determine counts on each day>>> date_counts = dates.size()>>> date_counts[0:10]Completion Date01/03/2011 401/03/2012 12501/04/2011 5401/04/2012 3801/05/2011 7801/05/2012 10001/06/2011 10001/06/2012 5801/07/2011 101/09/2012 12>>>>>> # Sort the counts>>> date_counts.sort()>>> date_counts[-10:]Completion Date10/12/2012 31310/21/2011 31409/20/2011 31610/26/2011 31902/22/2011 32510/26/2012 33303/17/2011 33610/13/2011 37810/14/2011 39110/07/2011 457>>>
嗯,看样子2011年10月7日对老鼠们来说是个很忙碌的日子啊!^_^
讨论
Pandas是一个拥有很多特性的大型函数库,我在这里不可能介绍完。 但是只要你需要去分析大型数据集合、对数据分组、计算各种统计量或其他类似任务的话,这个函数库真的值得你去看一看。
看完上述内容,是不是对Python如何实现数据的累加与统计有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。