DataFrame.shift() - ( Pandas DataFrame Basics )
Heading h2
Syntax
DataFrame.shift(periods=1, freq=None, axis=0, fill_value=None)
Example
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df_shifted = df.shift(periods=1)
print(df_shifted)
Output
a b
0 NaN NaN
1 1.0 4.0
2 2.0 5.0
Explanation
DataFrame.shift()
is a Pandas function that shifts the index by a specified number of periods. This can be useful for time-series data or for comparing data with previous or future time points.
The function shifts the index values and optionally fills any gaps with a specified value. By default, the shift is applied along the row axis (axis=0
), but it can also be applied along the column axis (axis=1
).
In the above example, we create a simple Pandas DataFrame with two columns and then use df.shift(periods=1)
to shift the index values down by one period. This produces a new DataFrame with the same columns, but with the first row containing NaN
values.
Use
The DataFrame.shift()
function is useful for analyzing time-series data or comparing data at different time points. By shifting the index values by a specified number of periods, we can compare data at previous or future time points and observe trends or changes over time.
Important Points
DataFrame.shift()
is a Pandas function that shifts the index by a specified number of periods- The shift can be applied along the row axis (
axis=0
) or the column axis (axis=1
) - The function optionally fills any gaps with a specified value
Summary
In conclusion, DataFrame.shift()
is a useful function in Pandas for analyzing time-series data and comparing data at different time points. By shifting the index values by a specified number of periods, we can observe trends and changes over time and make comparisons with previous or future time points.