计算pandas数据帧中非数字列的每日出现次数

时间:2017-08-02 13:15:04

标签: python pandas

我有这个人。 dataframe(每小时时间戳索引):

                      relative_humidity                 condition   fid
2017-08-02 10:00:00               0.49  Chance of a Thunderstorm     1
2017-08-02 11:00:00               0.50  Chance of a Thunderstorm     1
2017-08-02 12:00:00               0.54             Partly Cloudy     1
2017-08-02 13:00:00               0.58             Partly Cloudy     2
2017-08-02 14:00:00               0.68             Partly Cloudy     2

如何计算每天最常出现的情况,并将其放在以日期为索引的数据框中。还需要按fid分隔?

我试过了:

df.groupby(['fid', pd.Grouper(freq='D')])['condition']

2 个答案:

答案 0 :(得分:2)

index[0]需要value_counts,因为数据已排序且第一个值为top:

d = {'level_1':'date'}
df1 = df.groupby(['fid', pd.Grouper(freq='D')])['condition'] \
       .apply(lambda x: x.value_counts().index[0]).reset_index().rename(columns=d)
print (df1)
   fid       date                 condition
0    1 2017-08-02  Chance of a Thunderstorm
1    2 2017-08-02             Partly Cloudy

答案 1 :(得分:1)

df.groupby(['fid',pd.Grouper(freq='D'),'condition']).size().groupby(level=[0,1]).head(1)

输出:

fid              condition               
1    2017-08-02  Chance of a Thunderstorm    2
2    2017-08-02  Partly Cloudy               2
dtype: int64