vojtam
vojtam

Reputation: 1255

ValueError: window must be an integer 0 or greater in rolling

I want to compute 7 days rolling mean in my dataset.

transaction_week.dtypes

transaction_week.dtypes
zisk_obj               float64
datetime_add    datetime64[ns]
dtype: object

This:

transaction_week["mean_weeks_zisk_obj"] = transaction_week.rolling('7D').mean()

and this:

transaction_week["mean_weeks_zisk_obj"] = transaction_week.reset_index().rolling('7D').mean()

gives the same error:

Traceback (most recent call last):
  File "/usr/lib/python3.8/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "/home/vojtam/Desktop/poptavka_cena/venv/lib/python3.8/site-packages/pandas/core/generic.py", line 10868, in rolling
    return Rolling(
  File "/home/vojtam/Desktop/poptavka_cena/venv/lib/python3.8/site-packages/pandas/core/window/rolling.py", line 158, in __init__
    self.validate()
  File "/home/vojtam/Desktop/poptavka_cena/venv/lib/python3.8/site-packages/pandas/core/window/rolling.py", line 1532, in validate
    raise ValueError("window must be an integer 0 or greater")
ValueError: window must be an integer 0 or greater

How can I fix it please?

This question did not help me: Rolling Mean with Time Offset Pandas

Upvotes: 2

Views: 1438

Answers (1)

vojtam
vojtam

Reputation: 1255

I came with this solution, but there must be a better one:

transaction_week['week'] = transaction_week['datetime_add'].apply(lambda x: x.week)
transaction_week['mean_weeks_zisk_obj'] = transaction_week.groupby(['week'])["zisk_obj"].transform('mean')

Upvotes: 1

Related Questions