📜  使用 Pandas 在给定的 Excel 表中查找损益百分比

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

使用 Pandas 在给定的 Excel 表中查找损益百分比

在这些文章中,让我们讨论如何从 Excel 文件中提取数据并找到给定数据的利润百分比和亏损百分比。假设我们的 Excel 文件看起来像这样,我们必须从列中提取 Selling Price 和 Cost Price 并找到利润百分比和损失百分比并将其存储到新的 DataFrame 列中。

要获取上面使用的 excel 文件,请单击此处。

所以,让我们讨论一下方法:

第一步:导入需要的模块并从excel中读取数据。

Python3
# 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


Python3
# Create column for profit and loss
data['Profit percent']= None
data['Loss percent'] = None
data


Python3
# 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)


Python3
# 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


输出 :

第 2 步:在 DataFrame 中为商店利润百分比和损失百分比创建一个新列。

Python3

# Create column for profit and loss
data['Profit percent']= None
data['Loss percent'] = None
data

输出 :

步骤 3:设置售价、成本价、利润百分比和损失百分比的指数。

Python3

# 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)%

Python3

# 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

输出 :