📜  如何从 Pandas DataFrame 中选择行?

📅  最后修改于: 2022-05-13 01:54:57.351000             🧑  作者: Mango

如何从 Pandas DataFrame 中选择行?

pandas.DataFrame.loc是一个函数,用于根据提供的条件从 Pandas DataFrame 中选择行。在本文中,让我们学习根据一些条件从 Pandas DataFrame 中选择行。

示例 1:

# Importing pandas as pd
from pandas import DataFrame
  
# Creating a data frame
cart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'],
        'Type': ['Electronic', 'HomeAppliances', 'Electronic', 
                 'HomeAppliances', 'Sports'],
        'Price': [10000, 35000, 50000, 30000, 799]
       }
  
df = DataFrame(cart, columns = ['Product', 'Type', 'Price'])
  
# Print original data frame
print("Original data frame:\n")
print(df)
  
# Selecting the product of Electronic Type
select_prod = df.loc[df['Type'] == 'Electronic']
  
print("\n")
  
# Print selected rows based on the condition
print("Selecting rows:\n")
print (select_prod)

输出:

示例 2:

# Importing pandas as pd
from pandas import DataFrame
  
# Creating a data frame
cart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'],
        'Type': ['Electronic', 'HomeAppliances', 'Electronic',
                 'HomeAppliances', 'Sports'],
        'Price': [10000, 35000, 50000, 30000, 799]
       }
  
df = DataFrame(cart, columns = ['Product', 'Type', 'Price'])
  
# Print original data frame
print("Original data frame:\n")
print(df)
  
# Selecting the product of HomeAppliances Type
select_prod = df.loc[df['Type'] == 'HomeAppliances']
  
print("\n")
  
# Print selected rows based on the condition
print("Selecting rows:\n")
print (select_prod)

输出:

示例 3:

# Importing pandas as pd
from pandas import DataFrame
  
# Creating a data frame
cart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'],
        'Type': ['Electronic', 'HomeAppliances', 'Electronic',
                 'HomeAppliances', 'Sports'],
        'Price': [10000, 35000, 50000, 30000, 799]
       }
  
df = DataFrame(cart, columns = ['Product', 'Type', 'Price'])
  
# Print original data frame
print("Original data frame:\n")
print(df)
  
# Selecting the product of Price greater 
# than or equal to 25000
select_prod = df.loc[df['Price'] >= 25000]
  
print("\n")
  
# Print selected rows based on the condition
print("Selecting rows:\n")
print (select_prod)

输出:

示例 4:

# Importing pandas as pd
from pandas import DataFrame
  
# Creating a data frame
cart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'],
        'Type': ['Electronic', 'HomeAppliances', 'Electronic',
                 'HomeAppliances', 'Sports'],
        'Price': [10000, 35000, 30000, 30000, 799]
       }
  
df = DataFrame(cart, columns = ['Product', 'Type', 'Price'])
  
# Print original data frame
print("Original data frame:\n")
print(df)
  
# Selecting the product of Price not 
# equal to 30000
select_prod = df.loc[df['Price'] != 30000]
  
print("\n")
  
# Print selected rows based on the condition
print("Selecting rows:\n")
print (select_prod)

输出: