Selecting Columns and Rows
When analyzing data, you often need to focus on specific parts — like selecting a column of interest or checking a few rows.
In Pandas, this is done using column labels, row positions, and index labels.
Selecting Columns
The most reliable way to select a column is with square brackets and the column name:
df["Population"]
This returns a Series. You can also assign it to a variable, combine it with conditions, or perform calculations.
Avoid using
df.ColumnName
(dot notation). It works only when column names are valid Python identifiers.
Selecting Rows
To select rows, use either:
iloc[]
for position-based accessloc[]
for label-based access
df.iloc[0]
df.loc[0]
These return a row as a Series.
Selecting a Specific Value
You can combine row and column selection to get a single cell value:
df.loc[0, "Population"]
This gives you the value at row 0, column "Population".
Summary Table
Selector | Access Type | Example |
---|---|---|
df["col"] | Column by name | df["Age"] |
df.iloc[i] | Row by position | df.iloc[3] |
df.loc[i] | Row by label | df.loc[3] |
df.loc[i, "col"] | Cell | df.loc[3, "Age"] |
What’s Next?
Now that you know how to select data, let’s filter it using conditions!
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.