2|PYTHON – Little Chicken

BYU Student Author: @Jae
Reviewers: @Nate, @klayton, @TylerBooth
Estimated Time to Solve: 20 minutes

We provide the solution to this challenge using:

Development Environment (IDE). The challenge requires the pandas library.

Need a program? Click here.

Overview
Little Chicken is a local fried chicken stand owned by your friend, Tom. Tom knows a lot about fried chicken, but not so much about business. In an attempt to boost his sales, Tom recently purchased a mini fridge. The refrigerator is consistently stocked with various beverages for his customers to take free of charge. Tom does not like to be controlling, so he allows his customers to take as many beverages as they need. Since purchasing the mini fridge, Tom has noticed a considerable increase in fried chicken sales but is concerned at how often he also restocks drinks.

Tom would like to evaluate the current state of his sales. He has been keeping an eye on how many drinks customers take each time they buy some chicken, recording the number of bottles alongside the quantity of chicken in their order. Tom is also interested in knowing whether his mini fridge decision has been more profitable for his stand. He has provided you with data on chicken order quantities before and after the purchase of the minifridge for comparison.

Tom purchases and sells his chicken for $0.99 and $3.99 per piece, respectively, and spends an average of $1.59 per bottle on drinks.

Instructions
Using the datafile linked below, compute the information Tom needs to evaluate the current state of his stand. Tom will need to know the following:

  • Total Sales for both periods (Before/After the purchase of the mini fridge)
  • Total Expenses for both periods, and
  • Total Net Income (Profitability) for both periods

Do you think the mini fridge strategy is effective? What changes would you like Tom to make?

Data Files

Alternatively, this file can also be directly called by using the following code after importing pandas as pd:

df=pd.read_csv('https://byu.box.com/shared/static/rcuvuky4qmgs8lukrlia4w5kw8c4hm9w') 
Suggestions and Hints
  • Net Income = Sales - Expenses
  • Since Tom didn’t own a mini fridge at the time of some chicken sales, you can assume that the drink expenses for this period were zero.
  • separating the before/after sales column may help with calculating each total sales figure

Solution

Challenge2c_Solution_Image

Solution Code
import pandas as pd 
# import data and create price/expense variables 
df = pd.read_csv('https://byu.box.com/shared/static/rcuvuky4qmgs8lukrlia4w5kw8c4hm9w') 
chicken_price = 3.99 
chicken_exp = 0.99 
drink_exp = 1.59 

# Seperate the Before Period sales from the After Period 
before_sales = df['Chicken Sold'][pd.isnull(df['Drinks Given'])].reset_index(drop=True) 
after_sales = df['Chicken Sold'][pd.isnull(df['Drinks Given'])==False] 
drinks_given = df['Drinks Given'][pd.isnull(df['Drinks Given'])==False] 

# Add new columns to dataframe 
df['before_sales'] = before_sales 
df['after_sales'] = after_sales 
df['drinks_given'] = drinks_given 

# Remove original data columns 
df = df.drop(columns=['Chicken Sold','Drinks Given']).dropna() 

# Perform calculations 
total_sales_before = sum(df['before_sales'])*chicken_price 
total_expense_before = sum(df['before_sales'])*chicken_exp 
net_income_before = total_sales_before - total_expense_before 

total_sales_after = sum(df['after_sales'])*chicken_price 
total_expense_after = (sum(df['after_sales'])*chicken_exp) + (sum(df['drinks_given'])*drink_exp) 
net_income_after = total_sales_after - total_expense_after 

# output information for Tom 
print(f'Before\nTotal Sales: ${round(total_sales_before,2)}') 
print(f'Total Expense: $({round(total_expense_before,2)})') 
print(f'Net Income: ${round(net_income_before,2)}') 

print(f'\nAfter\nTotal Sales: ${round(total_sales_after,2)}') 
print(f'Total Expense: $({round(total_expense_after,2)})') 
print(f'Net Income: ${round(net_income_after,2)}') 

Solution Video: Challenge 2|PYTHON – Little Chicken

I outputted my results to a bar chart:

