pandas :数事 [英] pandas: count things

查看:76
本文介绍了 pandas :数事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面,male_trips是一个大熊猫数据帧,而station是一个小熊猫数据帧.对于每个车站ID,我想知道发生了多少次男性旅行.下面的工作可以完成,但是需要很长时间:

In the following, male_trips is a big pandas data frame and stations is a small pandas data frame. For each station id I'd like to know how many male trips took place. The following does the job, but takes a long time:

mc = [ sum( male_trips['start_station_id'] == id ) for id in stations['id'] ]

我应该怎么做呢?

更新!因此,有两种主要方法:groupby(),后跟size(),以及更简单的.value_counts().我做了一个快速的timeit,而groupby的方法大获全胜!这是代码:

Update! So there were two main approaches: groupby() followed by size(), and the simpler .value_counts(). I did a quick timeit, and the groupby approach wins by quite a large margin! Here is the code:

from timeit import Timer
setup = "import pandas; male_trips=pandas.load('maletrips')"
a  = "male_trips.start_station_id.value_counts()"
b = "male_trips.groupby('start_station_id').size()"
Timer(a,setup).timeit(100)
Timer(b,setup).timeit(100)

这是结果:

In [4]: Timer(a,setup).timeit(100) # <- this is value_counts
Out[4]: 9.709594964981079

In [5]: Timer(b,setup).timeit(100) # <- this is groupby / size
Out[5]: 1.5574288368225098

请注意,以这种速度,用于探索数据的 typ value_counts的速度稍快,而且记忆力也较差!

Note that, at this speed, for exploring data typing value_counts is marginally quicker and less remembering!

推荐答案

我很喜欢Vishal,但不是使用size()来使用sum()来获取分配给每组"start_station_id"的行数'.所以:

I'd do like Vishal but instead of using sum() using size() to get a count of the number of rows allocated to each group of 'start_station_id'. So:

df = male_trips.groupby('start_station_id').size()

这篇关于 pandas :数事的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