Dataframe filter the highest value from each day and save it again in a DataFrame with 2 columns

Viewed 104

i got a DataFrame like this. df:

enter image description here

I apply the following function to df

df_new = df.groupby(pd.Grouper(key="longtime",freq="D")).agg({df.columns[1]: [np.max]})
df_new = pd.DataFrame(data= df_new)
print(df_new)

following you see the output of df_new. the DatFrame has 1 column. but i want the "longtime" and "amax" to be stored in 2 separate columns. how do I have to adjust the function of df_new to achieve this ?

enter image description here

2 Answers

Remove [] from one element list in agg for avoid MultiIndex and add DataFrame.reset_index:

df_new = (df.groupby(pd.Grouper(key="longtime",freq="D"))
            .agg({df.columns[1]: np.max})
            .reset_index())

You can keep the function as is and just drop the first level of the header rows and then reset the index:

df_new = df_new.droplevel(0, axis=1).reset_index()
Related