Creating another column with values from a 'groupby' column after the 'groupby' statement

Viewed 14

Hi I have a dataset like the one below:

data = [['ALFA', 351740.00, 0.31, 0.22, 0.44, 0.19, 0.05], 
            ['ALFA', 401740.00, 0.43, 0.26, 0.23, 0.16, 0.09], 
            ['Bravo', 511830.00, 0.52, 0.16, 0.08, 0.26, 0], 
            ['Charlie', 590030.00, 0.75, 0.2, 0.14, 0.37, 0.06], 
            ['Charlie', 590030.00, 0.75, 0.2, 0.27, 0.2, 0.01], 
            ['Delta', 590030.00, 0.75, 0.2, 0.34, 0.3, 0], 
            ['Delta', 590030.00, 0.75, 0.2, 0, 0.28, 0], 
            ['Echo', 590030.00, 0.75, 0.2, 0.08, 0.26, 0], 
            ['Echo', 590030.00, 0.75, 0.2, 0.14, 0.37, 0.06]]
    
df = pd.DataFrame(data, columns= ['Name', 'Column1', 'Column2', 'Column3', 'Column4', 'Column5', 'Column6'])
df

I grouped by 'Names' to get the mean of the 'Names' and saved it as a new dataframe using the code below:

df1 = df.groupby('Name').mean()
df1

However, I can no longer access the 'Names' column (as would a normal dataframe column) after the last 'groupby' statement. I tried main things including df1['cluster_id'] = df1['Name'] but ended up with errors. Is there a way to create another column 'Cluster_id' with same data as the 'Names' column so the output looks like the df shown below and I can use it for further analysis?

Name   Column1   Column2  Column3  Column4 Column5 Column6 Cluster_id                       
ALFA    376740.0    0.37    0.24    0.335   0.175   0.070   ALFA
Bravo   511830.0    0.52    0.16    0.080   0.260   0.000   Bravo
Charlie 590030.0    0.75    0.20    0.205   0.285   0.035   Charlie
Delta   590030.0    0.75    0.20    0.170   0.290   0.000   Delta
Echo    590030.0    0.75    0.20    0.110   0.315   0.030   Echo
0 Answers
Related