<jupyter_start><jupyter_text>Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.<jupyter_code># Dependencies and Setup
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# from IPython.display import display
# # from pandas_summary import DataFrameSummary


# File to Load (Remember to Change These)
file = "Resources/purchase_data.csv"

# Read Purchasing File and store into Pandas data frame
df = pd.read_csv(file)
# df.head()
# display(df)
df
# df.info()
# df.describe()
#Display the total number of players

TP = df['SN'].nunique()
TP

# Create a dataframe for total players 

Total_players = pd.DataFrame({"Total Players":[TP]})
Total_players

# Calculate Total Players , Average Price , Number of Purchases and Total revenue

Purchasing_Anaylsis_Total =  pd.DataFrame({"Total Players":[df['SN'].nunique()], "Average Price": [df['Price'].mean()],"Number of Purchases": [df.shape[0]], "Total Revenue": [df["Price"].sum()]})

# Fix formatting by adding a $ and rounding of to 2 decimal point  

Purchasing_Anaylsis_Total["Average Price"] = Purchasing_Anaylsis_Total["Average Price"].astype(float).map("${:,.2f}".format)
Purchasing_Anaylsis_Total["Total Revenue"] = Purchasing_Anaylsis_Total["Total Revenue"].astype(float).map("${:,.2f}".format)

# Purchasing_Anaylsis_Total.info()
# Purchasing_Anaylsis_Total.set_index('Total Players', inplace=True)

Purchasing_Anaylsis_Total<jupyter_output><empty_output><jupyter_text>Gender Demographics<jupyter_code>#Calculate percenatge of players by Gender using group by 

Gender_Data_Percentages = (df.groupby('Gender').nunique()['SN'] / TP) *100
Gender_Data_Percentages

#Create a data from using group by dataframe 
Gender_demo =  pd.DataFrame({'Total Count': TP, 'Percentage of Players': Gender_Data_Percentages})

#converting Percentage of players to proper formatting 
Gender_demo["Percentage of Players"] = Gender_demo["Percentage of Players"].astype(float).map("{:,.2f}%".format)

# removing the index 
Gender_demo.index.name = None
Gender_demo<jupyter_output><empty_output><jupyter_text>Purchasing Analysis (Gender) * Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame<jupyter_code># Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender

Gen_Obj = df.groupby('Gender')

gender_purchase_count = Gen_Obj['Item Name'].count()
gender_purchase_count

gender_avg_purchase_price = Gen_Obj['Price'].mean()
gender_avg_purchase_price

gender_avg_purchase_pp = df.groupby('Gender')['Price'].mean()
gender_avg_purchase_pp

gender_total_pp = Gen_Obj['Price'].sum() / gender_purchase_count
gender_total_pp

#lets make a dataframe df1

df1 = pd.DataFrame({
    'Purchase Count' : gender_purchase_count,
    'Average Purchase Price' : gender_avg_purchase_price,
    'Total Purchase Value'  : gender_total_pp,
    'Avg Total Purchase per Person' : gender_avg_purchase_pp
})
#lets format the dataframe df1

df1["Average Purchase Price"]=df1["Average Purchase Price"].astype(float).map("${:.2f}".format)
df1["Total Purchase Value"]=df1["Total Purchase Value"].astype(float).map("${:.2f}".format)
df1["Avg Total Purchase per Person"]=df1["Avg Total Purchase per Person"].astype(float).map("${:.2f}".format)

df1<jupyter_output><empty_output><jupyter_text>Age Demographics * Establish bins for ages* Categorize the existing players using the age bins. Hint: use pd.cut()* Calculate the numbers and percentages by age group* Create a summary data frame to hold the results* Optional: round the percentage column to two decimal points* Display Age Demographics Table<jupyter_code>#Establish age bins
bins = [0, 9.99, 14.99, 19.99, 24.99, 29.99, 34.99, 39.99, 50]

