We use DataFrames to organize data in tables with rows and columns. Creating a DataFrame from a NumPy array helps us turn raw numbers into a clear table format for easy analysis.
Creating DataFrame from NumPy array in Pandas
import pandas as pd import numpy as np # Create a NumPy array data_array = np.array([[1, 2], [3, 4]]) # Create DataFrame from the array df = pd.DataFrame(data_array, columns=['Column1', 'Column2'], index=['Row1', 'Row2'])
The columns parameter names the columns.
The index parameter names the rows.
import pandas as pd import numpy as np # Empty array empty_array = np.array([]).reshape(0, 0) df_empty = pd.DataFrame(empty_array) print(df_empty)
import pandas as pd import numpy as np # One element array one_element_array = np.array([[42]]) df_one = pd.DataFrame(one_element_array, columns=['OnlyColumn'], index=['OnlyRow']) print(df_one)
import pandas as pd import numpy as np # Array with multiple rows and columns multi_array = np.array([[10, 20, 30], [40, 50, 60]]) df_multi = pd.DataFrame(multi_array, columns=['A', 'B', 'C'], index=['First', 'Second']) print(df_multi)
This program shows how to turn a NumPy array of student scores into a labeled DataFrame for easier reading and analysis.
import pandas as pd import numpy as np # Step 1: Create a NumPy array with sample data sample_data = np.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]]) # Step 2: Print the original NumPy array print("Original NumPy array:") print(sample_data) # Step 3: Create a DataFrame from the NumPy array # Naming columns and rows for clarity data_frame = pd.DataFrame(sample_data, columns=['Math', 'Science', 'English'], index=['Student1', 'Student2', 'Student3']) # Step 4: Print the DataFrame print("\nDataFrame created from NumPy array:") print(data_frame)
Creating a DataFrame from a NumPy array takes O(n*m) time, where n is rows and m is columns, because it copies all data.
It uses extra memory to store row and column labels besides the array data.
Common mistake: forgetting to match the number of column names to the number of columns in the array causes errors.
Use this method when you want to add labels and use pandas features; if you only need raw numbers, NumPy arrays alone may be enough.
DataFrames organize array data into labeled tables.
You can add row and column names when creating a DataFrame from a NumPy array.
This helps make data easier to understand and analyze with pandas tools.
Practice
Solution
Step 1: Understand what a DataFrame is
A DataFrame is a table-like structure with rows and columns, which helps organize data clearly.Step 2: Know the role of NumPy arrays
NumPy arrays hold data in a grid but lack labels for rows and columns.Final Answer:
Organize array data into a labeled table with rows and columns -> Option CQuick Check:
DataFrame = labeled table from array [OK]
- Thinking DataFrame converts arrays to charts automatically
- Confusing DataFrame creation with SQL querying
- Believing DataFrame auto-converts back to NumPy arrays
arr with column names ['A', 'B']?Solution
Step 1: Recall DataFrame constructor parameters
Thecolumnsparameter sets column labels, anddatais the array.Step 2: Check each option
pd.DataFrame(arr, columns=['A', 'B']) correctly usescolumns=['A', 'B']with the array as data. pd.DataFrame(arr, index=['A', 'B']) wrongly usesindexfor columns. pd.DataFrame(columns=['A', 'B'], arr) incorrectly passesarrpositionally after keywordcolumns, causing a syntax error. pd.DataFrame(arr, names=['A', 'B']) uses a non-existentnamesparameter.Final Answer:
pd.DataFrame(arr, columns=['A', 'B']) -> Option AQuick Check:
Use columns= for column names [OK]
- Using index= instead of columns= for column names
- Passing data positionally after columns keyword (syntax error)
- Using invalid parameter names like names=
import numpy as np import pandas as pd arr = np.array([[1, 2], [3, 4]]) df = pd.DataFrame(arr, columns=['X', 'Y']) print(df)
Solution
Step 1: Understand the array and DataFrame creation
The array has shape (2,2) with values [[1,2],[3,4]]. Columns are named ['X', 'Y'].Step 2: Predict DataFrame output
Rows get default index 0 and 1. Columns are X and Y. Values fill accordingly.Final Answer:
X Y 0 1 2 1 3 4 -> Option DQuick Check:
Array shape matches DataFrame shape with columns named [OK]
- Confusing row and column labels
- Expecting error due to columns parameter
- Misreading array shape and values
import numpy as np import pandas as pd arr = np.array([[5, 6], [7, 8]]) df = pd.DataFrame(arr, columns=['A']) print(df)
Solution
Step 1: Check array shape and columns length
The array has 2 columns, but columns=['A'] has length 1.Step 2: Understand pandas error
pandas raises a ValueError because the number of columns does not match the array's second dimension.Final Answer:
The columns list length does not match the number of array columns -> Option BQuick Check:
Columns length must equal array columns [OK]
- Assuming 1D array is required
- Thinking index parameter is mandatory with columns
- Believing integers are invalid in DataFrames
arr = np.array([[10, 20], [30, 40], [50, 60]]). You want to create a DataFrame with columns named ['Height', 'Weight'] and row labels ['Alice', 'Bob', 'Charlie']. Which code correctly creates this DataFrame?Solution
Step 1: Understand DataFrame parameters for rows and columns
Usecolumns=to name columns andindex=to name rows.Step 2: Check each option
pd.DataFrame(arr, columns=['Height', 'Weight'], index=['Alice', 'Bob', 'Charlie']) correctly usescolumns=['Height', 'Weight']andindex=['Alice', 'Bob', 'Charlie']. pd.DataFrame(arr, index=['Height', 'Weight'], columns=['Alice', 'Bob', 'Charlie']) swaps index and columns incorrectly. pd.DataFrame(data=arr, names=['Height', 'Weight'], labels=['Alice', 'Bob', 'Charlie']) uses invalid parametersnamesandlabels. pd.DataFrame(arr, rows=['Alice', 'Bob', 'Charlie'], cols=['Height', 'Weight']) uses non-existentrowsandcolsparameters.Final Answer:
pd.DataFrame(arr, columns=['Height', 'Weight'], index=['Alice', 'Bob', 'Charlie']) -> Option AQuick Check:
Use columns= for columns, index= for rows [OK]
- Swapping index and columns parameters
- Using invalid parameter names like rows= or names=
- Forgetting to match index length to array rows
Ready to prove it?
Pass the test and this pattern moves unknown
