› Forums › Python › Pandas (Python library) › Why Do We Use Double Brackets in home_data[[…]]?
- This topic is empty.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
May 8, 2026 at 11:45 pm #6548
Understanding the Error with
feature_namesin PandasThe error is happening because you mixed up:
- a list of column names
- with the actual DataFrame selection
Letβs understand carefully.
β Your Current Code
You wrote something like:
feature_names = home_data[['LotArea', 'YearBuilt', ...]]This creates a DataFrame, not a list.
But the exercise expects:
feature_namesto be a Python list of column names.
β Correct Version
# Create the list of features feature_names = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd'] # Select data corresponding to features X = home_data[feature_names]
π Why This Works
Step 1 β Create a Python List
feature_names = ['LotArea', 'YearBuilt']This is ONLY a list:
['LotArea', 'YearBuilt']Not actual dataset data yet.
Step 2 β Use the List to Select Columns
X = home_data[feature_names]This tells pandas:
βUse these column names from the DataFrame.β
π§ Important Beginner Concept
These are DIFFERENT things:
1οΈβ£ A Python List
['LotArea', 'YearBuilt']Just text labels.
2οΈβ£ A DataFrame Selection
home_data[['LotArea', 'YearBuilt']]Actual table data extracted from the dataset.
π₯ Why Your Error Happened
You effectively did:
feature_names = ACTUAL_DATAFRAMEThen later:
X = feature_namesThe checker expected:
feature_namesβ listXβ DataFrame
But both became DataFrames.
π Correct Mental Flow
First: Create Labels
feature_names = ['LotArea', 'YearBuilt']
Then: Use Labels to Extract Data
X = home_data[feature_names]
π§© Visualization
Dataset (
home_data)LotArea YearBuilt Price 5000 2001 200000
List of Feature Names
['LotArea', 'YearBuilt']
Selected Data (
X)LotArea YearBuilt 5000 2001
π Final Takeaway
β WRONG
feature_names = home_data[['LotArea', 'YearBuilt']]because this stores actual data.
β CORRECT
feature_names = ['LotArea', 'YearBuilt'] X = home_data[feature_names]because:
- first line creates labels
- second line extracts columns using those labels
-
AuthorPosts
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.
