Creating DataFrames (dict, list, CSV) in Data Analysis Python - Performance & Efficiency
When we create DataFrames from different data sources, the time it takes depends on the input size and format.
We want to know how the time grows as the data gets bigger.
Analyze the time complexity of the following code snippet.
import pandas as pd
n = 10 # example value for n
data_dict = {"A": list(range(n)), "B": list(range(n))}
df_from_dict = pd.DataFrame(data_dict)
list_of_lists = [[i, i*2] for i in range(n)]
df_from_list = pd.DataFrame(list_of_lists, columns=["A", "B"])
# Assume CSV file with n rows
# df_from_csv = pd.read_csv('data.csv') # reading CSV into DataFrame
This code creates DataFrames from a dictionary, a list of lists, and mentions reading from a CSV file.
- Primary operation: Iterating over n rows to build DataFrame structure.
- How many times: Each element in the input data is processed once.
As the number of rows n increases, the time to create the DataFrame grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: Doubling the input roughly doubles the work done.
Time Complexity: O(n)
This means the time to create a DataFrame grows linearly with the number of rows.
[X] Wrong: "Creating a DataFrame from a dictionary or list is instant and does not depend on data size."
[OK] Correct: Even though it feels fast for small data, the process reads each row once, so time grows with data size.
Understanding how data loading time grows helps you explain performance in real projects and shows you think about efficiency.
"What if we read a CSV file with many columns instead of rows? How would the time complexity change?"
Practice
Solution
Step 1: Understand what a DataFrame is
A DataFrame is like a table with rows and columns, used to organize data clearly.Step 2: Identify the purpose of DataFrames
They help analyze data easily by structuring it in rows and columns.Final Answer:
To organize data in a table format for easy analysis -> Option AQuick Check:
DataFrame = Table for data analysis [OK]
- Confusing DataFrame with a simple list
- Thinking DataFrame is for saving files only
- Believing DataFrame is just for calculations
Solution
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.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.Final Answer:
pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]}) -> Option BQuick Check:
Dictionary with lists = pd.DataFrame() [OK]
- Using pd.DataFrame with wrong brackets
- Passing single values instead of lists
- Trying to assign columns after creating DataFrame
import pandas as pd data = [[1, 'Alice'], [2, 'Bob']] df = pd.DataFrame(data, columns=['ID', 'Name']) print(df)
Solution
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.Step 2: Check the print output
The DataFrame will show two rows with columns 'ID' and 'Name' filled with given data.Final Answer:
A DataFrame with columns 'ID' and 'Name' showing the two rows of data -> Option AQuick Check:
List + columns = DataFrame table [OK]
- Expecting a list output instead of DataFrame
- Forgetting columns parameter causes default columns
- Confusing list of lists with dictionary input
import pandas as pd
df = pd.read_csv('data.csv', header=2)
print(df.head())Solution
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.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.Final Answer:
The header parameter should be 0 to read the first row as column names -> Option CQuick Check:
header=0 reads first row as columns [OK]
- Setting header to wrong row number
- Confusing file extensions
- Misunderstanding print(df.head()) usage
Solution
Step 1: Read CSV file into DataFrame
Use pd.read_csv('file.csv') to load all data.Step 2: Filter rows where 'Score' > 80
Use boolean indexing: df[df['Score'] > 80] to keep only rows with Score above 80.Final Answer:
import pandas as pd\ndf = pd.read_csv('file.csv')\ndf_filtered = df[df['Score'] > 80]\nprint(df_filtered) -> Option DQuick Check:
Boolean indexing filters rows [OK]
- Trying to filter inside read_csv
- Using df.filter() incorrectly
- Using df.where() without proper condition
Ready to prove it?
Pass the test and this pattern moves unknown
