每月,每年分组的值计数-熊猫

时间:2019-04-17 11:05:21

标签: python pandas group-by count transform

我正在尝试groupby在特定输出中每月和每年的日期计数。我每天都可以这样做,但是每月/每年都无法获得相同的输出。

d = ({
    'Date' : ['1/1/18','1/1/18','2/1/18','3/1/18','1/2/18','1/3/18','2/1/19','3/1/19'],                 
    'Val' : ['A','B','C','D','A','B','C','D'],                                      
     })

df = pd.DataFrame(data = d)

df['Date'] = pd.to_datetime(df['Date'], format= '%d/%m/%y')

df['Count_d'] = df.Date.map(df.groupby('Date').size())

这是我想要的输出:

        Date Val  Count_d
0 2018-01-01   A        2
1 2018-01-01   B        2
2 2018-01-02   C        1
3 2018-01-03   D        1
4 2018-02-01   A        1
5 2018-03-01   B        1
6 2019-01-02   C        1
7 2019-01-03   D        1

当我尝试执行类似操作但每月和每年时,我使用以下内容:

df1 = df.groupby([df['Date'].dt.year.rename('year'), df['Date'].dt.month.rename('month')]).agg({'count'})
print(df)

但是输出是:

            Date   Val
           count count
year month            
2018 1         4     4
     2         1     1
     3         1     1
2019 1         2     2

预期输出:

        Date Val  Count_d Count_m Count_y
0 2018-01-01   A        2       4       6
1 2018-01-01   B        2       4       6
2 2018-01-02   C        1       4       6
3 2018-01-03   D        1       4       6
4 2018-02-01   A        1       1       6
5 2018-03-01   B        1       1       6
6 2019-01-02   C        1       2       2
7 2019-01-03   D        1       2       2

2 个答案:

答案 0 :(得分:6)

GroupBy.transform用于具有与原始DataFrame相同大小的列:

df['Date'] = pd.to_datetime(df['Date'], format= '%d/%m/%y')
y = df['Date'].dt.year
m = df['Date'].dt.month

df['Count_d'] = df.groupby('Date')['Date'].transform('size')
df['Count_m'] = df.groupby([y, m])['Date'].transform('size')
df['Count_y'] = df.groupby(y)['Date'].transform('size')

print(df)
        Date Val  Count_d  Count_m  Count_y
0 2018-01-01   A        2        4        6
1 2018-01-01   B        2        4        6
2 2018-01-02   C        1        4        6
3 2018-01-03   D        1        4        6
4 2018-02-01   A        1        1        6
5 2018-03-01   B        1        1        6
6 2019-01-02   C        1        2        2
7 2019-01-03   D        1        2        2

答案 1 :(得分:1)

您可以使用pd.Grouper

df['Count_d'] = df.groupby([pd.Grouper(key='Date', freq='D')])['Date'].transform('size').astype(int)
df['Count_m'] = df.groupby([pd.Grouper(key='Date', freq='M')])['Date'].transform('size').astype(int)
df['Count_y'] = df.groupby([pd.Grouper(key='Date', freq='Y')])['Date'].transform('size').astype(int)

哪个会给

        Date Val  Count_d  Count_m  Count_y
0 2018-01-01   A        2        4        6
1 2018-01-01   B        2        4        6
2 2018-01-02   C        1        4        6
3 2018-01-03   D        1        4        6
4 2018-02-01   A        1        1        6
5 2018-03-01   B        1        1        6
6 2019-01-02   C        1        2        2
7 2019-01-03   D        1        2        2

您可以以此将各种不同的频率分组,请参见documentation on DateOffsets