We use shift() to move data up or down in a table. This helps us compare current values with past values easily.
shift() for lagging data in Pandas
DataFrame.shift(periods=1, freq=None, axis=0, fill_value=None)
periods tells how many steps to move the data. Positive moves data down (lag), negative moves up (lead).
axis=0 means shift rows, axis=1 means shift columns.
df['lagged'] = df['value'].shift(1)
df['lead'] = df['value'].shift(-1)
df.shift(2)This code creates a table of sales by day. It adds a column with the previous day's sales using shift(1). Then it calculates the change in sales from the previous day.
import pandas as pd data = {'day': [1, 2, 3, 4, 5], 'sales': [100, 150, 200, 130, 170]} df = pd.DataFrame(data) df['previous_day_sales'] = df['sales'].shift(1) df['sales_change'] = df['sales'] - df['previous_day_sales'] print(df)
Missing values appear where there is no previous data after shifting (usually at the start).
You can use fill_value to replace missing values after shifting.
shift() moves data up or down to compare current and past values.
It is useful for time-based comparisons and feature creation.
Remember that shifting creates missing values where data is moved out of range.
Practice
shift() function do in pandas?Solution
Step 1: Understand the purpose of
Theshift()shift()function moves data up or down in a column, creating a lag or lead effect.Step 2: Compare with other options
Sorting, removing missing values, or changing data types are different pandas functions, notshift().Final Answer:
It moves data up or down to compare current and past values. -> Option BQuick Check:
shift()moves data for lagging [OK]
- Confusing shift() with sort()
- Thinking shift() removes missing data
- Assuming shift() changes data types
data by 2 rows downward?Solution
Step 1: Understand shift() parameter
The argument insideshift()is the number of periods to move. Positive values shift downward (lag), negative shift upward (lead).Step 2: Apply to the question
To shift downward by 2 rows, usedata.shift(2). Negative or zero values do not match the requirement.Final Answer:
data.shift(2) -> Option AQuick Check:
Positive number shifts down = data.shift(2) [OK]
- Using negative number to shift downward
- Omitting the argument defaults to shift by 1
- Using zero which means no shift
import pandas as pd data = pd.Series([10, 20, 30, 40, 50]) shifted = data.shift(1)
What is the value of
shifted at index 2?Solution
Step 1: Understand shift(1) effect on Series
Shifting by 1 moves all values down by one index. The value at index 2 inshiftedis the original value at index 1.Step 2: Find original value at index 1
Originaldataat index 1 is 20, soshiftedat index 2 is 20.0 (float due to NaN presence).Final Answer:
20.0 -> Option CQuick Check:
shift(1) moves index 1 value to index 2 [OK]
- Confusing index positions after shift
- Expecting integer type instead of float
- Thinking shifted index 2 is original index 2
import pandas as pd
data = pd.Series([5, 10, 15])
shifted = data.shift('1')Solution
Step 1: Check shift() argument type
Theshift()function expects an integer or a timedelta, not a string.Step 2: Identify error cause
Passing a string like '1' causes a TypeError because pandas cannot interpret it as a number of periods.Final Answer:
The argument to shift() should be an integer, not a string. -> Option DQuick Check:
shift() needs integer periods, not string [OK]
- Passing string instead of integer to shift()
- Thinking shift() only works on DataFrames
- Forgetting shift() default axis is 0
df with a column 'sales'. You want to create a new column 'sales_change' that shows the difference between current sales and sales one day before. Which code correctly achieves this?Solution
Step 1: Understand the goal
We want the change from previous day to current day, so current minus previous.Step 2: Use shift(1) to get previous day sales
df['sales'].shift(1)gives previous day's sales aligned with current row.Step 3: Calculate difference
Subtract previous sales from current sales:df['sales'] - df['sales'].shift(1).Final Answer:
df['sales_change'] = df['sales'] - df['sales'].shift(1) -> Option AQuick Check:
Current minus previous = sales_change [OK]
- Reversing subtraction order
- Using negative shift which looks ahead
- Using diff(-1) which is future difference
Ready to prove it?
Pass the test and this pattern moves unknown
