Ask a dataframe grouping problem

clipboard.png
such a table, if you want to group it with key1, take the row with the larger data2, and how do you make a table?
tried df.groupby ("key1",as_index=False). Max () takes the largest of all columns. This won"t work. What can I do?
this is the original data:
df = pd.DataFrame ({"key1": [" one","two","one","two","one"], "data1":np.random.randn (5)," data2":np.random.randn (5)})
df

Mar.02,2021

def f(df, col=1):
    return df[df['data2'] == max(df['data2'])]

df1 = df.groupby(['key1']).apply(f)

l = df.groupby('key1')['data2'].max().tolist()
df = df.query('data2 in @l')

Menu