在Pandas DataFrame中应用if条件的方法

在Pandas DataFrame中应用if条件的方法

一般来说,在Pandas DataFrame上,if条件可以按列、按行或按单个单元格来应用。进一步的文件用例子说明了每一种情况。

首先,我们将创建以下数据框架。

# importing pandas as pd
import pandas as pd
  
# create the DataFrame
df = pd.DataFrame({
    'Product': ['Umbrella', 'Matress', 'Badminton', 
                'Shuttle', 'Sofa', 'Football'],
    'MRP': [1200, 1500, 1600, 352, 5000, 500],
    'Discount': [0, 10, 0, 10, 20, 40]
})
  
# display the DataFrame
print(df)

输出 :

在Pandas DataFrame中应用if条件的方法

例子1:列值的if条件(图元)。if条件可以应用在列值上,比如当有人问到MRP为<=2000 and Discount >0</=2000>的所有项目时<=2000 and Discount >,下面的代码就会这样做。同样地,任何数量的条件都可以应用在数据框架的任何数量的属性上。
</=2000>

# if condition with column conditions given
# the condition is if MRP of the product <= 2000 
# and discount > 0 show me those items
df[(df['MRP'] <= 2000) & (df['Discount'] > 0)]

输出 :

在Pandas DataFrame中应用if条件的方法

例子2 :如果条件是行值(图元)。这可以作为列值条件的一个特殊案例。如果给出一个元组(Sofa, 5000, 20)并在DataFrame中找到它,可以像这样做。

# if condition with row tuple given
df[(df['Product'] == 'Sofa') & (df['MRP'] == 5000) & (df['Discount']== 20)]

输出 :

在Pandas DataFrame中应用if条件的方法

例子3 :使用Lambda函数。Lambda函数接受一个输入,并根据某个条件返回一个结果。它可以用来对Pandas DataFrame中的每一列元素应用某个函数。下面的例子使用Lambda函数为折扣值设置了20的上限,即如果任何单元格的折扣值>20,则将其设置为20。

# importing pandas as pd 
import pandas as pd 
  
# Create the dataframe 
df = pd.DataFrame({
    'Product': ['Umbrella', 'Matress', 'Badminton', 
                'Shuttle', 'Sofa', 'Football'],
    'MRP': [1200, 1500, 1600, 352, 5000, 500],
    'Discount': [0, 10, 0, 10, 20, 40]
})
  
# Print the dataframe 
print(df) 
  
# If condition on column values using Lambda function 
df['Discount'] = df['Discount'].apply(lambda x : 20 if x > 20 else x)
print(df)

输出 :

在Pandas DataFrame中应用if条件的方法

在Pandas DataFrame中应用if条件的方法

示例4:使用iloc()或loc()函数:iloc()和loc()函数都是用来从一个数据框架中提取子数据框架。子DataFrame可以是任何东西,从一个单元格到整个表格。iloc()通常在我们知道行和列的索引范围时使用,而loc()用于标签搜索。

下面的例子显示了这两个函数在数据框架中的使用情况。这里有一个索引为[2, 1]的单元格,是羽毛球产品的MRP。

# If condition on a cell value using iloc() or loc() functions
# iloc() is based on index search and loc() based on label search
  
# using iloc()
if df.iloc[2, 1] > 1500:
  print("Badminton Price > 1500")
else:
  print("Badminton Price < 1500")
  
# using loc()
print(df.loc[2, 'MRP'])
if df.iloc[2, 'MRP'] > 1500:         
  print("Badminton Price > 1500")
else:
  print("Badminton Price < 1500")

输出 :

在Pandas DataFrame中应用if条件的方法

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程