Найдите прибыль и убыток в данном листе Excel с помощью Pandas

Опубликовано: 27 Марта, 2022

В этих статьях мы обсудим, как извлечь данные из файла Excel и найти прибыль и убыток по заданным данным. Предположим, что наш файл Excel выглядит так, как будто нам нужно извлечь из столбца продажную цену и себестоимость, найти прибыль и убыток и сохранить их в новом столбце DataFrame.

Чтобы использовать файл Excel, щелкните здесь.

Итак, давайте обсудим подход:

Шаг 1. Импортируйте необходимый модуль и считайте данные из 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

Выход :

Step 2: Create a new column in DataFrame for store Profit and Loss

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

Step 4: Compute profit and loss according to there each column index.

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

Выход :

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.