熊猫:groupby,并通过串联结果创建一个新列

时间:2018-08-16 15:50:57

标签: python pandas merge concat

我想知道如何在groupby之后创建一个新列并应用求和。

我有一个这样的数据框。

> 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. groupby tour_id,并在time列中求和,其中condAcondBcondC均为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合并到原始df

3 个答案:

答案 0 :(得分:1)

使用all过滤数据帧

df['driving']=df.tour_id.map(df[(df.iloc[:,-3:]).all(1)].groupby('tour_id').time.sum())

答案 1 :(得分:1)

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 :(得分:0)

您可以将groupby数据框转换为字典,然后通过它映射tour_id列:

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