在pandas python中按两列分组,最大值为第三

时间:2017-06-27 09:22:40

标签: python pandas dataframe

我有一个包含PERIOD_START_TIME,ID,更多列和列VALUE的数据框。 我需要的是按PERIOD_START_TIME和ID分组(因为时间和ID有重复的行)并取值VALUE的最大值。 DF:

PERIOD_START_TIME     ID       VALUE
06.01.2017 02:00:00   55  ...   35
06.01.2017 02:00:00   55  ...   22
06.01.2017 03:00:00   55  ...   63
06.01.2017 03:00:00   55  ...   33
06.01.2017 04:00:00   55  ...   63
06.01.2017 04:00:00   55  ...   45
06.01.2017 02:00:00   65  ...   10
06.01.2017 02:00:00   65  ...   5
06.01.2017 03:00:00   65  ...   22
06.01.2017 03:00:00   65  ...   5
06.01.2017 04:00:00   65  ...   12
06.01.2017 04:00:00   65  ...   15

期望的输出:

PERIOD_START_TIME     ID  ...  VALUE
06.01.2017 02:00:00   55  ...   35
06.01.2017 03:00:00   55  ...   63
06.01.2017 04:00:00   55  ...   63
06.01.2017 02:00:00   65  ...   10
06.01.2017 03:00:00   65  ...   22
06.01.2017 04:00:00   65  ...   15

1 个答案:

答案 0 :(得分:4)

使用groupby并汇总max

app.get('/', (req, res) => {
    var count = 0; 
    request(url1, function(err, data) {
       count++;
       // something to be done
       if(count == 3) {
          res.render('index'); 
       }  
    });
    request(url2, function(err, data) {
       count++;
       // something to be done
       if(count == 3) {
          res.render('index'); 
       }  
    });
    request(url3, function(err, data) {
       count++;
       // something to be done
       if(count == 3) {
          res.render('index'); 
       }  
    });

或者:

print (df)
      PERIOD_START_TIME  ID  A  VALUE
0   06.01.2017 02:00:00  55  8     35
1   06.01.2017 02:00:00  55  8     22
2   06.01.2017 03:00:00  55  8     63
3   06.01.2017 03:00:00  55  8     33
4   06.01.2017 04:00:00  55  8     63
5   06.01.2017 04:00:00  55  8     45
6   06.01.2017 02:00:00  65  8     10
7   06.01.2017 02:00:00  65  8      5
8   06.01.2017 03:00:00  65  8     22
9   06.01.2017 03:00:00  65  8      5
10  06.01.2017 04:00:00  65  8     12
11  06.01.2017 04:00:00  65  8     15

df = df.groupby(['PERIOD_START_TIME','ID'], as_index=False)['VALUE'].max()            
df = df.groupby(['PERIOD_START_TIME','ID'])['VALUE'].max().reset_index()

要获取更多列,需要idxmax并按loc选择:

print (df)
     PERIOD_START_TIME  ID  VALUE
0  06.01.2017 02:00:00  55     35
1  06.01.2017 02:00:00  65     10
2  06.01.2017 03:00:00  55     63
3  06.01.2017 03:00:00  65     22
4  06.01.2017 04:00:00  55     63
5  06.01.2017 04:00:00  65     15

替代:

df = df.loc[df.groupby(['PERIOD_START_TIME','ID'])['VALUE'].idxmax()]  
print (df)
      PERIOD_START_TIME  ID  A  VALUE
0   06.01.2017 02:00:00  55  8     35
6   06.01.2017 02:00:00  65  8     10
2   06.01.2017 03:00:00  55  8     63
8   06.01.2017 03:00:00  65  8     22
4   06.01.2017 04:00:00  55  8     63
11  06.01.2017 04:00:00  65  8     15