Python Forum

Full Version: How to use bfill und groupby under conditions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm trying to backfill previous rows (which are filled with 0) with the mean of the last value before each serie of last 0.

see picture for a better understanding. [Image: 1ssVXsm] picture

here is the file file

here is what I tried

for row in data.itertuples():
    if row == 0:
        data['Date_Time'] = data['Date_Time'].where(data['x'].between(0, 0)).bfill()
        final_data = df.fillna(method='bfill').groupby('Date_Time', as_index=False)['x']).sum()

# Error
  File "<ipython-input-23-c1ec45568d73>", line 4
    final_data = df.fillna(method='bfill').groupby('Date_Time', as_index=False)['x']).sum()
                                                                                    ^
SyntaxError: invalid syntax
Look sharp. Count the brackets. Look at the caret (^). It shows exactly where the syntax error is.