<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

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

# Read Purchasing File and store into Pandas data frame
purchase_data_df = pd.read_csv(purchase_data)
purchase_data_df.head()<jupyter_output><empty_output><jupyter_text>Player Count * Display the total number of players<jupyter_code># total number of players
numberofplayers = purchase_data_df["SN"].nunique()
numberofplayers
# Create a dataframe
num_players_df = pd.DataFrame({"Total Players":[numberofplayers]})
num_players_df<jupyter_output><empty_output><jupyter_text>Purchasing Analysis (Total) * Run basic calculations to obtain number of unique items, average price, etc.* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame<jupyter_code># Number of unique items
#unique_items = purchase_data_pd["Item Name"].value_counts()
#unique_items
unique_items =len(purchase_data_df["Item ID"].unique())
unique_items

# Average purchase price
average = purchase_data_df["Price"].mean()
average
# Total number of Purchases
total = purchase_data_df["Purchase ID"].count()
total
# Total revenue
totalrevenue = purchase_data_df["Price"].sum()
totalrevenue
# Summary data frame
summary_table_df = pd.DataFrame({"Number of unique items":unique_items, 
                                  "Average Price":average,
                                   "Number of Purchases":total,
                                   "Total Revenue":[totalrevenue]})
                          
summary_table_df<jupyter_output><empty_output><jupyter_text>Gender Demographics * Percentage and Count of Male Players* Percentage and Count of Female Players* Percentage and Count of Other / Non-Disclosed<jupyter_code># Count of players
gender_states = purchase_data_df.groupby("Gender")
total_count_gender = gender_states.nunique()["SN"]
total_count_gender
# Percentage of players
percentage_of_player = total_count_gender/numberofplayers*100
percentage_of_player
# Gender Demographics Data Frame
gender_demo_df = pd.DataFrame({"Total Count":total_count_gender, "Percentage of Players" : percentage_of_player})
gender_demo_df
gender_demo_df.sort_values(["Total Count"], ascending=False).style.format({"Percentage of Players":"{:.2f}%"})<jupyter_output><empty_output><jupyter_text>Purchasing Analysis (Gender) * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame<jupyter_code># Count of Male players
Male_players = (purchase_data_df["Gender"] == "Male").value_counts()
Male_players[True]
# Count of Female players
Female_players = (purchase_data_df["Gender"] == "Female").value_counts()
Female_players[True]
# Count of Non Disclosed/other
nondisclosed_players = (purchase_data_df["Gender"] == "Other / Non-Disclosed").value_counts()
nondisclosed_players[True]
#  Purchase count by gender
purchase_count= purchase_data_df.groupby(["Gender"]).Price.count()
purchase_count
# Average by gender
average_gender= purchase_data_df.groupby(["Gender"]).Price.mean()
average_gender
# Total Purchase
total_purchase = purchase_data_df.groupby(["Gender"]).Price.sum()
total_purchase
#Average total purchase per person
average_per_person = total_purchase/total_count_gender
average_per_person
# Purchasing Analysis dataframe
purchasing_analysis_df = pd.DataFrame({"Purchase Count": purchase_count,   
                                       "Average Purchase Price":average_gender,  
                                       "Total Purchase Value":total_purchase,   
                                       "Average Total purchase per Person":average_per_person})
purchasing_analysis_df
purchasing_analysis_df.sort_values(["Gender"], ascending=False)
purchasing_analysis_df.style.format({"Average Purchase Price":"${:,.2f}",
                                      "Total Purchase Value":"${:,.2f}",
                                       "Average Total purchase per Person":"${:,.2f}"})<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>print(purchase_data_df["Age"].max())
print(purchase_data_df["Age"].min())
# Create bins
bins = [0,9,14,19,24,29,34,39,100]
# Create labels
group_labels = ["<10", "10 to 14","15 to 19","20 to 24","25 to 29","30 to 34","35 to 39","40+"]

purchase_data_df["Age Group"] = pd.cut(purchase_data_df["Age"],bins, labels=group_labels)
purchase_data_df

