Slice Pandas DataFrame by Row

Given a pandas dataframe, we have to slice pandas dataframe by row. By Pranit Sharma Last updated : October 02, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Rows in pandas are the different cell (column) values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows are generally marked with the index number but in pandas, we can also assign index names according to the needs. In pandas, we can create, read, update, and delete a column or row value.

Problem statement

Suppose, we are given a DataFrame with multiple columns and multiple rows. We need to select some rows at a time to draw some useful insights and then we will slice the DataFrame with some other rows.

Slicing a Pandas DataFrame by Row

We will achieve this task with the help of the loc property of pandas. The pandas.DataFrame.loc property is a type of data selection method which takes the name of a row or column as a parameter. To perform various operations using the pandas.DataFrame.loc property, we need to pass the required condition of rows and columns in order to get the filtered data.

Let us understand with the help of an example,

Python program to slice pandas dataframe by row

# Importing pandas package
import pandas as pd

# Import numpy package
import numpy as np

# Defining a function
def function(arr):
    return np.mean(arr), np.std(arr), np.amax(arr)

# Creating dictionary
d = {'A': [10,20,30,40,50], 'B': [40,50,60,70,80]}

# Creating DataFrame
df = pd.DataFrame(d)

# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")

# Slicing with rows
res1 = df.loc[[0,2,4]]
res2 = df.loc[1:3]

# Display result
print("Result 1:\n",res1,"\n")
print("Result 2:\n",res2,"\n")

Output

The output of the above program is:

Example: Slice Pandas DataFrame by Row

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.