Bird
Raised Fist0
Pandasdata~20 mins

pct_change() for percentage change in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pct_Change_Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of pct_change() with default parameters
What is the output of the following code snippet using pandas pct_change() with default settings?
Pandas
import pandas as pd

s = pd.Series([100, 120, 144, 172.8])
result = s.pct_change()
print(result)
A
0    NaN
1    1.20
2    1.20
3    1.20
dtype: float64
B
0    NaN
1    0.20
2    0.20
3    0.20
dtype: float64
C
0    0.00
1    0.20
2    0.20
3    0.20
dtype: float64
D
0    NaN
1    20.0
2    20.0
3    20.0
dtype: float64
Attempts:
2 left
💡 Hint
Remember pct_change() calculates the relative change between current and prior element.
❓ data_output
intermediate
2:00remaining
Percentage change with periods parameter
Given the DataFrame below, what is the output of df['value'].pct_change(periods=2)?
Pandas
import pandas as pd

df = pd.DataFrame({'value': [10, 15, 20, 30, 45]})
result = df['value'].pct_change(periods=2)
print(result)
A
0         NaN
1         NaN
2    2.000000
3    2.000000
4    2.250000
Name: value, dtype: float64
B
0         NaN
1         NaN
2    0.500000
3    0.500000
4    0.500000
Name: value, dtype: float64
C
0         NaN
1    0.500000
2    0.333333
3    0.500000
4    0.500000
Name: value, dtype: float64
D
0         NaN
1         NaN
2    1.000000
3    1.000000
4    1.250000
Name: value, dtype: float64
Attempts:
2 left
💡 Hint
The periods=2 means compare with the value two rows before.
🔧 Debug
advanced
2:00remaining
Identify the error in pct_change usage
What error does the following code raise?
Pandas
import pandas as pd

s = pd.Series([1, 2, 3, 4])
result = s.pct_change(periods='two')
print(result)
AValueError: periods must be an integer
BAttributeError: 'str' object has no attribute 'pct_change'
CTypeError: unsupported operand type(s) for -: 'str' and 'int'
DNo error, outputs percentage change
Attempts:
2 left
💡 Hint
Check the type of the periods parameter in pct_change.
🚀 Application
advanced
2:00remaining
Calculate daily returns from stock prices
You have a DataFrame with daily closing prices of a stock. Which code correctly calculates the daily returns as percentage changes?
Pandas
import pandas as pd

df = pd.DataFrame({'close': [100, 105, 110, 121, 115]})
Adf['returns'] = df['close'].pct_change()
Bdf['returns'] = df['close'].diff()
Cdf['returns'] = df['close'].pct_change().fillna(0)
Ddf['returns'] = (df['close'] / df['close'].shift(1)) * 100
Attempts:
2 left
💡 Hint
Daily returns should be percentage changes, and missing values can be filled with zero.
🧠 Conceptual
expert
2:00remaining
Understanding pct_change with fill_method parameter
What is the effect of using fill_method='ffill' in pct_change() on a Series with missing values?
AIt fills missing values forward before calculating percentage change, reducing NaNs in output.
BIt fills missing values backward after calculating percentage change, increasing NaNs in output.
CIt drops missing values before calculating percentage change, causing shorter output.
DIt replaces missing values with zero before calculating percentage change, causing division errors.
Attempts:
2 left
💡 Hint
Think about how forward fill affects data before pct_change calculation.

Practice

(1/5)
1. What does the pct_change() function in pandas do?
easy
A. Calculates the percentage change between consecutive rows.
B. Calculates the sum of all values in a column.
C. Sorts the DataFrame by index.
D. Removes missing values from the DataFrame.

Solution

  1. Step 1: Understand the purpose of pct_change()

    The pct_change() function calculates how much values change in percentage from one row to the next.
  2. Step 2: Compare with other options

    Options A, B, and C describe different pandas functions unrelated to percentage change.
  3. Final Answer:

    Calculates the percentage change between consecutive rows. -> Option A
  4. Quick Check:

    pct_change() = percentage change [OK]
