How to Slice a Dataframe in Python Using Indexes?

Estimated read time 2 min read

You can slice a DataFrame in Python using indexes by specifying the row and column indexes of the subset of data that you want to extract.

To slice a DataFrame in Python using indexes, you can use the .iloc[] method. The .iloc[] method is a location-based indexing method that allows you to select subsets of a DataFrame using integer indexes for both rows and columns.

Here’s an example of slicing a DataFrame using integer indexes:

import pandas as pd

# create a sample dataframe
data = {'name': ['John', 'Alice', 'Bob', 'Jane', 'Mary'], 'age': [25, 30, 35, 40, 45], 'gender': ['M', 'F', 'M', 'F', 'F']}
df = pd.DataFrame(data)

# slice the first two rows and first two columns
new_df = df.iloc[0:2, 0:2]
print(new_df)

In this example, the .iloc[] method is used to slice the first two rows and first two columns of the DataFrame df. The resulting slice is a new DataFrame containing the first two rows and columns:

    name  age
0   John   25
1  Alice   30

Note that the row and column indexes start at 0, and the ending index is not included in the slice.

You can also slice a DataFrame using a list of indexes. For example, to slice the 1st, 3rd, and 5th rows of the DataFrame, you can do the following:

# slice the 1st, 3rd, and 5th rows
new_df = df.iloc[[0, 2, 4], :]
print(new_df)

In this example, the .iloc[] method is used to slice the 1st, 3rd, and 5th rows of the DataFrame df. The resulting slice is a new DataFrame containing only the selected rows:

   name  age gender
0  John   25      M
2   Bob   35      M
4  Mary   45      F

Similarly, to slice the 2nd and 3rd columns of the DataFrame, you can do the following:

# slice the 2nd and 3rd columns
new_df = df.iloc[:, [1, 2]]
print(new_df)

In this example, the .iloc[] method is used to slice the 2nd and 3rd columns of the DataFrame df. The resulting slice is a new DataFrame containing only the selected columns:

   age gender
0   25      M
1   30      F
2   35      M
3   40      F
4   45      F

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply