Bird
Raised Fist0
Pandasdata~20 mins

Reading Excel files with read_excel in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Excel Reader Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of reading specific sheet from Excel
What is the output of this code snippet when reading the 'Sales' sheet from an Excel file?
Pandas
import pandas as pd
from io import BytesIO
import numpy as np

# Create a sample Excel file in memory
excel_file = BytesIO()
with pd.ExcelWriter(excel_file, engine='xlsxwriter') as writer:
    pd.DataFrame({'Month': ['Jan', 'Feb'], 'Sales': [100, 150]}).to_excel(writer, sheet_name='Sales', index=False)
    pd.DataFrame({'Month': ['Jan', 'Feb'], 'Expenses': [80, 90]}).to_excel(writer, sheet_name='Expenses', index=False)

excel_file.seek(0)

# Read only the 'Sales' sheet
sales_df = pd.read_excel(excel_file, sheet_name='Sales')
print(sales_df)
A
  Month  Sales
0   Jan    100
1   Feb    150
B
  Month  Expenses
0   Jan        80
1   Feb        90
C
Empty DataFrame
Columns: []
Index: []
DRaises FileNotFoundError
Attempts:
2 left
💡 Hint
Check which sheet is being read by the read_excel function.
❓ data_output
intermediate
2:00remaining
Number of rows read from Excel with skiprows
Given an Excel file with 5 rows of data, what is the number of rows in the DataFrame after reading with skiprows=2?
Pandas
import pandas as pd
from io import BytesIO

# Create Excel file with 5 rows
excel_file = BytesIO()
data = {'A': range(5), 'B': range(5, 10)}
df = pd.DataFrame(data)
with pd.ExcelWriter(excel_file, engine='xlsxwriter') as writer:
    df.to_excel(writer, index=False)
excel_file.seek(0)

# Read Excel skipping first 2 rows
read_df = pd.read_excel(excel_file, skiprows=2)
print(len(read_df))
A3
B2
C5
D0
Attempts:
2 left
💡 Hint
skiprows skips the first rows before reading data.
🔧 Debug
advanced
2:00remaining
Identify the error when reading Excel with wrong engine
What error will this code raise when trying to read an Excel file but the file is actually a CSV?
Pandas
import pandas as pd
from io import StringIO

csv_data = "A,B\n1,2\n3,4"
csv_file = StringIO(csv_data)

# Attempt to read CSV data as Excel
pd.read_excel(csv_file)
AXLRDError: Unsupported format, or corrupt file
BFileNotFoundError
CValueError: Excel file format cannot be determined, you must specify an engine manually.
DTypeError: read_excel() got an unexpected keyword argument 'engine'
Attempts:
2 left
💡 Hint
The input is not an Excel file but read_excel expects one.
❓ visualization
advanced
2:00remaining
Plotting data read from Excel
After reading this Excel sheet, what will the plot show?
Pandas
import pandas as pd
import matplotlib.pyplot as plt
from io import BytesIO

excel_file = BytesIO()
with pd.ExcelWriter(excel_file, engine='xlsxwriter') as writer:
    pd.DataFrame({'Year': [2020, 2021, 2022], 'Revenue': [1000, 1500, 2000]}).to_excel(writer, index=False)
excel_file.seek(0)

df = pd.read_excel(excel_file)
plt.plot(df['Year'], df['Revenue'])
plt.xlabel('Year')
plt.ylabel('Revenue')
plt.title('Yearly Revenue')
plt.grid(True)
plt.show()
AA bar chart with Year on x-axis and Revenue values
BA line plot with Year on x-axis and Revenue increasing from 1000 to 2000
CA scatter plot with random points
DNo plot is shown due to error
Attempts:
2 left
💡 Hint
Look at the plt.plot function and the data columns used.
🧠 Conceptual
expert
2:00remaining
Effect of usecols parameter in read_excel
If an Excel file has columns 'A', 'B', 'C', 'D', what columns will be read with usecols='B:D'?
AColumns 'C' and 'D' only
BColumns 'A', 'B', and 'C'
COnly column 'B'
DColumns 'B', 'C', and 'D'
Attempts:
2 left
💡 Hint
usecols='B:D' means columns from B to D inclusive.

Practice

(1/5)
1. What does the pandas.read_excel() function do?
easy
A. Saves a pandas DataFrame to an Excel file
B. Creates a new Excel file
C. Loads data from an Excel file into a pandas DataFrame
D. Converts Excel formulas into Python code

Solution

  1. Step 1: Understand the purpose of read_excel

    The function pandas.read_excel() is designed to read data from Excel files.
  2. Step 2: Identify the output type

    It loads the Excel data into a pandas DataFrame, which is a table-like structure for data analysis.
  3. Final Answer:

    Loads data from an Excel file into a pandas DataFrame -> Option C
  4. Quick Check:

    read_excel loads Excel data [OK]
