Home > Software engineering >  I need to transform an array to a colum
I need to transform an array to a colum

Time:04-30

I have a data frame in python and in certains columns i calculated the rolling mean. the result of this rolling means is an array.

I want to transform this arrays to columns to generate a new dataframe of rolling means to calculate a heatmap.

i hope you understand mi question

i have this rolling means

mmal = pd.Series(df['Alcohol (ml)']).rolling (window = 3).mean().iloc[2:].values
mmca = pd.Series(df['Cardio (cal)']).rolling (window = 3).mean().iloc[2:].values
mmfz = pd.Series(df['Fuerza (cal)']).rolling (window = 3).mean().iloc[2:].values
mmay = pd.Series(df['Ayuno (h)']).rolling (window = 3).mean().iloc[2:].values
mmdp = pd.Series(df['Dif Peso (kg)']).rolling (window = 3).mean().iloc[2:].values
mmdg = pd.Series(df['Dif Grasa (kg)']).rolling (window = 3).mean().iloc[2:].values
mmdm = pd.Series(df['Dif Músculo (kg)']).rolling (window = 3).mean().iloc[2:].values
mmdgv = pd.Series(df['Grasa Visceral']).rolling (window = 3).mean().iloc[2:].values
mmda = pd.Series(df['Dif (ml)']).rolling (window = 3).mean().iloc[2:].values
mmdpa = pd.Series(df['Pasos']).rolling (window = 3).mean().iloc[2:].values
mmdsn = pd.Series(df['Sueño (h)']).rolling (window = 3).mean().iloc[2:].values
mmdh = pd.Series(df['Huesos (kg)']).rolling (window = 3).mean().iloc[2:].values

and i want this results y a data frame where the columns are all this variables

CodePudding user response:

How about

pd.DataFrame({
    'Alcohol (ml)': mmal,
    'Cardio (cal)': mmca,
    # ... rest ...
})    

And it would be simpler if you would use for-loop with df.columns

import pandas as pd

df = pd.DataFrame({
    'Alcohol (ml)':[1,2,3,4,5,6,7,8,9,0],
    'Cardio (cal)':[0,9,8,7,6,5,4,3,2,1],
    # ... rest ...
})

results = {}

for name in df.columns:
    results[name] = pd.Series(df[ name ]).rolling(window=3).mean().iloc[2:].values

pd.DataFrame(results)    

CodePudding user response:

IIUC, you can do something like this using pd.concat and list comprehension:

cols = ['Alcohol (ml)', 'Cardio (cal)', 'Fuerza (cal)',
        'Ayuno (h)', 'Dif Peso (kg)', 'Dif Grasa (kg)',
        'Dif Músculo (kg)', 'Grasa Visceral', 'Dif (ml)',
        'Pasos', 'Sueño (h)', 'Huesos (kg)', 'Huesos (kg)']

df_new = pd.concat([pd.Series(df[col]).rolling (window = 3).mean().iloc[2:]] for col in cols], axis=1) 
  • Related