ADVERTISEMENT
ADVERTISEMENT

Select Pandas rows based on list index

Given a Pandas DataFrame, we have to select rows based on list index.
Submitted by Pranit Sharma, on June 18, 2022

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 the data.

When it comes to selecting a row or column value, we always use pandas.DataFrame.loc property or pandas.DataFrame.iloc property.

To select pandas rows based on the list index, we will select an index of those rows with certain sequence numbers which indicate a list.

If we want row 1 and row 3 as a list, then we will pass [1,3] in a list and then we will select all columns by using ':'.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python code to select Pandas rows based on list index

# Importing pandas package
import pandas as pd

# Creating a DataFrame
df = pd.DataFrame({
    'Brand':['Samsung','Motorola','Redmi'],
    'Series':['M','E','A'],
    'Price_range':['15k-25k','10k-20k','10k-15k']
})

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

# Selecting row based on list
ind_list = [0, 2]

result = df.iloc[ind_list]

print("Selected rows:\n",result)

Output:

Example: Select Pandas rows

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.