📜  使用 Pandas 中的查询方法使用复杂条件进行选择

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

使用 Pandas 中的查询方法使用复杂条件进行选择

在本文中,让我们讨论如何使用 Pandas 中的 Query() 方法选择复杂条件。在 Pandas for Selecting with complex conditions using the query 中,首先,我们在 pandas.Dataframe() 的帮助下创建数据框并将其存储为一个变量,然后在 query() 方法的帮助下我们可以选择复杂的标准。在 pandas.Dataframe.loc() 的帮助下,我们可以通过传递数据帧的索引来查找数据帧的详细信息。
示例 1:

Python3
import pandas as pd
  
df = pd.DataFrame([[10, 20, 30, 40], [70, 14, 21, 80], 
                   [55, 15, 80, 12]],
                    
                  columns=['GFG_USER_1', 'GFG_USER_2',
                           'GFG_USER_3', 'GFG_USER_4'],
                    
                  index=['Practice1', 'Practice2', 'Practice3'])
  
print(df, "\n")
  
# Filter data using query method
df1 = df.loc[df.query(
    'GFG_USER_1 <= 80 & GFG_USER_2 > 10 & \
    GFG_USER_3 < 50 &  GFG_USER_4 == 80').index]
  
print(df1)


Python3
import pandas as pd
  
df = pd.DataFrame([[100, 200, 300], [70, 140, 210], 
                   [55, 150, 180]],
                    
                  columns=['PAK', 'AUS', 'IND'],
                    
                  index=['Match1', 'Match2', 'Match3'])
  
print(df, "\n")
  
# Filter data using query method
df1 = df.loc[df.query('PAK <= 80 & AUS > 100 & IND < 250').index]
  
print(df1)


Python3
import pandas as pd
  
df = pd.DataFrame([[1000, 2000, 3000, 4000], [7000, 1400, 2100, 2800], 
                   [5500, 1500, 800, 1200]],
                    
                  columns=['DSA_Self_Paced', 'OOPS', 'DBMS', 'System_design'],
                    
                  index=['Sale1', 'Sale2', 'Sale3'])
  
print(df, "\n")
  
# Filter data using query method
df1 = df.loc[df.query(
    'DSA_Self_Paced <= 6000 & OOPS > 1400 & DBMS < 1500 \
    &  System_design == 1200').index]
  
print(df1)


输出:

示例2:

蟒蛇3

import pandas as pd
  
df = pd.DataFrame([[100, 200, 300], [70, 140, 210], 
                   [55, 150, 180]],
                    
                  columns=['PAK', 'AUS', 'IND'],
                    
                  index=['Match1', 'Match2', 'Match3'])
  
print(df, "\n")
  
# Filter data using query method
df1 = df.loc[df.query('PAK <= 80 & AUS > 100 & IND < 250').index]
  
print(df1)

输出:

示例 3:

蟒蛇3

import pandas as pd
  
df = pd.DataFrame([[1000, 2000, 3000, 4000], [7000, 1400, 2100, 2800], 
                   [5500, 1500, 800, 1200]],
                    
                  columns=['DSA_Self_Paced', 'OOPS', 'DBMS', 'System_design'],
                    
                  index=['Sale1', 'Sale2', 'Sale3'])
  
print(df, "\n")
  
# Filter data using query method
df1 = df.loc[df.query(
    'DSA_Self_Paced <= 6000 & OOPS > 1400 & DBMS < 1500 \
    &  System_design == 1200').index]
  
print(df1)

输出: