Pandas DataFrame | slice_shift method
Start your free 7-days trial now!
Pandas DataFrame.slice_shift(~)
method shifts the rows of the DataFrame by the specified amount, and empty rows are stripped away.
Both methods slice_shift(~)
and shift(~)
perform shifting, but there are two main differences:
slice_shift(~)
does not return a new copy of the source DataFrame, that is, modifying the result ofslice_shift(~)
will end up mutating the source DataFrame. In contrast,shift(~)
returns a new copy.slice_shift(~)
may modify the shape of the DataFrame, whereas theshift(~)
method always returns a DataFrame with the same shape as the original. Check examples below for clarification.
Parameters
1. periods
link | int
The amount to shift by:
positive integers: rows are shifted downwards
negative integers: rows are shifted upwards.
Return Value
A DataFrame
with the rows shifted.
Examples
Consider the following DataFrame:
df = pd.DataFrame({"A":["a","b","c","d"],"B":["e","f","g","h"],"C":["i","j","k","l"]}, index=[6,7,8,9])df
A B C6 a e i7 b f j8 c g k9 d h l
Basic usage
To shift down by 2 rows:
df.slice_shift(2)
A B C8 a e i9 b f j
Notice how only the values are shifted down, while the index is left as is. Since indexes 6
and 7
no longer have valid values, those rows are stripped away.
To contrast this with the shift(~)
method:
df.shift(2)
A B C6 NaN NaN NaN7 NaN NaN NaN8 a e i9 b f j
The takeaway here is that, instead of throwing away indexes 6
and 7
, shift(~)
simply fill their values with NaN
.
Shifting upwards
To shift up by 2 rows:
df.slice_shift(-2)
A B C0 c g k1 d h l
Mutating behaviour
Consider the same DataFrame as above:
df = pd.DataFrame({"A":["a","b","c","d"],"B":["e","f","g","h"],"C":["i","j","k","l"]}, index=[6,7,8,9])df
A B C6 a e i7 b f j8 c g k9 d h l
Performing the shift and storing the returned DataFrame in x
:
x = df.slice_shift(2)x
A B C8 a e i9 b f j
If we modify x
, then the original df
is mutated as well:
x.iloc[0,0] = "Z"df
A B C6 Z e i7 b f j8 c g k9 d h l