Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Creating DataFrames (dict, list, CSV) in Data Analysis Python - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
DataFrame Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this DataFrame creation code?
Consider the following Python code that creates a DataFrame from a dictionary. What will be the output when printing df?
Data Analysis Python
import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)
A
03   boB    1
52   ecilA  0
egA  emaN
B
   Name  Age
1  Alice   25
2    Bob   30
C
   Name  Age
0  Alice   25
1    Bob   30
D
   Name  Age
0  Alice  25
1  Bob  30
2  None  None
Attempts:
2 left
💡 Hint
Look at how pandas assigns default row indices when creating a DataFrame from a dictionary.
❓ data_output
intermediate
1:30remaining
How many rows and columns does this DataFrame have?
Given the code below, how many rows and columns does the resulting DataFrame contain?
Data Analysis Python
import pandas as pd

list_of_dicts = [{'city': 'Paris', 'temp': 20}, {'city': 'Berlin', 'temp': 18}, {'city': 'Rome', 'temp': 25}]
df = pd.DataFrame(list_of_dicts)
print(df.shape)
A(3, 2)
B(3, 3)
C(2, 3)
D(2, 2)
Attempts:
2 left
💡 Hint
The shape attribute returns (rows, columns). Count the dictionaries and keys.
🔧 Debug
advanced
1:00remaining
What error does this code raise when reading a CSV?
What error will this code produce when trying to read the CSV file?
Data Analysis Python
import pandas as pd

df = pd.read_csv('nonexistent_file.csv')
AFileNotFoundError
BValueError
CKeyError
DTypeError
Attempts:
2 left
💡 Hint
Think about what happens if the file path does not exist.
🚀 Application
advanced
2:00remaining
Which code creates a DataFrame with columns 'A' and 'B' from a list of lists?
You have data as a list of lists: [[1, 2], [3, 4]]. Which code correctly creates a DataFrame with columns named 'A' and 'B'?
Apd.DataFrame([[1, 2], [3, 4]], index=['A', 'B'])
Bpd.DataFrame({'A': [1, 3], 'B': [2, 4]})
Cpd.DataFrame({'A': 1, 'B': 2}, [[3, 4]])
Dpd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
Attempts:
2 left
💡 Hint
When using a list of lists, specify columns with the columns parameter.
❓ visualization
expert
2:30remaining
What does this code plot from a CSV file?
Given a CSV file 'data.csv' with columns 'Year' and 'Sales', what will the following code plot?
Data Analysis Python
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('data.csv')
df.plot(x='Year', y='Sales', kind='line')
plt.show()
AA pie chart of Sales distribution
BA line chart showing Sales over Year
CA scatter plot of Year vs Sales
DA bar chart showing Sales over Year
Attempts:
2 left
💡 Hint
The kind='line' parameter specifies the plot type.

Practice

(1/5)
1. What is the main purpose of creating a DataFrame in data analysis?
easy
A. To organize data in a table format for easy analysis
B. To write data to a text file
C. To create a list of numbers
D. To perform calculations without storing data

Solution

  1. Step 1: Understand what a DataFrame is

    A DataFrame is like a table with rows and columns, used to organize data clearly.
  2. Step 2: Identify the purpose of DataFrames

    They help analyze data easily by structuring it in rows and columns.
  3. Final Answer:

    To organize data in a table format for easy analysis -> Option A
  4. Quick Check:

    DataFrame = Table for data analysis [OK]
Hint: DataFrames = tables for data, not just lists or files [OK]
Common Mistakes:
  • Confusing DataFrame with a simple list
  • Thinking DataFrame is for saving files only
  • Believing DataFrame is just for calculations
2. Which of the following is the correct way to create a DataFrame from a dictionary in Python using pandas?
easy
A. pd.DataFrame(name=['Alice', 'Bob'], age=[25, 30])
B. pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]})
C. pd.DataFrame({'name': 'Alice', 'age': 25})
D. pd.DataFrame['name', 'age'] = ['Alice', 'Bob'], [25, 30]

