Python | Pandas Series.shift ()

Python Methods and Functions

Series.shift() Pandas Series.shift() shifts the index to the desired number of periods from the optional time frequency. When freq is not passed, shift the index without aligning the data.

Syntax: Series.shift (periods = 1, freq = None, axis = 0, fill_value = None)

Parameter:
periods: Number of periods to shift. Can be positive or negative.
freq: Offset to use from the tseries module or time rule (eg 'EOM')
axis: Shift direction .
fill_value: The scalar value to use for newly introduced missing values ​​

Returns: Copy of input object, shifted.

Example # 1: Use Series.shift () to offset the data of this Series object by 2 periods.

# import pandas as pd

import pandas as pd

 
# Create a series

sr = pd.Series ([ 'New York' , 'Chicago' , ' Toronto' , 'Lisbon' , ' Rio' , 'Moscow' ])

 
# Create date and time index

didx = pd.DatetimeIndex (start = ' 2014-08-01 10:00' , freq = 'W'

  periods = 6 , tz = ' Europe / Berlin' < code class = "plain">) 

 
# set index

sr.index = didx

 
# Print series

print (sr)

Output:

We will now use Series.shift () to shift the data in this series object by 2 periods.

# shift by 2 period

sr.shift (periods = 2 )

Output:

As we can see in the output, Series.shift () has successfully shifted the data along the index. Note that the data corresponding to the last two indices has been deleted.

Example # 2: Use Series.shift () to offset the data of this Series object for -2 periods.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 'New York' , 'Chicago' , ' Toronto' , 'Lisbon' , ' Rio' , 'Moscow' ])

  
# Create date and time index

didx = pd.DatetimeIndex (start = '2014-08-01 10:00' , freq = 'W'

periods = 6 , tz = ' Europe / Berlin'

 
# set index

sr.index = didx

  
# Print series

print (sr)

Output:

Now we will use Series.shift () to shift the data in this series object by -2 periods.

# shift by -2 periods

sr.shift (periods = - 2 )

Output:

As we can see in the output, Series.shift () has successfully shifted the data p about the index. Note that the data for the first two indices has been removed.





Get Solution for free from DataCamp guru