Check if all elements in a group are equal using pandas GroupBy
Use groupby
and nunique
, and check whether the result is 1:
df.groupby([df.datetime.dt.date, 'rating']).signal.nunique().eq(1)
datetime rating
2018-12-20 HY True
IG False
2018-12-27 HY True
IG True
Name: signal, dtype: bool
Or, similarly, using apply
with set
conversion:
(df.groupby([df.datetime.dt.date, 'rating']).signal
.apply(lambda x: len(set(x)) == 1))
datetime rating
2018-12-20 HY True
IG False
2018-12-27 HY True
IG True
Name: signal, dtype: bool
PS., you don't need to assign a temp column, groupby
takes arbitrary grouper arguments.
Try to find out alternative without using groupby
just for fun
df.datetime=df.datetime.dt.date
s=pd.crosstab(df.datetime,[df.rating,df.signal])
s.eq(s.sum(axis=1,level=0),1).any(level=0,axis=1).stack()
Out[556]:
datetime rating
2018-12-20 HY True
IG False
2018-12-27 HY True
IG True
dtype: bool