Solution

  1. Step 1: Recall pandas DataFrame creation syntax

    Use pd.DataFrame() with a dictionary where keys are column names and values are lists of column data.
  2. Step 2: Check each option

    pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]}) correctly uses a dictionary with lists for columns. Others have syntax errors or wrong formats.
  3. Final Answer:

    pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]}) -> Option B
  4. Quick Check:

    Dictionary with lists = pd.DataFrame() [OK]
Hint: Use dictionary with lists inside pd.DataFrame() [OK]
Common Mistakes:
  • Using pd.DataFrame with wrong brackets
  • Passing single values instead of lists
  • Trying to assign columns after creating DataFrame
3. What will be the output of this code?
import pandas as pd
data = [[1, 'Alice'], [2, 'Bob']]
df = pd.DataFrame(data, columns=['ID', 'Name'])
print(df)
medium
A. A DataFrame with columns 'ID' and 'Name' showing the two rows of data
B. A list of lists printed as is
C. An error because columns parameter is missing
D. A DataFrame with default numeric column names

Solution

  1. Step 1: Understand DataFrame creation from list of lists

    Passing a list of lists with columns names creates a DataFrame with those columns and rows.
  2. Step 2: Check the print output

    The DataFrame will show two rows with columns 'ID' and 'Name' filled with given data.
  3. Final Answer:

    A DataFrame with columns 'ID' and 'Name' showing the two rows of data -> Option A
  4. Quick Check:

    List + columns = DataFrame table [OK]
Hint: List + columns param creates labeled DataFrame [OK]
Common Mistakes:
  • Expecting a list output instead of DataFrame
  • Forgetting columns parameter causes default columns
  • Confusing list of lists with dictionary input
4. Identify the error in this code that tries to create a DataFrame from a CSV file:
import pandas as pd
df = pd.read_csv('data.csv', header=2)
print(df.head())
medium
A. read_csv cannot read CSV files
B. The file name must be 'data.txt' not 'data.csv'
C. The header parameter should be 0 to read the first row as column names
D. print(df.head()) is incorrect syntax

Solution

  1. Step 1: Understand header parameter in read_csv

    header=2 means pandas treats the third row as column names, which may be wrong if first row has headers.
  2. Step 2: Identify correct header usage

    Usually header=0 is used to read the first row as column names. Using 2 can cause wrong column names or data misalignment.
  3. Final Answer:

    The header parameter should be 0 to read the first row as column names -> Option C
  4. Quick Check:

    header=0 reads first row as columns [OK]
Hint: Use header=0 to read first row as column names [OK]
Common Mistakes:
  • Setting header to wrong row number
  • Confusing file extensions
  • Misunderstanding print(df.head()) usage
5. You have a CSV file with columns 'Name', 'Age', and 'Score'. You want to create a DataFrame but only keep rows where 'Score' is above 80. Which code correctly creates the DataFrame and filters it?
hard
A. import pandas as pd\ndf = pd.read_csv('file.csv', filter='Score > 80')\nprint(df)
B. import pandas as pd\ndf = pd.read_csv('file.csv')\ndf_filtered = df.where('Score' > 80)\nprint(df_filtered)
C. import pandas as pd\ndf = pd.read_csv('file.csv')\ndf_filtered = df.filter('Score > 80')\nprint(df_filtered)
D. import pandas as pd\ndf = pd.read_csv('file.csv')\ndf_filtered = df[df['Score'] > 80]\nprint(df_filtered)

Solution

  1. Step 1: Read CSV file into DataFrame

    Use pd.read_csv('file.csv') to load all data.
  2. Step 2: Filter rows where 'Score' > 80

    Use boolean indexing: df[df['Score'] > 80] to keep only rows with Score above 80.
  3. Final Answer:

    import pandas as pd\ndf = pd.read_csv('file.csv')\ndf_filtered = df[df['Score'] > 80]\nprint(df_filtered) -> Option D
  4. Quick Check:

    Boolean indexing filters rows [OK]
Hint: Use df[df['Score'] > 80] to filter rows [OK]
Common Mistakes:
  • Trying to filter inside read_csv
  • Using df.filter() incorrectly
  • Using df.where() without proper condition
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