Looks like Little Chicken is SLIGHTLY better in terms of profit after ordering the fridge (assuming that our data reflects the same time span for before fridge and after fridge). However, its profit margin dropped from 75.2% to 53.9%. So although his decision to buy a fridge may be good from a cash flow perspective, he may be sacrificing long-term profitability.

Here’s my code (I had help from ChatGPT on the bar chart :slight_smile:)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('C:\\Users\\Mitch.Frei\\OneDrive - Connor Group, Inc\\Documents\\Python\\Challenge2c_Dataset_Little_Chicken.csv')

df['Cost per Chicken'] = 0.99
df['Sales Price per Chicken'] = 3.99
df['Cost per Drink'] = 1.59
df['Sales'] = df['Chicken Sold']*df['Sales Price per Chicken']
df['Expenses'] = np.where(df['Drinks Given'].isnull(), -(df['Chicken Sold']*df['Cost per Chicken']), -((df['Chicken Sold']*df['Cost per Chicken']) + (df['Drinks Given']*df['Cost per Drink'])))
df['Profit'] = df['Sales'] + df['Expenses']
df['Period'] = np.where(df['Drinks Given'].isnull(), 'Before Fridge', 'After Fridge')

pre_fridge_sales = round(df.loc[df['Period'] == 'Before Fridge', 'Sales'].sum(), 2)
post_fridge_sales = round(df.loc[df['Period'] == 'After Fridge', 'Sales'].sum())
pre_fridge_exp = round(df.loc[df['Period'] == 'Before Fridge', 'Expenses'].sum())
post_fridge_exp = round(df.loc[df['Period'] == 'After Fridge', 'Expenses'].sum())
pre_fridge_profit = round(df.loc[df['Period'] == 'Before Fridge', 'Profit'].sum())
post_fridge_profit = round(df.loc[df['Period'] == 'After Fridge', 'Profit'].sum())

df = pd.DataFrame({'Description': ['Sales', 'Expenses', 'Profit'], 'Before Fridge': [pre_fridge_sales, pre_fridge_exp, pre_fridge_profit], 'After Fridge': [post_fridge_sales, post_fridge_exp, post_fridge_profit]})

x = range(len(df))
bar_width = 0.35
spacing = 0.05

plt.bar(x, df['Before Fridge'], width=bar_width, label='Before Fridge', color='blue')
plt.bar([i + bar_width + spacing for i in x], df['After Fridge'], width=bar_width, label='After Fridge', color='orange')

plt.title('Before and After Fridge Comparison')
plt.xticks([i + bar_width + spacing/2 for i in x], df['Description'])
plt.yticks([-1000, -750, -500, -250, 0, 250, 500, 750, 1000, 1250, 1500, 1750, 2000])
plt.legend()

for i, value in enumerate(df['Before Fridge']):
    plt.text(x[i], value, str(value), ha='center', va='bottom')

for i, value in enumerate(df['After Fridge']):
    plt.text(x[i] + bar_width + spacing, value, str(value), ha='center', va='bottom')

