在python中记录每个id的最大序列
我想为每个id保留一个序列最大的记录。因此,对于每个id,我需要一行。我想我需要像这样的东西在python中记录每个id的最大序列,python,pandas,numpy,Python,Pandas,Numpy,我想为每个id保留一个序列最大的记录。因此,对于每个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
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 series s1 s2 s3
1 8 6 2 2
2 9 4 1 5
3 6 7 2 3
IIUC您希望在“id”列上获取“Series”值最大的索引标签,并使用该标签在原始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
另一种解决方案是使用和聚合:
这里有一个基于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
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