📌  相关文章
📜  使用 Pandas 在给定的 Excel 表中查找损益

📅  最后修改于: 2022-05-13 01:54:25.227000             🧑  作者: 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']= None
data['Loss']= 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')
index_loss = data.columns.get_loc('Loss')
  
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]:
        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


输出 :

第 2 步:在 DataFrame 中为商店损益创建一个新列

Python3

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

输出 :

第 3 步:设置销售价格、成本价格、利润和损失的索引以访问 DataFrame 列

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')
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

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]:
        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

输出 :