In the dataframe below, I want to
- insert corresponding average
Scoreof eachStatein a new column calledavg
import pandas as pd
import numpy as np
# initialise data of lists.
data = {'State':['CA', 'CA', 'CA', 'CA','CA', 'TX', 'TX', 'TX','TX', 'TX', 'FL', 'FL','FL', 'FL', 'FL', 'AZ','AZ','AZ', 'AZ', 'AZ'],
'Score':[3,3,3,2,1,4,2,2,1,2,1,1,1,1,2,2,5,5,5,5],
'Income':[32112,34214,45575,22106,32612,34216,47515,22906,32112,34511,45525,12106,52112,54214,45015,22986,32112,34214,47518,22175],
}
df = pd.DataFrame(data)
My attempt below:
mean_score = df.groupby(['State'])['Score'].agg(pd.Series.mean)
mean_score[:4]
# I need assistance here, instead of subsetting one by one I want efficiently append the mean_score to each corresponding state
az = df.loc[df['State'] == 'AZ']
az['avg'] = mean_score[0]
ca = df.loc[df['State'] == 'CA']
ca['avg'] = mean_score[1]
fl = df.loc[df['State'] == 'FL']
fl['avg'] = mean_score[2]
tx = df.loc[df['State'] == 'TX']
tx['avg'] = mean_score[3]
# concat all 4 dataframes
new_df = pd.concat([az,ca,fl,tx],axis = 0).reset_index(drop = True)
# export the output as a csv file
new_df.to_csv("analysis_output.csv",index = False)