代码之家  ›  专栏  ›  技术社区  ›  Makoto Miyazaki

Pandas:groupby并通过连接结果生成新列

  •  0
  • Makoto Miyazaki  · 技术社区  · 7 年前

    我有一个这样的数据框。

    > df
    tour_id  time  condA  condB  condC
          1    10   True   True   True
          1    20   True   True   True
          1    30  False  False  False
          1    40  False  False  False
          2    15   True   True   True
          2    25  False  False  False
          2    30  False  False  False
          2    45  False  False  False
          2    50   True   True   True
    

    1. 子句 tour_id 取一笔 time 列,其中 condA condB condC 都是 False

      tour_id    sum
            1     70
            2    100
      
    2. 将1的结果合并到原始数据帧 df ,在组中填充相同的值,并将此新列命名为 driving .

    结果应该是:

    tour_id  time  condA  condB  condC  driving
          1    10   True   True   True       70
          1    20   True   True   True       70
          1    30  False   False False       70
          1    40  False   False False       70
          2    15   True   True   True      100
          2    25  False  False  False      100
          2    30  False  False  False      100
          2    45  False  False  False      100
          2    50   True   True   True      100
    

    我的尝试:

    temp = df[(df.condA == True)&(df.condB == True) &(df.condC == True)]
    df2 = temp.groupby('tour_id').time.sum().reset_index()
    

    但我不知道怎么合并 df2 原汁原味 .

    3 回复  |  直到 7 年前
        1
  •  1
  •   rahlf23    7 年前
    df['driving'] = df['tour_id'].map(df[~df[['condA','condB','condC']].all(1)].groupby('tour_id')['time'].sum())
    

    产量:

       tour_id  time  condA  condB  condC  driving
    0        1    10   True   True   True       70
    1        1    20   True   True   True       70
    2        1    30  False  False  False       70
    3        1    40  False  False  False       70
    4        2    15   True   True   True      100
    5        2    25  False  False  False      100
    6        2    30  False  False  False      100
    7        2    45  False  False  False      100
    8        2    50   True   True   True      100
    
        2
  •  1
  •   BENY    7 年前

    使用 all

    df['driving']=df.tour_id.map(df[(df.iloc[:,-3:]).all(1)].groupby('tour_id').time.sum())
    
        3
  •  0
  •   ysearka    7 年前

    您可以将groupby数据帧转换为dict,然后通过它映射tour\u id列:

    df['driving'] = df.tour_id.map(temp.groupby('tour_id').time.sum().to_dict())