Home > Software design >  Grouping by Date, using two functions and putting them in alternate order
Grouping by Date, using two functions and putting them in alternate order

Time:10-19

I basically want a Dataframe, that has the max and min of a specific Date in alternating order. But I run into 2 problems:

  1. I can't concat after using agg with 2 functions
  2. I haven't found an elegant way to get these "two" columns into one alternating one

Help would be really appreciated Edit: Sorry I didn't make it clearer, I will try here :

I have a csv file containing dates and values.

I want a csvfile in the following way:

date1, max(date1)

date1, min(date1)

date2, max(date2)

date2, min(date1) etc.

I hope that explains it better

CodePudding user response:

It's hard to know exactly what the setup is without seeing some data, but if you get your data into a pandas.DataFrame called df with columns "date", "min", "max" then you can use pandas.DataFrame.melt:

df.melt(id_vars="date").sort_values(["date", "variable"])

This will give you columns

  • "date" - the original date
  • "variable" - either "min" or "max" strings
  • "value" - the min or max value for the date

CodePudding user response:

Use DataFrame.stack with Series.reset_index:

df1 = (df.groupby('col1')['col2']
        .agg(['max','min'])
        .stack()
        .reset_index(level=1, drop=True)
        .reset_index(name='new'))
  • Related