The pandas
library is a powerful data manipulation and analysis tool in Python. The shift()
function is used to shift the index of a DataFrame or a Series by a specified number of periods. It can be applied to both rows and columns.
Here's the syntax of the shift()
function:
main.py63 chars2 lines
periods
specifies the number of periods to shift. A positive value will shift the index forward, while a negative value will shift it backward. By default, it is set to 1.freq
is an optional parameter that represents the time frequency of the data.axis
determines whether the shift is applied to rows (axis=0) or columns (axis=1). By default, it is set to 0.fill_value
is an optional parameter that determines the value to use for newly created missing values. By default, missing values are filled with NaN (Not a Number).Here's an example usage of the shift()
function on a DataFrame in pandas:
main.py169 chars9 lines
In the above example, the original DataFrame df
has the values [1, 2, 3, 4, 5] in column 'A'. After applying df.shift(periods=2)
, the resulting DataFrame df_shifted
will have the values [NaN, NaN, 1, 2, 3] in column 'A', where the first two values are filled with NaN as there are no values to shift backward.
Note that the shift()
function does not modify the original DataFrame; it returns a new shifted DataFrame instead.
gistlibby LogSnag