Fix the Bug: Column Selection
Intermediate · Fix the bug · from Pandas: Create, Load, and Explore DataFrames
From the lesson: Pandas: Create, Load, and Explore DataFrames
You have a spreadsheet with 10,000 rows of sales data. You need to find every order over $500, group them by region, and calculate the average. In Excel, that takes a pivot table, a filter, and a lot of clicking. In pandas, it takes three lines of code.
Read the lessonThis code tries to select two columns from a DataFrame but throws an error. Fix the bug so it prints the name and city columns as a DataFrame. Print the column names as a list using print(result.columns.tolist()).
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob'],
'age': [28, 34],
'city': ['NYC', 'LA']
})
# Bug: this line has incorrect brackets
result = df['name', 'city']
print(result.columns.tolist())
More Pandas DataFrame exercises
- Create a Named SeriesIntermediate
- Build a DataFrame from a DictionaryIntermediate
- DataFrame from RecordsIntermediate
- Predict the Output: head()Intermediate
- Add a Computed ColumnIntermediate
- Extract Stats from describe()Intermediate
All Python exercises · 50 practice problems · Data Science & Machine Learning quiz