使用Pandas查找给定的Excel表格中的利润和损失
在这些文章中,我们将讨论如何从Excel文件中提取数据并在给定的数据中找到利润和损失。假设我们的Excel文件是这样的,那么我们必须从列中提取销售价格和成本价格,找到利润和损失,并将其存储到一个新的DataFrame列。
因此,让我们来讨论一下这个方法。
第1步:导入所需的模块并从Excel中读取数据。
# importing module
import pandas as pd;
# Creating df
# Reading data from Excel
data = pd.read_excel("excel_work/book_sample.xlsx");
print("Original DataFrame")
data
输出 :
第2步:在数据框架中为商店的利润和损失创建一个新列
# Create column for profit and loss
data['Profit']= None
data['Loss']= None
data
输出 :
第3步:为销售价格、成本价格、利润和损失设置索引,以访问数据框架列。
# set index
index_selling = data.columns.get_loc('Selling Price')
index_cost = data.columns.get_loc('Cost price')
index_profit = data.columns.get_loc('Profit')
index_loss = data.columns.get_loc('Loss')
print(index_selling, index_cost, index_profit, index_loss)
输出 :
2 3 4 5
第四步:根据每一列索引计算利润和损失。
Profit = Selling price - Cost price
Loss = Cost price - Selling price
# Loop for accessing every index in DataFrame
# and compute Profit and loss
# and store into new column in DataFrame
for row in range(0, len(data)):
if data.iat[row, index_selling] > data.iat[row, index_cost]:
data.iat[row, index_profit] = data.iat[row,
index_selling] - data.iat[row, index_cost]
else:
data.iat[row, index_loss] = data.iat[row,
index_cost]-data.iat[row, index_selling]
data
输出 :