Complete the code to create a DataFrame from a dictionary.
import pandas as pd data = {'name': ['Anna', 'Bob'], 'age': [25, 30]} df = pd.[1](data) print(df)
We use pd.DataFrame() to create a DataFrame from a dictionary. Other options like Series or list do not create a DataFrame.
Complete the code to create a DataFrame with specified columns order.
import pandas as pd data = {'name': ['Anna', 'Bob'], 'age': [25, 30]} df = pd.DataFrame(data, columns=[1]) print(df)
The columns parameter takes a list of column names in the order you want them to appear. Here, ['name', 'age'] matches the data keys.
Fix the error in the code to create a DataFrame from a list of lists.
import pandas as pd data = [['Anna', 25], ['Bob', 30]] df = pd.DataFrame([1], columns=['name', 'age']) print(df)
The variable data should be passed directly to pd.DataFrame(). Using braces or quotes causes errors.
Fill both blanks to create a DataFrame from a list of dictionaries and set the index.
import pandas as pd data = [{'name': 'Anna', 'age': 25}, {'name': 'Bob', 'age': 30}] df = pd.DataFrame([1]) df = df.set_index([2]) print(df)
We pass the list of dictionaries data to create the DataFrame. Then we set the index to the 'name' column to label rows by names.
Fill all three blanks to create a DataFrame from a dictionary, rename columns, and select a subset.
import pandas as pd data = {'n': ['Anna', 'Bob'], 'a': [25, 30], 'c': ['NY', 'LA']} df = pd.DataFrame([1]) df = df.rename(columns=[2]) df_subset = df.loc[:, [3]] print(df_subset)
First, create the DataFrame from data. Then rename columns using the dictionary mapping old to new names. Finally, select the subset of columns ['name', 'age'].