
How to Access Columns by Name in Pandas (Python)
↓ Code Available Below! ↓
This video shows how to access the columns of a pandas data frame using the name of the column. Although base python data structures like lists don't have index names, data frames have named columns that often give information about what is in the column, so it is usually more natural to select columns by name than a numeric index.
If you find this video useful, like, share and subscribe to support the channel!
► Subscribe: https://www.youtube.com/c/DataDaft?sub_confirmation=1
Code used in this Python Code Clip:
import pandas as pd
import statsmodels.api as sm #(To access mtcars dataset)
mtcars = sm.datasets.get_rdataset("mtcars", "datasets", cache=True).data
mtcars.head()
# Access a column with direct indexing
mtcars["mpg"]
# Access a column with direct dot indexing
mtcars.mpg
# Access multiple columns by name
mtcars[["mpg","cyl","hp"]]
# Access multiple columns by name with a subset of rows by row name
mtcars.loc[["Mazda RX4 Wag","Valiant", "Porsche 914-2"],["mpg","cyl","hp"]]
# Access multiple columns by name with a subset of rows by row index
mtcars.loc[mtcars.index[[2,6,26]],["mpg","cyl","hp"]]
* Note: YouTube does not allow greater than or less than symbols in the text description, so the code above will not be exactly the same as the code shown in the video! I will use Unicode large < and > symbols in place of the standard sized ones. .
⭐ Kite is a free AI-powered coding assistant that integrates with popular editors and IDEs to give you smart code completions and docs while you’re typing. It is a cool application of machine learning that can also help you code faster! Check it out here: https://www.kite.com/get-kite/?utm_medium=referral&utm_source=youtube&utm_campaign=datadaft&utm_content=description-only