使用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步:在DataFrame中为商店的利润百分比和损失百分比创建一个新列。
# Create column for profit and loss
data['Profit percent']= None
data['Loss percent'] = 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 percent')
index_loss = data.columns.get_loc('Loss percent')
print(index_selling, index_cost, index_profit, index_loss)
输出 :
2 3 4 5
第四步:根据每一列的指数计算利润和损失百分比。
profit = (SP) - (CP)
profit % = (profit/ CP × 100)%
Loss = (CP) - (SP)
Loss % = (loss/ CP × 100)%
# 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]:
profit = data.iat[row, index_selling] - data.iat[row, index_cost]
data.iat[row, index_profit] = (profit/data.iat[row, index_cost]*100)
else:
loss = abs(data.iat[row, index_cost]-data.iat[row, index_selling])
data.iat[row, index_loss] = (loss/data.iat[row, index_cost]*100)
data
输出 :