Q.We can add a new row to a DataFrame DF using the ______ method. (A) DF.add() (B) DF.loc[] (C) DF.loc() (D) DF.addloc[]
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →To add a new row to a Pandas DataFrame, you use the .loc[] indexer to assign data to a new, non-existent index label. The correct option is (B).
Concept and Intuition
A Pandas DataFrame is essentially a two-dimensional, labeled data structure with columns of potentially different types. Think of it like a spreadsheet or a SQL table. Each row and each column has a label (its index).
When you want to add a new row, you're essentially telling Pandas, "Hey, I want to put this new data at this specific row label." Pandas needs a way to identify where this new row should go. Since DataFrames are label-indexed, the most direct and idiomatic way to do this is by using a label-based indexer.
The .loc[] accessor in Pandas is designed precisely for label-based indexing. It allows you to select data by row and column labels. When you use .loc[] to assign data to a row label that does not yet exist in the DataFrame's index, Pandas understands this as an instruction to create a new row with that label and populate it with the provided data.
Step-by-step Solution
-
Understand the Goal: We need to add a new row to an existing DataFrame. This means we're not modifying an existing row, but rather extending the DataFrame with additional data.
-
Evaluate Option (A)
DF.add():The
DF.add()method in Pandas is used for element-wise addition of DataFrames or Series. For example,df1.add(df2)would add corresponding elements ofdf1anddf2. It is not designed for adding new rows or columns to a DataFrame.import pandas as pd df1 = pd.DataFrame({'A': [1, 2]}, index=[0, 1]) df2 = pd.DataFrame({'A': [3, 4]}, index=[0, 1]) result = df1.add(df2) # result is DataFrame({'A': [4, 6]}, index=[0, 1]) # This does not add new rows. -
Evaluate Option (B)
DF.loc[]:The
.loc[]accessor is the primary label-based indexer for DataFrames. It allows you to select rows and columns by their labels. When you assign a new list or Series of values to a non-existent row label using.loc[], Pandas automatically creates that new row.TipDF.loc[]is versatile. It can be used to select existing rows/columns, or to create new ones if the label doesn't exist. This "assignment to a new label creates it" behavior is key for adding rows.Consider a DataFrame
df:import pandas as pd df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]}, index=['A', 'B']) print("Original DataFrame:") …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.