pandas shift a column forwards in python

To shift a column forward, we can use the shift() function in pandas. The shift() function can be used with two parameters: periods and freq. The periods parameter specifies the number of periods to shift the values. A positive value of periods shifts the column forward, and a negative value shifts it backward. The freq parameter specifies the frequency of the data, which is important when working with time series data.

Here's an example of how to shift a column forwards in pandas:

main.py
import pandas as pd

# Create a dataframe
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50]})

# Shift column B forward by 1 period
df['B_shifted'] = df['B'].shift(periods=1)

print(df)
203 chars
10 lines

Output:

main.py
   A   B  B_shifted
0  1  10        NaN
1  2  20       10.0
2  3  30       20.0
3  4  40       30.0
4  5  50       40.0
120 chars
7 lines

In this example, we created a dataframe with two columns A and B. We then used the shift() function to shift column B forward by one period and stored the result in a new column B_shifted. Note that the first value of B_shifted is NaN, since there is no value to shift into the first row.

related categories

gistlibby LogSnag