I have a DataFrame
df
like this:
Date Close Symbol
0 2018-03-05 44.21 AAPL
1 2018-03-06 44.17 AAPL
2 2018-03-07 43.76 AAPL
3 2018-03-08 44.24 AAPL
4 2018-03-09 44.99 AAPL
... ... ... ...
1253 2023-02-24 146.71 AAPL
1254 2023-02-27 147.92 AAPL
1255 2023-02-28 147.41 AAPL
1256 2023-03-01 145.31 AAPL
1257 2023-03-02 145.91 AAPL
If I say to resample
the data by month:
monthly = df.resample('M', on = 'Date')
print(monthly)
I get
DatetimeIndexResampler [freq=<MonthEnd>, axis=0, closed=right, label=right, convention=start, origin=start_day]
2017-11-23 11:20:21.374692 100
If I instead try to get the percent change
by month
like this:
monthly = df.resample('M', on = 'Date').agg(lambda x: x[-1])
I get an error:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/ivanfigueredo/Documents/python/rr/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script
exec(code, module.__dict__)
File "/Users/ivanfigueredo/Documents/python/rr/rr.py", line 571, in <module>
volworks()
File "/Users/ivanfigueredo/Documents/python/rr/rr.py", line 431, in volworks
monthly = df.resample('M', on = 'Date').agg(lambda x: x[-1])
File "/Users/ivanfigueredo/Documents/python/rr/lib/python3.9/site-packages/pandas/core/resample.py", line 355, in aggregate
result = self._groupby_and_aggregate(how, *args, **kwargs)
File "/Users/ivanfigueredo/Documents/python/rr/lib/python3.9/site-packages/pandas/core/resample.py", line 460, in _groupby_and_aggregate
result = grouped.apply(how, *args, **kwargs)
File "/Users/ivanfigueredo/Documents/python/rr/lib/python3.9/site-packages/pandas/core/groupby/groupby.py", line 1567, in apply
result = self._python_apply_general(f, self._selected_obj)
File "/Users/ivanfigueredo/Documents/python/rr/lib/python3.9/site-packages/pandas/core/groupby/groupby.py", line 1629, in _python_apply_general
values, mutated = self.grouper.apply(f, data, self.axis)
File "/Users/ivanfigueredo/Documents/python/rr/lib/python3.9/site-packages/pandas/core/groupby/ops.py", line 839, in apply
res = f(group)
File "/Users/ivanfigueredo/Documents/python/rr/rr.py", line 431, in <lambda>
monthly = df.resample('M', on = 'Date').agg(lambda x: x[-1])
File "/Users/ivanfigueredo/Documents/python/rr/lib/python3.9/site-packages/pandas/core/frame.py", line 3807, in __getitem__
indexer = self.columns.get_loc(key)
File "/Users/ivanfigueredo/Documents/python/rr/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3804, in get_loc
raise KeyError(key) from err
KeyError: -1