How to slice a Pandas DataFrame

1 min

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.