<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 os

# File to Load (Remember to Change These)
file_to_load = os.path.join("Resources", "purchase_data.csv")

# Read Purchasing File and store into Pandas data frame
purchase_data = pd.read_csv(file_to_load)
purchase_data.head()<jupyter_output><empty_output><jupyter_text>Player Count * Display the total number of players<jupyter_code>#create a new column that counts all of the unique players
Total_players = len(purchase_data["SN"].value_counts())


#create a dataframe to display total players using dict of lists
count = pd.DataFrame({"Total Players":[Total_players]})
count<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 = len(purchase_data["Item ID"].value_counts())

#Average Purchase Price
purchase_price = pd.Series(purchase_data["Price"]).mean()
purchase_price = round(purchase_price,2)


#Total Number of Purchases
total_purchases = len(purchase_data["Price"])
total_purchases = round(total_purchases,2)

#Total Revenue
total_revenue = pd.Series(purchase_data["Price"]).sum()

#add data to dataframe
purchase_analysis = {'Unique Items':[unique_items],
                   'Average Price':[purchase_price],
                   'Number of Purchases': [total_purchases],
                   'Total Purchases':[total_revenue]}
df_pa =pd.DataFrame(purchase_analysis)
df_pa

# Format with currency style
df_pa["Average Price"] = df_pa["Average Price"].map("${:.2f}".format)
df_pa["Total Purchases"] = df_pa["Total Purchases"].map("${:.2f}".format)
df_pa.head()


#create a copy of the original dataframe
df_data = purchase_data.copy()
df_data.head()<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>#group dataframe by gender
df_gender = df_data.groupby(['Gender'])
print(df_gender)
df_gender.head()

# Count of Male, Female and Other/Non-Disclosed and drop NaN values
gender_count = df_gender.nunique()['SN']


#percentage of Male,Female and other/non-disclosed
gender_percentage = gender_count / Total_players * 100
gender_percentage = round(gender_percentage,2)
gender_percentage

# add them all to a dataframe
gender_analysis = {'Total Count':gender_count,
                   'Percentage of Players':gender_percentage}
df_ga = pd.DataFrame(gender_analysis)


#add percentage sign
df_ga["Percentage of Players"] = df_ga["Percentage of Players"].map("{:.2f}%".format)
df_ga.head()<jupyter_output><pandas.core.groupby.generic.DataFrameGroupBy object at 0x118f41110><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>#purchase count by gender 
purchase_count = df_gender["Purchase ID"].count()

#average purchase prices by gender
avg_purchase_price = df_gender["Price"].mean()
avg_purchase_price = round(avg_purchase_price,2)

#total purchase value
total_purchase_value = df_gender["Price"].sum()


#average purchase total per person
per_person = total_purchase_value / gender_count

per_person = round(per_person,2)
per_person

#add all to dataframe
gender_purchase_analysis = {'Purchase Count':purchase_count,
                     'Average Purchase Price':avg_purchase_price,
                     'Total Purchase value':total_purchase_value,
                     'Avg Total Purchase Per Person':per_person}
df_gpa = pd.DataFrame(gender_purchase_analysis)
df_gpa.head()

#add dollar signs
df_gpa["Average Purchase Price"] = df_gpa["Average Purchase Price"].map("${:.2f}".format)
df_gpa["Total Purchase value"] = df_gpa["Total Purchase value"].map("${:.2f}".format)
df_gpa["Avg Total Purchase Per Person"] = df_gpa["Avg Total Purchase Per Person"].map("${:.2f}".format)
df_gpa.head()<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>#The below each broken into bins of 4 years (i.e. &lt;10, 10-14, 15-19, etc.)
age_bin = [0, 9.90, 14.90, 19.90, 24.90, 29.90, 34.90, 39.90, 99999]
bin_names = ["<10", "10-14", "15-19","20-24", "25-29", "30-34", "35-39", "40+" ]

df_data["Age Groups"] = pd.cut(df_data["Age"], age_bin, labels=bin_names)
df_data

#grouby based on age groups
grouped_age = df_data.groupby("Age Groups")

# Purchase Count
age_purchase_count = grouped_age.nunique()["SN"]

#Average Purchase pricee
avg_purchase_by_age = grouped_age["Price"].mean()
avg_purchase_by_age = round(avg_purchase_by_age,2)

# Total Purchase Value
total_purchase_by_age = grouped_age["Price"].sum()

#average total perchase per person by age
avg_per_person_by_age = total_purchase_by_age / age_purchase_count

avg_per_person_by_age = round(avg_per_person_by_age,2)

