Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply calculation for dataframe columns for multiple dataframes at the same time

I am creating multiple dataframes for each unique value in a column. It works properly.

regions = dataDF['region'].unique().tolist()  df_dict = {name:
dataDF.loc[dataDF['region'] == name] for name in regions}

However, now I would like to calculate the average for the temperature and then calculate the mean afterward for every newly created dataframe.

for df in df_dict:
    df['avg'] = (df['tmax'] + df['tmin'])/2
    df = pd.DataFrame(df.groupby(df['date'].dt.year)['avg'].mean())

Thanks for the help in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Dictionary of DataFrames is not necessary, you can aggregate by year and column region:

out = (dataDF[['tmax', 'tmin']].mean(axis=1)
                               .groupby([dataDF['region'], dataDF['date'].dt.year])
                               .mean())

Or:

out = (dataDF.assign(avg = dataDF[['tmax', 'tmin']].mean(axis=1), 
                     y = dataDF['date'].dt.year)
             .groupby(['region', 'y'])['avg']
             .mean())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading