0
0
Pandasdata~20 mins

Creating DataFrame from NumPy array in Pandas - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
NumPy to DataFrame Master
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 code creating a DataFrame?
Consider the following code that creates a DataFrame from a NumPy array. What will be the output DataFrame?
Pandas
import numpy as np
import pandas as pd

arr = np.array([[1, 2], [3, 4]])
df = pd.DataFrame(arr, columns=['A', 'B'])
print(df)
A
   A  B
1  1  2
2  3  4
B
   A  B
0  1  2
1  3  4
C
   A  B
0  2  1
1  4  3
D
   0  1
0  1  2
1  3  4
Attempts:
2 left
💡 Hint
Look at how the columns parameter names the columns and the default index.
data_output
intermediate
1:30remaining
How many rows and columns does this DataFrame have?
Given this code creating a DataFrame from a NumPy array, how many rows and columns does the resulting DataFrame have?
Pandas
import numpy as np
import pandas as pd

arr = np.arange(12).reshape(3, 4)
df = pd.DataFrame(arr)
print(df.shape)
A(3, 4)
B(4, 3)
C(12, 1)
D(1, 12)
Attempts:
2 left
💡 Hint
The reshape method sets rows and columns as (3, 4).
🔧 Debug
advanced
2:00remaining
What error does this code raise?
This code tries to create a DataFrame from a NumPy array with mismatched columns. What error will it raise?
Pandas
import numpy as np
import pandas as pd

arr = np.array([[1, 2], [3, 4]])
df = pd.DataFrame(arr, columns=['A', 'B', 'C'])
ANo error, DataFrame created with NaN in missing column
BTypeError: columns must be a list of integers
CIndexError: list index out of range
DValueError: 3 columns passed, passed data had 2 columns
Attempts:
2 left
💡 Hint
Check if the number of columns matches the array shape.
🚀 Application
advanced
2:30remaining
Which option produces a DataFrame with custom row labels?
You want to create a DataFrame from a NumPy array with columns 'X', 'Y' and row labels 'a', 'b'. Which code does this correctly?
Pandas
import numpy as np
import pandas as pd

arr = np.array([[10, 20], [30, 40]])
Apd.DataFrame(arr, index=['X', 'Y'], columns=['a', 'b'])
Bpd.DataFrame(arr, columns=['a', 'b'], index=['X', 'Y'])
Cpd.DataFrame(arr, columns=['X', 'Y'], index=['a', 'b'])
Dpd.DataFrame(arr, index=['a', 'b'])
Attempts:
2 left
💡 Hint
Columns are the names of the data columns, index is for row labels.
🧠 Conceptual
expert
3:00remaining
What happens if you create a DataFrame from a 3D NumPy array?
You try to create a DataFrame from a 3-dimensional NumPy array. What will happen?
Pandas
import numpy as np
import pandas as pd

arr = np.ones((2, 2, 2))
df = pd.DataFrame(arr)
ARaises ValueError: Must pass 2-d input
BCreates a DataFrame flattening the array automatically
CCreates a DataFrame with nested arrays in cells
DCreates a DataFrame with default integer columns and rows
Attempts:
2 left
💡 Hint
DataFrames require 2D data structures.