<jupyter_start><jupyter_text>Time ShiftingSometimes you may need to shift all your data up or down along the time series index. In fact, a lot of pandas built-in methods do this under the hood. This isn't something we'll do often in the course, but it's definitely good to know about this anyways!<jupyter_code>import pandas as pd
df = pd.read_csv('../Data/starbucks.csv',index_col='Date',parse_dates=True)
df.head()
df.tail()<jupyter_output><empty_output><jupyter_text>.shift() forwardThis method shifts the entire date index a given number of rows, without regard for time periods (months & years).It returns a modified copy of the original DataFrame.<jupyter_code>df.shift(1).head()
# NOTE: You will lose that last piece of data that no longer has an index!
df.shift(1).tail()<jupyter_output><empty_output><jupyter_text>.shift() backwards<jupyter_code>df.shift(-1).head()
df.shift(-1).tail()<jupyter_output><empty_output><jupyter_text>Shifting based on Time Series Frequency CodeWe can choose to shift index values up or down without realigning the data by passing in a freq argument.This method shifts dates to the next period based on a frequency code. Common codes are 'M' for month-end and 'A' for year-end. Refer to the Time Series Offset Aliases table from the Time Resampling lecture for a full list of values, or click here.<jupyter_code># Shift everything forward one month
df.shift(periods=1, freq='M').head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08953168044077135, 'fraction_numerical': 0.003443526170798898, 'mean_word_length': 5.821596244131455, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '67377', 'license': 'Apache-2.0', 'n_tokens_mistral': 439, 'n_tokens_neox': 428, 'n_words': 177, 'path': '01-Time-Series-with-Pandas/02-Time-Shifting.ipynb', 'repo_name': 'vwang0/time_series_analysis', 'size': '1452'}