How to save the obtained medias in a dataframe, in a new column containing the averages of this dataframe using pandas?

Asked

Viewed 1,847 times

1

Good night, I have a problem trying to save values of the average of a df, in a single column. An example of how I wanted you to stay was:

Dataframe

In this first part, I just opened my dataframe and transpires to get with the function Mean() the values of the averages.

Maybe it’s a bit of a dumb question, but I’m really not getting to put the values of the media I got in that Mean() function in a new column with such values. Is there any way to do that? Thank you very much!!

1 answer

1

To put the average in the last column, it is necessary:

  1. Turn first row into header

  2. Calculate the mean on the vertical axis (axis=0)

  3. Indicate that you want the (average) calculation only with the numerical values, otherwise the Labels (e.g., 'consumption1') will interfere in the calculation.

Below is how to insert the media column':

# Cria o DataFrame
df = pd.DataFrame({'cliente':[1,2,3],'consumo1':[10,11,45],'consumo2':[12,20,10],'consumo3':[13,45,18]})

# Transpõe
df_transp = df.T

# Saída
df_transp
           0   1   2
cliente    1   2   3
consumo1  10  11  45
consumo2  12  20  10
consumo3  13  45  18

# Seta o nome das colunas para os valores da primeira linha
df_transp.columns = df_transp.iloc[0]

# Define os dados começando a partir da segunda linha
df_transp = df_transp[1:]

# Saída
df_transp
cliente    1   2   3
consumo1  10  11  45
consumo2  12  20  10
consumo3  13  45  18

# AQUI => Cria a coluna 'media' com os valores 
# da média (apenas para valores numéricos) calculados 
# no eixo vertical (axis=0)
df_transp.loc[:,'media'] = df_transp.mean(numeric_only=True, axis=0).values

# Saída
df_transp
cliente    1   2   3      media
consumo1  10  11  45  11.666667
consumo2  12  20  10  25.333333
consumo3  13  45  18  24.333333
  • 1

    Managed to remedy my doubts, and still managed to apply in other situations, thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.