-3

How could i calculate a rolling average with f-stringed columns? Normally it's:

df.columns=['x','y']
rollingaverage = df.y.rolling(window=6).mean()

How do I do implement this given I use f-string? This didn't work:

    concatted  apple_y  banana_y    date         apple banana
  apple_bana  0.500      2         2010-02-20    True True   
       apple  0.400      3         2010-02-10    True False
      banana  0.530      4         2010-01-12    False  True   
       ...
fruits= ['apple', 'banana']
for fruit in fruits:
    selected_rows = df[ df[ fruit ] == True ]
    df[f'{fruit}_rollingaverage'] = selected_rows.[f'{fruit}_y'].rolling(window=6).mean()
arv
  • 398
  • 1
  • 9

1 Answers1

1

Your code is mostly fine. It seems like you have a couple of typos. The following works (note that I changed the size of the window to 1, to get some meaningful results for this small dataset).

data = """    concatted  apple_y  banana_y    date         apple banana
  apple_bana  0.500      2         2010-02-20    True True   
       apple  0.400      3         2010-02-10    True False
      banana  0.530      4         2010-01-12    False  True   
"""
df = pd.read_csv(StringIO(data), sep = "\s+")

fruits= ['apple', 'banana']
for fruit in fruits:
    selected_rows = df[ df[ fruit ] == True ]
    df[f'{fruit}_rollingaverage'] = selected_rows[f'{fruit}_y'].rolling(window=1).mean()

print(df)

The output is:

    concatted  apple_y  banana_y        date  apple  banana  apple_rollingaverage  banana_rollingaverage
0  apple_bana     0.50         2  2010-02-20   True    True                   0.5                    2.0
1       apple     0.40         3  2010-02-10   True   False                   0.4                    NaN
2      banana     0.53         4  2010-01-12  False    True                   NaN                    4.0
Roy2012
  • 11,755
  • 2
  • 22
  • 35
  • Thanks in the code I also create other variables like the 'apple_y' beforehand. When running this rolling average line, I get key error :KeyError: 'apple_y'. Is this because of missing values in that apple_y column? – arv Jul 26 '20 at 10:19
  • So please include a piece of code that actually reproduces the issue ... – Roy2012 Jul 26 '20 at 10:21