How to slice a Pandas DataFrame

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

You can use the .loc[], .iloc[], and [] accessors to slice a Pandas DataFrame. Here's an example of how you can use these accessors to select specific rows and columns:

.loc[]: Selects data by label. For example, you can select all rows with a specific label:

df.loc[1:3] # will select all rows between 1 and 3 including 1 and 3

.iloc[]: Selects data by integer position. For example, you can select the first three rows:

df.iloc[0:3] # will select first three rows

[]: Selects data by label or integer position. For example, you can select a specific column:

df['Name'] # will select 'Name' column

You can also use both .loc[] and [] together to select specific rows and columns. For example, you can select the 'Name' column for the first three rows:

df.loc[0:2, 'Name'] # will select first three rows of 'Name' column

You can also use slicing on the rows and columns together

df.loc[:, 'Name':'Age'] # will select all rows for columns 'Name' and 'Age'

You can also use .iloc[] to select specific rows and columns using integer positions:

df.iloc[:, 1:3] # will select all rows for columns with integer position 1 and 2

It's also possible to use boolean indexing to select specific rows and columns:

df.loc[df['Salary'] > 55000, ['Name', 'Age']]

In all the examples above, the returned DataFrame will include only the selected rows and columns.

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.