Ограниченный выбор строк с заданным столбцом в Pandas | Python

Опубликовано: 27 Марта, 2022

Methods in Pandas like iloc[], iat[] are generally used to select the data from a given dataframe. In this article, we will learn how to select the limited rows with given columns with the help of these methods.

Example 1: Select two columns

# Import pandas package 
import pandas as pd 
    
# Define a dictionary containing employee data 
data = {"Name":["Jai", "Princi", "Gaurav", "Anuj"], 
        "Age":[27, 24, 22, 32], 
        "Address":["Delhi", "Kanpur", "Allahabad", "Kannauj"], 
        "Qualification":["Msc", "MA", "MCA", "Phd"]} 
    
# Convert the dictionary into DataFrame  
df = pd.DataFrame(data) 
    
# select three rows and two columns 
print(df.loc[1:3, ["Name", "Qualification"]])

Выход:

 Имя Квалификация
1 Princi MA
2 Gaurav MCA
3 Анудж, доктор философии

Example 2: First filtering rows and selecting columns by label format and then Select all columns.

# Import pandas package 
import pandas as pd 
    
# Define a dictionary containing employee data 
data = {"Name":["Jai", "Princi", "Gaurav", "Anuj"], 
        "Age":[27, 24, 22, 32], 
        "Address":["Delhi", "Kanpur", "Allahabad", "Kannauj"], 
        "Qualification":["Msc", "MA", "MCA", "Phd"
       
  
# Convert the dictionary into DataFrame  
df = pd.DataFrame(data) 
    
# .loc DataFrame method 
# filtering rows and selecting columns by label format 
# df.loc[rows, columns] 
# row 1, all columns 
print(df.loc[0, :] )

Выход:

Address          Delhi
Age                 27
Name               Jai
Qualification      Msc
Name: 0, dtype: object

Example 3: Select all or some columns, one to another using .iloc.

# Import pandas package 
import pandas as pd 
    
# Define a dictionary containing employee data 
data = {"Name":["Jai", "Princi", "Gaurav", "Anuj"], 
        "Age":[27, 24, 22, 32], 
        "Address":["Delhi", "Kanpur", "Allahabad", "Kannauj"], 
        "Qualification":["Msc", "MA", "MCA", "Phd"]} 
    
# Convert the dictionary into DataFrame  
df = pd.DataFrame(data) 
    
# iloc[row slicing, column slicing] 
print(df.iloc [0:2, 1:3] )

Выход:

 Возраст Имя
0 27 Джай
1 24 Princi

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.