2016-11-03 3 views
3

各IDに対して最大の系列を持つ1つのレコードを保持したいと思います。だから私は1つの行が必要です。私はPythonの各IDの最大の系列を記録してください。

df_new = df.groupby('id')['series'].nlargest(1) 

ようなものが必要だと思うが、それは間違いなく間違っているのです。

私のデータセットがどのように見えるかです:

id series s1 s2 s3 
1 2  4 9 1 
1 8  6 2 2 
1 3  9 1 3 
2 9  4 1 5 
2 2  2 5 5 
2 5  1 7 8 
3 6  7 2 3 
3 2  4 4 1 
3 1  3 9 9 

これは結果でなければなりません:あなたは「ID」列にgroupbyにしたい

id series s1 s2 s3 
1 8  6 2 2 
2 9  4 1 5 
3 6  7 2 3 

答えて

4

sort_valuesと集計firstのもう一つの解決策:

df = df.sort_values(by="series", ascending=False).groupby("id", as_index=False).first() 
print (df) 
    id series s1 s2 s3 
0 1  8 6 2 2 
1 2  9 4 1 5 
2 3  6 7 2 3 
6

IIUC、どこで "シリーズのインデックスラベルを取得値はidxmax()を使用して最大です。これを使用して元のdfにインデックスバックします:

In [91]: 
df.loc[df.groupby('id')['series'].idxmax()] 

Out[91]: 
    id series s1 s2 s3 
1 1  8 6 2 2 
3 2  9 4 1 5 
6 3  6 7 2 3 
3

ここだ1つのnumpyのベースのソリューション -

def grouby_max(df): 
    arr = df[['id','series']].values 
    n = arr.shape[0]-1 
    idx = (arr[:,0]*(arr[:,1].max()+1) + arr[:,1]).argsort() 
    sidx = np.append(np.nonzero(arr[idx[1:],0] > arr[idx[:-1],0])[0],n) 
    return df.iloc[idx[sidx]] 

ランタイムテスト -

In [201]: # Setup input 
    ...: N = 100 # Number of groups 
    ...: data = np.random.randint(11,999999,(10000,5)) 
    ...: data[:,0] = np.sort(np.random.randint(1,N+1,(data.shape[0]))) 
    ...: df = pd.DataFrame(data, columns=[['id','series','s1','s2','s3']]) 
    ...: 

In [202]: %timeit df.loc[df.groupby('id')['series'].idxmax()] 
100 loops, best of 3: 15.8 ms per loop #@EdChum's soln 

In [203]: %timeit df.sort_values(by="series", ascending=False).groupby("id", as_index=False).first() 
100 loops, best of 3: 4.52 ms per loop #@jezrael's soln 

In [204]: %timeit grouby_max(df) 
100 loops, best of 3: 1.96 ms per loop 
関連する問題