#Percentage of Players
player_percent_by_age = age_purchase_count / 576 * 100

player_percent_by_age= round(player_percent_by_age,2)
player_percent_by_age

#put data in dataframe
age_demo = {'Total Count':age_purchase_count,
            'Percentage of Players':player_percent_by_age}
age_demo = pd.DataFrame(age_demo)
age_demo.head(10)

#turn into percentage
age_demo["Percentage of Players"] = age_demo["Percentage of Players"].map("{:.2f}%".format)
age_demo.head(10)<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
purchase_count1 = grouped_age["Age Groups"].count()

#create dataframe for age analysis
age_analysis = {'Purchase Count':purchase_count1,
                'Average Purchase Price':avg_purchase_by_age,
                'Total Purchase Value':total_purchase_by_age,
                'Avg Total Purchase Per Person':avg_per_person_by_age}
age_demo = pd.DataFrame(age_analysis)
age_demo.head(10)

#add $

age_demo["Average Purchase Price"] = age_demo["Average Purchase Price"].map("${:.2f}".format)
age_demo["Total Purchase Value"] = age_demo["Total Purchase Value"].map("${:.2f}".format)
age_demo["Avg Total Purchase Per Person"] = age_demo["Avg Total Purchase Per Person"].map("${:.2f}".format)
age_demo.head()<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>#Identify the top 5 spenders in the game by total purchase value, then list (in a table):
#SN grouby
top_five = df_data.groupby("SN")
top_five.head()

# Purchase Count
top_purchase_count = top_five["Purchase ID"].count()

# Average Purchase Price
top_avg_purchase_price = top_five["Price"].mean()
top_avg_purchase_price = round(top_avg_purchase_price,2)

# Total Purchase Value
top_total_purchase_value = top_five["Price"].sum()
top_total_purchase_value

#dataframe for top spenders
top_spenders = {'Purchase Count':top_purchase_count,
                'Average Purchase Price':top_avg_purchase_price,
                'Total Purchase Value':top_total_purchase_value}
top_spenders = pd.DataFrame(top_spenders)
top_spenders

#sort in descending order
top_spenders_sort = top_spenders.sort_values(["Total Purchase Value"], ascending = False)
top_spenders_sort.head()

#add $
top_spenders_sort["Average Purchase Price"] = top_spenders_sort["Average Purchase Price"].map("${:.2f}".format)
top_spenders_sort["Total Purchase Value"] = top_spenders_sort["Total Purchase Value"].map("${:.2f}".format)
top_spenders_sort.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, 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>#Retrieve the Item ID, Item Name, and Item Price columns
most_pop = df_data.loc[:,["Item ID", "Item Name", "Price"]]

#Group by Item ID and Item Name. 
grouped_most_pop = df_data.groupby(["Item ID", "Item Name"])

#Purchase Count; how many times has an item been purchased
mostpop_purchase_count = grouped_most_pop["Item ID"].count()

#purchase value per item
purchase_per_item = grouped_most_pop["Price"].sum()

#item price per item
item_price = purchase_per_item / mostpop_purchase_count

#dataframe for top spenders
most_pop_df = {'Purchase Count':mostpop_purchase_count,
                'Item Price':item_price,
                'Total Purchase Value':purchase_per_item}
most_pop_df = pd.DataFrame(most_pop_df)
most_pop_df.head()

#sort purchase count in descending order
most_pop_sort = most_pop_df.sort_values(["Purchase Count"], ascending = False)
most_pop_sort.head()

#add $
most_pop_sort["Item Price"] = most_pop_sort["Item Price"].map("${:.2f}".format)
most_pop_sort["Total Purchase Value"] = most_pop_sort["Total Purchase Value"].map("${:.2f}".format)
most_pop_sort.head()<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>#sort total purchase value in descending order
most_pop_sort = most_pop_df.sort_values(["Total Purchase Value"], ascending = False)
most_pop_sort.head()

#add $
most_pop_sort["Item Price"] = most_pop_sort["Item Price"].map("${:.2f}".format)
most_pop_sort["Total Purchase Value"] = most_pop_sort["Total Purchase Value"].map("${:.2f}".format)
most_pop_sort.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10561361324331822, 'fraction_numerical': 0.011467677795246463, 'mean_word_length': 5.954340836012862, 'pattern_counts': {'":': 1, '<': 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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '334769', 'license': 'ADSL', 'n_tokens_mistral': 3568, 'n_tokens_neox': 3342, 'n_words': 973, 'path': 'HeroesOfPymoli_starter.ipynb', 'repo_name': 'ArazOha/Pandas-Challenge', 'size': '10813'}