plt.show()```
1 Like

here is my solution

import pandas as pd

Define the URL to the data file

data_url = ‘https://byu.box.com/shared/static/rcuvuky4qmgs8lukrlia4w5kw8c4hm9w

Load the data from the URL into a DataFrame

df = pd.read_csv(data_url)

Separate the data into two periods: Before and After mini fridge purchase

before_purchase = df[df[‘Period’] == ‘Before’]
after_purchase = df[df[‘Period’] == ‘After’]

Calculate Total Sales, Total Expenses, and Total Net Income for both periods

total_sales_before = before_purchase[‘Sales’].sum()
total_expenses_before = before_purchase[‘Expenses’].sum()
total_net_income_before = total_sales_before - total_expenses_before

total_sales_after = after_purchase[‘Sales’].sum()
total_expenses_after = after_purchase[‘Expenses’].sum()
total_net_income_after = total_sales_after - total_expenses_after

Display the financial data

print(“Financial Information:”)
print(“Period: Before Mini Fridge Purchase”)
print(f"Total Sales: ${total_sales_before:.2f}“)
print(f"Total Expenses: ${total_expenses_before:.2f}”)
print(f"Total Net Income: ${total_net_income_before:.2f}\n")

print(“Period: After Mini Fridge Purchase”)
print(f"Total Sales: ${total_sales_after:.2f}“)
print(f"Total Expenses: ${total_expenses_after:.2f}”)
print(f"Total Net Income: ${total_net_income_after:.2f}\n")

Evaluate the mini fridge strategy

if total_net_income_after > total_net_income_before:
print(“The mini fridge strategy appears to be effective as it resulted in increased net income.”)
print(“Tom should consider continuing with this strategy.”)
else:
print(“The mini fridge strategy may not be effective as it did not result in increased net income.”)
print(“Tom should evaluate and consider making changes to the strategy.”)

Here is the code I used. I printed the results of NI for Tom and it looks like the change has been profitable to increase chicken sales but he is definitely taking a risk with his strategy.

import pandas as pd
df=pd.read_csv(‘https://byu.box.com/shared/static/rcuvuky4qmgs8lukrlia4w5kw8c4hm9w’)

price_chicken=3.99
cost_chicken=0.99
cost_drink=1.59

before_chicken_sales = df[‘Chicken Sold’][pd.isnull(df[‘Drinks Given’])].reset_index(drop=True)
after_chicken_sales = df[‘Chicken Sold’][pd.isnull(df[‘Drinks Given’])==False]
drinks_given = df[‘Drinks Given’][pd.isnull(df[‘Drinks Given’])==False]

df[‘sales_before’]=before_chicken_sales
df[‘sales_after’]=after_chicken_sales
df[‘drinks_given’]=drinks_given

df=df.drop(columns=[‘Chicken Sold’,‘Drinks Given’]).dropna()

income_before=sum(df[‘sales_before’])*price_chicken
exp_before=sum(df[‘sales_before’])*cost_chicken
ni_before=income_before-exp_before

income_after=sum(df[‘sales_after’])*price_chicken
exp_after=sum((df[‘sales_after’])*cost_chicken)+sum(df[‘drinks_given’]*cost_drink)
ni_after=income_after-exp_after

print(income_before,income_after)
print(ni_before)
print(ni_after)
df.head(120)

I used python pandas on a Google Colab sheet to filter clean up and filter the data.

Here is a link to my code:

Summary:

  • Total Sales for both periods (Before/After the purchase of the mini fridge):

    • before: 1176
    • after: 1744
  • Total Expenses for both periods

    • before: 219
    • after: 361
  • Total Net Income (Profitability) for both periods

    • before: 957
    • after: 1042

What a fun challenge, I love working with pandas in Python!
As far as my analysis, I thought Tom did good by getting the fridge, as it increased his profits by 3.64%. However, I thought it was a little ridiculous to not sell them for any amount. IE if a customer buys 2 chickens, they get a free drink, or if they buy one, then they can get a drink for $0.50. I would recommend selling it as if it were a product, but then throwing discounts if they buy more chicken. Here was my code for my figures:

import pandas as pd

def fridgeFigure(drinksGiven):
if drinksGiven>0:
return ‘After’
else:
return ‘Before’

dataurl = ‘https://byu.box.com/shared/static/rcuvuky4qmgs8lukrlia4w5kw8c4hm9w
df = pd. read_csv(dataurl).fillna(0)
df[‘Drinks Given’] = df[‘Drinks Given’].apply(int)
chickenBuy, chickenSell, drinkBuy = 0.99, 3.99, 1.59
df[‘Fridge?’]= df[‘Drinks Given’].apply(fridgeFigure)
dfSum = df.groupby(‘Fridge?’).sum()
dfSum[‘Sales’]= (dfSum[‘Chicken Sold’]*chickenSell)
dfSum[‘Costs’]= (dfSum[‘Chicken Sold’]*chickenBuy) + (dfSum[‘Drinks Given’]*drinkBuy)
dfSum[‘Profit’]= dfSum.Sales - dfSum[‘Costs’]
dfSum = dfSum.transpose()
dfSum[‘Change’] = dfSum[‘After’]-dfSum[‘Before’]
dfSum[‘Change%’] = round((dfSum[‘After’]-dfSum[‘Before’])/(dfSum[‘Before’]/100),2)
display(dfSum)