代码之家  ›  专栏  ›  技术社区  ›  Outcast

无法使用count创建新列并保留groupby列

  •  1
  • Outcast  · 技术社区  · 7 年前

    我正在做以下工作:

    data_weeks = pd.read_csv('Desktop/Weeks_ids.csv', keep_default_na=True)
    data_surveys = pd.read_csv('Desktop/surveys_data.csv', keep_default_na=True)
    
    data_surveys_with_weeks = data_weeks.merge(data_surveys , on=['Date'], how='inner')
    
    data_surveys_with_weeks = data_surveys_with_weeks.groupby(['Store_id', 'Week_id'], as_index=False).transform('count')
    
    data_surveys_with_weeks .to_csv('Desktop/Performance Engine/surveys_count.csv', index=False)
    

    但是,不是用 count 对于 Store_id 和 Week_id 我没有得到这个专栏,我也错过了 库斯泰德 和 周日 柱。

    为什么会发生这种事,我该怎么解决?

    1 回复  |  直到 7 年前
        1
  •  1
  •   It_is_Chris    7 年前

    只需将返回的序列分配给一个新列:

    # sample data
    df = pd.DataFrame({'Date':pd.date_range('2019-01-01', '2019-01-10'),
                       'Week':pd.date_range('2019-01-01', '2019-01-10').week,
                       'store_id': [1,1,1,2,2]*2})
    
    df['group_count'] = df.groupby(['store_id', 'Week']).transform('count')
    
            Date  Week  store_id  group_count
    0 2019-01-01     1         1            4
    1 2019-01-02     1         1            4
    2 2019-01-03     1         1            4
    3 2019-01-04     1         2            2
    4 2019-01-05     1         2            2
    5 2019-01-06     1         1            4
    6 2019-01-07     2         1            2
    7 2019-01-08     2         1            2
    8 2019-01-09     2         2            2
    9 2019-01-10     2         2            2
    

    或者如果你不想归还所有东西 agg :

    df.groupby(['store_id', 'Week']).agg('count')
    
                   Date
    store_id Week      
    1        1        4
             2        2
    2        1        2
             2        2
    

    更新

    您得到的错误是因为附加的列…它将返回一个帧而不是一个序列,所以只需指定要计数的列。请参见新示例:

    df = pd.DataFrame({'Date':pd.date_range('2019-01-01', '2019-01-10'),
                       'Week':pd.date_range('2019-01-01', '2019-01-10').week,
                       'store_id': [1,1,1,2,2]*2,
                      'another_col':np.random.randn(10)})
    
    df['group_count'] = df.groupby(['store_id', 'Week'])['Date'].transform('count')
    

    或者另一个例子 自动增益控制 :

    df.groupby(['store_id', 'Week']).agg({'Date':'count'})