Given the following code, what will be the column names of the resulting DataFrame?
import pandas as pd data = [[1, 2], [3, 4]] df = pd.DataFrame(data, columns=['A', 'B']) print(df.columns.tolist())
import pandas as pd data = [[1, 2], [3, 4]] df = pd.DataFrame(data, columns=['A', 'B']) print(df.columns.tolist())
Look at the columns parameter in the DataFrame constructor.
The columns parameter explicitly sets the column names. Here, it is set to ['A', 'B'], so the DataFrame columns will be named 'A' and 'B'.
Consider this code snippet. What will be the index of the DataFrame?
import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data, index=['x', 'y'])
print(df.index.tolist())import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data, index=['x', 'y']) print(df.index.tolist())
Check the index parameter in the DataFrame constructor.
The index parameter sets the row labels. Here, it is set to ['x', 'y'], so the DataFrame index will be ['x', 'y'].
Which of the following DataFrame constructions will cause an error?
import pandas as pd data = [[1, 2], [3, 4]]
Check the type expected for the columns parameter.
The columns parameter expects a list of strings, not a single string with commas. Option B passes a single string 'A,B' which causes a ValueError in pandas.
What happens when the number of columns and data columns do not match?
import pandas as pd data = [[1, 2], [3, 4]] df = pd.DataFrame(data, columns=['A', 'B', 'C']) print(df)
import pandas as pd data = [[1, 2], [3, 4]] df = pd.DataFrame(data, columns=['A', 'B', 'C']) print(df)
Check if pandas allows columns list length to differ from data width.
Pandas raises a ValueError if the number of columns specified does not match the number of data columns.
Which of the following is the best reason to specify both columns and index explicitly when creating a DataFrame?
Think about how labels help when working with data.
Specifying columns and index explicitly gives clear labels to rows and columns, making data easier to understand and access.