#Create group labels for age bins
labels = ["<10", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40+"]

#Categorize Data
df["Age Group"] = pd.cut(df["Age"], bins, labels=labels)

age_group = df.groupby("Age Group")

#Calculate Numbers and Percentages by Age Group
total_age = age_group["SN"].nunique()

age_percentage = (total_age/TP) * 100
# type(bins)
# type(labels)
#Create Summary Data Frame
agedemo = pd.DataFrame({"Total Count": total_age,
                                "Percentage of Players": age_percentage})
#Formating
agedemo.index.name = None
agedemo["Percentage of Players"] = agedemo["Percentage of Players"].astype(float).map("{:.2f}%".format)

agedemo<jupyter_output><empty_output><jupyter_text>Purchasing Analysis (Age)* Bin the purchase_data data frame by age* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame<jupyter_code># calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc.

# Purchase Count
purchase_count_byage = age_group['Purchase ID'].count()
#print it 
# purchase_count_byage

# Average Purchase Price 
avg_purchase_price_byage = age_group['Price'].mean().astype(float).map("${:.2f}".format)
#print it 
# avg_purchase_price_byage


# Total Purchase Value
total_purchase_value_byage = age_group["Price"].sum()
#print it
total_purchase_value_byage

#  Avg Total Purchase per Person 
avg_total_purchase_byage = total_purchase_value_byage/total_age
#print it 
# avg_total_purchase_byage

# Create a dataframe 

purchasing_analysis_byage = pd.DataFrame({
    'Purchase Count'                  :purchase_count_byage,
    'Average Purchase Price'          :avg_purchase_price_byage,  
    'Total Purchase Value'            :total_purchase_value_byage, 
    'Avg Total Purchase per Person'   :avg_total_purchase_byage
})

#print it 
purchasing_analysis_byage

# format it 
purchasing_analysis_byage.index.name = "Age Ranges"
purchasing_analysis_byage['Total Purchase Value'] =  purchasing_analysis_byage['Total Purchase Value'].astype(float).map("${:.2f}".format)
purchasing_analysis_byage['Avg Total Purchase per Person'] = purchasing_analysis_byage['Avg Total Purchase per Person'].astype(float).map("${:.2f}".format)

#print it 
purchasing_analysis_byage<jupyter_output><empty_output><jupyter_text>Top Spenders*Run basic calculations to obtain the results in the table below* Create a summary data frame to hold the results* Sort the total purchase value column in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the summary data frame<jupyter_code>ballers_purchase_count = df.groupby("SN")["Purchase ID"].count()
ballers_avg_purchase_price =  df.groupby("SN")["Price"].mean()
ballers_total_purchase_value = df.groupby("SN")["Price"].sum()

# Create Summary Data Frame
ballerss = pd.DataFrame({'Purchase Count'          :ballers_purchase_count,
                         'Average Purchase Price'  : ballers_avg_purchase_price,
                         'Total Purchase Value'    : ballers_total_purchase_value})
#print it 
ballerss
                       
#Formatting
ballerss_format = ballerss.sort_values(['Total Purchase Value'],ascending=False)
ballerss_format['Average Purchase Price'] = ballerss_format['Average Purchase Price'].astype(float).map("${:.2f}".format)
ballerss_format['Total Purchase Value'] =  ballerss_format['Total Purchase Value'].astype(float).map("${:.2f}".format)

ballerss_format.head()<jupyter_output><empty_output><jupyter_text>Most Popular Items * Retrieve the Item ID, Item Name, and Item Price columns* Group by Item ID and Item Name. Perform calculations to obtain purchase count, average item price, and total purchase value* Create a summary data frame to hold the results* Sort the purchase count column in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the summary data frame<jupyter_code># Item ID, Item Name, and Item Price columns
stuff = df[["Item ID", "Item Name", "Price"]]

#Purchase Count, Average Item Price, and Total Purchase Value
item_data = stuff.groupby(["Item ID", "Item Name"])

item_count = item_data["Item ID"].count()

avg_price = item_data["Price"].mean()

item_total_purchase_value = item_data["Price"].sum()



#Create  Data Frame
most_popular_stuff = pd.DataFrame({"Purchase Count": item_count,
                                  "Average Item Price": avg_price,
                                  "Total Purchase Value": item_total_purchase_value})
#Formatting
most_wanted = most_popular_stuff.sort_values(["Purchase Count"], ascending = False)
most_wanted["Average Item Price"] = most_wanted["Average Item Price"].astype(float).map("${:.2f}".format)
most_wanted["Total Purchase Value"] = most_wanted["Total Purchase Value"].astype(float).map("${:.2f}".format)

most_wanted.head(10)<jupyter_output><empty_output><jupyter_text>Most Profitable Items * Sort the above table by total purchase value in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the data frame<jupyter_code>#Sorting by Total Purchase Value 
most_wanted_items_Format = most_popular_stuff.sort_values(["Total Purchase Value"], ascending = False)

#Formatting
most_wanted_items_Format["Average Item Price"] = most_wanted_items_Format["Average Item Price"].astype(float).map("${:.2f}".format)
most_wanted_items_Format["Total Purchase Value"] = most_wanted_items_Format["Total Purchase Value"].astype(float).map("${:.2f}".format)

most_wanted_items_Format.head(10)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1125, 'fraction_numerical': 0.01, 'mean_word_length': 5.723389355742297, 'pattern_counts': {'":': 10, '<': 34, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '601124', 'license': 'MIT', 'n_tokens_mistral': 3153, 'n_tokens_neox': 2938, 'n_words': 834, 'path': 'HeroesOfPymoli/HerosOfPymoli.ipynb', 'repo_name': 'jagnoor/pandas-challenge', 'size': '9600'}