How to get count of categories within column from

2019-07-29 13:55发布

I'm new to data frames and am struggling to figure out how to accomplish the following:

I have a dataframe already as a time series like so:

timestamp             source                        
2017-06-18 10:43:54    two
2017-06-20 03:38:23    three
2017-06-18 07:37:02    one
2017-06-07 16:49:51    two
2017-06-15 22:36:10    two
2017-06-07 16:49:51    two
2017-06-18 22:36:10    two

I am trying to 1) resample into daily and 2) get a % of each category for that day. Like so:

timestamp      One    Two  Three                    
2017-06-18     33%    66%    0%
2017-06-20     0%     0%    100%
2017-06-07     0%    100%    0%
2017-06-15     0%    100%    0%

I can accomplish basic things like, get a count of 'source' resampled to daily, but it doesn't break it down into categories.

Can anyone help point me in the right direction? Greatly appreciated.

1条回答
仙女界的扛把子
2楼-- · 2019-07-29 14:21

groupby + value_counts + unstack

(df.groupby(df.timestamp.dt.date).source.value_counts(normalize=True)*100).unstack().fillna(0)

source            one  three         two
timestamp                               
2017-06-07   0.000000    0.0  100.000000
2017-06-15   0.000000    0.0  100.000000
2017-06-18  33.333333    0.0   66.666667
2017-06-20   0.000000  100.0    0.000000

pivot_table

df2 = df.pivot_table(index=df.timestamp.dt.date, columns='source', aggfunc='size')
df2 = df2.divide(df2.sum(1), axis=0).fillna(0)*100

pd.crosstab

pd.crosstab(df.timestamp.dt.date, df.source, normalize='index')*100
查看更多
登录 后发表回答