Hint: Remember: read_excel reads, not writes Excel files [OK]
Common Mistakes:
  • Confusing read_excel with to_excel
  • Thinking it creates Excel files
  • Assuming it converts formulas automatically
2. Which of the following is the correct syntax to read the sheet named 'Sales' from an Excel file 'data.xlsx' using pandas?
easy
A. pd.read_excel('data.xlsx', sheet='Sales')
B. pd.read_excel('data.xlsx', sheet_name='Sales')
C. pd.read_excel('data.xlsx', sheetname='Sales')
D. pd.read_excel('data.xlsx', sheetname=Sales)

Solution

  1. Step 1: Recall the correct parameter name

    The correct parameter to specify the sheet is sheet_name, not sheet or sheetname.
  2. Step 2: Check the syntax and quotes

    pd.read_excel('data.xlsx', sheet_name='Sales') uses sheet_name='Sales' correctly with quotes around the sheet name.
  3. Final Answer:

    pd.read_excel('data.xlsx', sheet_name='Sales') -> Option B
  4. Quick Check:

    Use sheet_name to select sheet [OK]
Hint: Use sheet_name, not sheet or sheetname [OK]
Common Mistakes:
  • Using sheet instead of sheet_name
  • Missing quotes around sheet name
  • Passing sheetname without quotes causing error
3. Given the Excel file 'report.xlsx' with two sheets: '2023' and '2024'. The '2023' sheet has columns 'Month', 'Sales', 'Profit'. What will be the output of this code?
import pandas as pd
df = pd.read_excel('report.xlsx', sheet_name='2023', usecols=['Month', 'Profit'])
print(df.head())
medium
A. A DataFrame with columns 'Month' and 'Profit' showing first 5 rows
B. A DataFrame with all columns from '2023' sheet
C. Error because usecols expects column indexes, not names
D. Empty DataFrame because 'Profit' column is missing

Solution

  1. Step 1: Understand usecols parameter

    The usecols parameter accepts a list of column names to read only those columns.
  2. Step 2: Check the sheet and columns requested

    The code reads sheet '2023' and selects columns 'Month' and 'Profit'. It then prints the first 5 rows with head().
  3. Final Answer:

    A DataFrame with columns 'Month' and 'Profit' showing first 5 rows -> Option A
  4. Quick Check:

    usecols selects columns by name [OK]
Hint: usecols can take column names list [OK]
Common Mistakes:
  • Thinking usecols only accepts indexes
  • Expecting all columns without usecols
  • Assuming head() prints all rows
4. What is wrong with this code snippet to read only the first 10 rows from 'data.xlsx'?
import pandas as pd
df = pd.read_excel('data.xlsx', nrows=10)
print(df)
medium
A. Nothing is wrong; the code correctly reads the first 10 rows
B. The file path is incorrect
C. Missing sheet_name parameter causes error
D. The print statement is incorrect

Solution

  1. Step 1: Check if nrows is supported by read_excel

    The read_excel function supports the nrows parameter to limit the number of rows read.
  2. Step 2: Verify other components

    The import is correct, file path is standard, sheet_name is optional (uses first sheet), and print(df) displays the DataFrame.
  3. Final Answer:

    Nothing is wrong; the code correctly reads the first 10 rows -> Option A
  4. Quick Check:

    nrows supported in read_excel [OK]
Hint: read_excel supports nrows parameter [OK]
Common Mistakes:
  • Thinking nrows is not supported by read_excel
  • Assuming sheet_name is mandatory
  • Thinking print causes error
5. You have an Excel file 'sales_data.xlsx' with multiple sheets named by year (e.g., '2021', '2022'). You want to read only the sheets for years 2021 and 2022 and combine them into one DataFrame. Which code snippet correctly does this?
hard
A. df = pd.read_excel('sales_data.xlsx', sheet_name='2021,2022')
B. df1 = pd.read_excel('sales_data.xlsx', sheet_name='2021') df2 = pd.read_excel('sales_data.xlsx', sheet_name='2022') df_combined = df1.append(df2)
C. df = pd.read_excel('sales_data.xlsx', sheet_name=['2021', '2022']) df_combined = df.concat()
D. df = pd.read_excel('sales_data.xlsx', sheet_name=['2021', '2022']) df_combined = pd.concat(df.values())

Solution

  1. Step 1: Read multiple sheets using sheet_name list

    Using sheet_name=['2021', '2022'] reads both sheets and returns a dictionary of DataFrames.
  2. Step 2: Combine the DataFrames from dictionary values

    pd.concat(df.values()) concatenates all DataFrames in the dictionary into one DataFrame.
  3. Final Answer:

    df = pd.read_excel('sales_data.xlsx', sheet_name=['2021', '2022']) df_combined = pd.concat(df.values()) -> Option D
  4. Quick Check:

    Use sheet_name list + concat dict values [OK]
Hint: Read sheets as dict, then concat values [OK]
Common Mistakes:
  • Using sheet_name string with comma
  • Trying to call concat on dict
  • Using deprecated append method
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