age_group = purchase_data_df.groupby("Age Group")

# total players by age category
total_count_age = age_group["SN"].nunique()
total_count_age
# Percentage by age category
percentage_age = (total_count_age/numberofplayers)*100
percentage_age
# Age demographics dataframe
age_demographics_df = pd.DataFrame({"Total Count":total_count_age,
                                    "Percentage of Players":percentage_age})
age_demographics_df
age_demographics_df.style.format({"Percentage of Players":"{:,.2f}%"})<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># Purchase count by age
purchase_count_age = age_group["Purchase ID"].count()
purchase_count_age
# Average purchase per price by age
ave_purchase_price_age = age_group["Price"].mean()
ave_purchase_price_age
# total purchase value by age group
total_purchase_value = age_group["Price"].sum() 
total_purchase_value
# average purchase per person
avg_purchase_per_person = total_purchase_value/total_count_age
avg_purchase_per_person
# Purchasing Analysis dataframe
purchasing_analysis = pd.DataFrame({"Purchase Count":purchase_count_age,
                                     "Average Purchase Price":ave_purchase_price_age,
                                     "Total Purchase Value":total_purchase_value,
                                      "Avg Total Purchase Per Person":avg_purchase_per_person
                                   })
purchasing_analysis
purchasing_analysis.style.format({"Average Purchase Price":"${:,.2f}",
                                      "Total Purchase Value":"${:,.2f}",
                                       "Avg Total Purchase Per Person":"${:,.2f}"})<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># Purchase count by spenders
spenders = purchase_data_df.groupby("SN")
spenders
purchase_count_spenders = spenders["Purchase ID"].count()
purchase_count_spenders
# Average purchase price by spenders
average_purchase_price = spenders["Price"].mean()
average_purchase_price
# total purchase by spenders
total_purchase = spenders["Price"].sum()
total_purchase
# spenders dataframe
spenders_df = pd.DataFrame({"Purchase Count":purchase_count_spenders,
                             "Average Purchase Price":average_purchase_price,
                             "Total Purchase Value":total_purchase})
spenders_df
format_spenders = spenders_df.sort_values(["Total Purchase Value"],ascending=False).head()
format_spenders.style.format({"Average Purchase Price":"${:,.2f}",
                                      "Total Purchase Value":"${:,.2f}",
                            })<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, 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># Retrive the item id, item name,item price.
item = purchase_data_df[["Item ID","Item Name","Price"]]
item
#Group by item id and item name
item_group = item.groupby(["Item ID","Item Name"])
item_group
# Count the num of items
purchase_count_item = item_group["Price"].count()
purchase_count_item
#Purchase value per item
purchase_value_item = item_group["Price"].sum()
purchase_value_item
#  item price
item_price = purchase_value_item/purchase_count_item
item_price
# most popular item data frame
most_popular_item = pd.DataFrame({"Purchase Count":purchase_count_item,
                                  "Item Price":item_price,
                                  "Total Purchase Value":purchase_value_item})
most_popular_item
most_popular_format = most_popular_item.sort_values(["Purchase Count"],ascending=False).head()
most_popular_format
most_popular_format.style.format({"Item Price":"${:,.2f}",
                                   "Total Purchase Value":"${:,.2f}"
                                 })<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># most profitable items data frame
most_popular_format = most_popular_item.sort_values(["Purchase Count"],ascending=False).head()
most_popular_format
most_popular_format.style.format({"Item Price":"${:,.2f}",
                                   "Total Purchase Value":"${:,.2f}"
                                 })<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09359510156477792, 'fraction_numerical': 0.006317426377684906, 'mean_word_length': 4.285053929121726, 'pattern_counts': {'":': 36, '<': 42, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '152721', 'license': 'ADSL', 'n_tokens_mistral': 3028, 'n_tokens_neox': 2837, 'n_words': 819, 'path': 'HeroesOfPymoli/HeroesOfPymoli_starter.ipynb', 'repo_name': 'pbhoomika888/Pandas_Challenge', 'size': '10289'}