Hint: Think: pct_change means percent change between rows [OK]
Common Mistakes:
  • Confusing pct_change() with sum()
  • Thinking it sorts data
  • Assuming it removes missing values
2. Which of the following is the correct way to use pct_change() on a pandas DataFrame named df?
easy
A. df.pct_change()
B. pct_change(df)
C. df.change_pct()
D. df.percent_change()

Solution

  1. Step 1: Recall pandas method syntax

    In pandas, pct_change() is a method called on a DataFrame or Series object, so the correct syntax is df.pct_change().
  2. Step 2: Check other options

    Options A, B, and D are not valid pandas syntax or method names.
  3. Final Answer:

    df.pct_change() -> Option A
  4. Quick Check:

    Method called on DataFrame = df.pct_change() [OK]
Hint: Remember: pandas methods use dot notation like df.method() [OK]
Common Mistakes:
  • Using pct_change() as a standalone function
  • Mixing method names
  • Using incorrect method names
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'Sales': [100, 120, 150, 180]})
print(df.pct_change())

What is the output?
medium
A. 0.2, 0.25, 0.2, NaN
B. 0, 20, 30, 30
C. NaN, 20, 30, 30
D. NaN, 0.2, 0.25, 0.2

Solution

  1. Step 1: Calculate percentage changes row by row

    From 100 to 120: (120-100)/100 = 0.2
    From 120 to 150: (150-120)/120 = 0.25
    From 150 to 180: (180-150)/150 = 0.2
  2. Step 2: Understand first row result

    The first row has no previous row, so result is NaN.
  3. Final Answer:

    NaN, 0.2, 0.25, 0.2 -> Option D
  4. Quick Check:

    pct_change() = NaN, 0.2, 0.25, 0.2 [OK]
Hint: First row is always NaN; next rows show percent change [OK]
Common Mistakes:
  • Confusing absolute change with percent change
  • Forgetting first row is NaN
  • Mixing up order of results
4. What is wrong with this code snippet?
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30]})
result = df.pct_change(axis=1)
print(result)
medium
A. The DataFrame has no numeric columns.
B. The code is correct and will run without errors.
C. pct_change() requires a parameter 'periods' to work.
D. pct_change() cannot be used with axis=1 on this DataFrame.

Solution

  1. Step 1: Understand axis parameter in pct_change()

    By default, pct_change() calculates percentage change down rows (axis=0). axis=1 calculates change across columns.
  2. Step 2: Check DataFrame shape and axis=1 effect

    The DataFrame has only one column. pct_change(axis=1) produces NaN values everywhere since there are no multiple columns to compare, but the code runs without errors or exceptions.
  3. Final Answer:

    The code is correct and will run without errors. -> Option B
  4. Quick Check:

    axis=1 on single column = NaN output, no error [OK]
Hint: axis=1 on single column gives NaN but runs fine [OK]
Common Mistakes:
  • Thinking axis=1 causes error on single-column DataFrame
  • Believing periods parameter is required
  • Claiming no numeric columns
5. You have a DataFrame df with daily stock prices:
import pandas as pd
df = pd.DataFrame({'Price': [50, 52, 51, 53, 54]})

You want to calculate the percentage change over 2 days instead of 1. Which code will give the correct result?
hard
A. df.pct_change(axis=1)
B. df.pct_change(periods=1)
C. df.pct_change(periods=2)
D. df.pct_change(periods=0)

Solution

  1. Step 1: Understand the periods parameter

    The periods parameter in pct_change() sets how many rows to look back for percentage change calculation. For 2-day change, use periods=2.
  2. Step 2: Check other options

    df.pct_change(periods=1) calculates 1-day change, df.pct_change(axis=1) uses axis=1 which is incorrect for this data, and df.pct_change(periods=0) computes zero change.
  3. Final Answer:

    df.pct_change(periods=2) -> Option C
  4. Quick Check:

    periods=2 for 2-day change [OK]
Hint: Use periods=2 to compare with 2 rows before [OK]
Common Mistakes:
  • Using default periods=1 for 2-day change
  • Using axis=1 incorrectly
  • Setting periods=0 which is invalid
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard