我有一个数据框,其格式为:
Date Time station num_bikes
1 3.02 Girwood 0
2 4.10 Fraser 0
3 10.10 Carslile 0
4 10.10 Girwood 5
5 7.46 Fraser 0
6 3.02 Girwood 0
我想知道自行车数量为零的时间和发生次数。 形式为:
Time Station Occurrences
3.02 Girwood 2
9.05 Girwood 1
4.10 Fraser 1
7.46 Fraser 1
10.10 Carslile 1
答案 0 :(得分:1)
仅过滤满足条件的行,然后过滤groupby
+ size
。使用NamedAgg
可以稍微清理一下语法。您可以选择任何列的size
,因此我任意选择'Time'
。
(df[df.num_bikes.eq(0)]
.groupby(['Time', 'station'])
.agg(occurences=('Time', 'size'))
.reset_index())
Time station occurences
0 3.02 Girwood 2
1 4.10 Fraser 1
2 7.46 Fraser 1
3 10.10 Carslile 1
答案 1 :(得分:1)
使用具有直接列名pd.crosstab
的{{1}}尝试不同的操作
Occurences