Python Pandas——如何基于条件选择DataFrame行
我们可以设置条件并提取DataFrame行。这些条件可以使用逻辑运算符甚至关系运算符来设置。
首先,导入所需的pandas库−
import pandas as pd
让我们创建一个DataFrame并读取我们的CSV文件−
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesRecords.csv")
使用关系运算符提取注册价格小于1000的数据帧行−
dataFrame[dataFrame.Reg_Price < 1000]
实例
代码如下−
import pandas as pd # reading csv file dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesRecords.csv") print("DataFrame...\n",dataFrame) # count the rows and columns in a DataFrame print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape) # fetching dataframe rows with registration price less than 1000 resData = dataFrame[dataFrame.Reg_Price < 1000] print("DataFrame...\n",resData)
输出
这将生成以下输出−
DataFrame... Car Date_of_Purchase Reg_Price 0 BMW 10/10/2020 1000 1 Lexus 10/12/2020 750 2 Audi 10/17/2020 750 3 Jaguar 10/16/2020 1500 4 Mustang 10/19/2020 1100 5 Lamborghini 10/22/2020 1000 Number of rows and column in our DataFrame = (6, 3) DataFrame... Car Date_of_Purchase Reg_Price 1 Lexus 10/12/2020 750 2 Audi 10/17/2020 750
广告