每个指数在一年内至少有两个不同的月份出现条目

  • 本文关键字:两个 指数 一年 python pandas
  • 更新时间 :
  • 英文 :


索引日期(dd.mm.yy(

A 1.1.20
A 1.2.20
B 1.1.20
B 5.5.21
C 1.1.20
C 10.1.20
D 1.1.20
D 10.1.20
D 10.5.20

我想看看一年内每个索引是否至少有两个月出现条目

因此,对于索引A、D,答案是True,对于B、C,答案是False预期输出:

A真
B假
C假
D真

我可以通过使用Grouper 轻松查看它是否在至少两个不同的月(或几年(内出现

df.groupby([index, pd.Grouper(freq='M', key='date]).agg('count')

并查看count是否>0

但是我怎样才能容易地检查这两个条件是否适用呢?

我尝试创建自己的agg函数或使用Grouper。

如果我们希望数据帧的形状与以前相同:

df['date'] = pd.to_datetime(df.date, dayfirst=True)
def resampled_data(freq):
    return df.groupby(['index', pd.Grouper(key='date', freq=freq)]).index.transform('count')
yg = resampled_data('Y')
mg = resampled_data('M')
df['bool'] = ((yg >= 2) & (mg != 2)) | ((yg >= 3) & (mg >=2))

输出

    index   date    bool
0   A   2020-01-01  True
1   A   2020-02-01  True
2   B   2020-01-01  False
3   B   2021-05-05  False
4   C   2020-01-01  False
5   C   2020-01-10  False
6   D   2020-01-01  True
7   D   2020-01-10  True
8   D   2020-05-10  True
df_per_month = pd.DataFrame.from_dict(df.groupby([index, df.date.dt.year, df.date.dt.month]).groups.keys())
df_max_entries_in_a_year = df_per_month.groupby([0,1]).agg('count').reset_index().groupby([0])[2].agg('max')

最新更新