<jupyter_start><jupyter_text>HEROES OF PYMOLI DATA ANALYSIS              Some important trends and observations :-    	 Total of 576 players in the dataset given the lion's share of players based on gender and age demographics consists of Males at a total of 484 or 84.03% males and a huge fanbase among the ages of 20-24 year old’s at 258 players or 44.79% and 15-19 year old’s at 107 players or 18.58% followed by 25-29 year old’s at 77 players or 13.37% of males, females, others combined. The Female fanbase comprises of a total of 81 players or 14.06% followed by a Non-Disclosed gender type at 11 players or 1.91%.The statistics clearly indicate the success of the game with the male gender and emphasizes the concentration of userbase among the youth between the ages of 15 to 29 year old's.        	The maximum purchases are made by the age group of 20-24 year old’s at 365 purchases and an average purchasing price of 3.05 dollars and the total purchase value being 1114.06 dollars which is the biggest dollar amount among all age groups with the average purchase per person being 4.32 dollars. These figures are followed by the age groups of 15-19 and 25-29 year olds in terms of revenue generation and re-confirming the trend of the game's popularity with the younger population especially between 15 to 29 years of age.        	The top spenders have spent 18.96, 15.45, 13.83 dollars each for a total of 5,4,3 purchases respectively. The most popular item being "Oathbreaker, Last Hope of the Breaking Storm" which has been bought 12 times for a total of 50.76 dollars by different users with runners up "Fiery Glass Crusader" which has been bought 9 times         for a total of 41.22 dollars and the 2nd runner up being "Extraction, Quickblade Of Trembling Hands" which was bought 9 times as well for a total of 31.77 dollars. Continuing the trend of its popularity "Oathbreaker, Last Hope of the Breaking Storm" remains the most profitable item on the list bringing in 50.76 dollars at an average price of 4.23 dollars, while "Nirvana" comes second as a profitable item at 4.90 dollars average price and generating 44.10 dollars and in the third place is "Fiery Glass Crusader" at a total of 9 purchases at 44.10 dollars for 4.90 dollars per item.     Two clear patterns worth noticing are the players being heavily concentrated between the ages of 15-29 and largely male and the popularity as well as profitability of the item Oathbreaker, Last Hope of the Breaking Storm".<jupyter_code>import pandas as pd
import numpy as np

csvpath = "purchase_data.csv"
csv_file = pd.read_csv(csvpath)
csv_file.head()


#Display the total number of players

player_count = csv_file["SN"].unique()
Total_players = len(player_count)

total_dict = [{"Total Players": 576}]
total_df = pd.DataFrame(total_dict)
total_df

#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

#Calculating the unique items , avg price , count and sum of all items.

Unique = csv_file["Item ID"].unique()

Total_unique_items = len(Unique)

Average_price = csv_file["Price"].mean()

No_of_purchases = csv_file["Purchase ID"].count()

Total_price = csv_file["Price"].sum()

#Summarizing the data in a Dataframe.

Purchasing_dict = [{"Total Unique Items":"183","Average Price":"$3.05","Number of Purchases":"780",
                    "Total Price":"$2379.77"}]

Purchasing_Analysis = pd.DataFrame(Purchasing_dict)

Purchasing_organized = Purchasing_Analysis[["Total Unique Items","Average Price","Number of Purchases","Total Price"]]

Purchasing_organized

#GENDER DEMOGRAPHICS

#Percentage and Count of Male Players

#Percentage and Count of Female Players

#Percentage and Count of Other / Non-Disclosed

#Gender break-up after removing duplicate SN.

#Calculating the gender break up after dropping duplicates.

csv_nodup = csv_file.drop_duplicates(subset=['SN'], keep='first')

Male_breakup = csv_nodup.loc[csv_nodup["Gender"]=="Male"].count()
Female_breakup = csv_nodup.loc[csv_nodup["Gender"]=="Female"].count()
Others_breakup = csv_nodup.loc[csv_nodup["Gender"]=="Other / Non-Disclosed"].count()

#gender_breakup_list = [81 Females, 484 Males,11 Other/Non Disclosed]

count_perecentageM = (100 * Male_breakup / Total_players).round(2).astype(str) + '%'
count_perecentageF = (100 * Female_breakup / Total_players).round(2).astype(str) + '%'
count_perecentageO = (100 * Others_breakup / Total_players).round(2).astype(str) + '%'

#Summarizing the data in a Dataframe.

Gender_demographics = pd.DataFrame({
    "Gender":["Male","Female","Other / Non-disclosed"],
    "Count" :[484,81,11],
    "Percentages":["84.03%","14.06%","1.91%"]
})
Gender_demographics

#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

#Calculating the sum ,average ,number and total average per person purchase on gender and price basis

gender_purchase_total = csv_file.groupby(["Gender"]).sum()["Price"].rename("Total Purchase Value")

gender_average = csv_file.groupby(["Gender"]).mean()["Price"].rename("Average Purchase Price")

gender_counts = csv_file.groupby(["Gender"]).count()


avg_total_per_person=[]
gender_breakup_list = [81,484,11]

temp1 = zip(gender_purchase_total,gender_breakup_list)

for (x,y) in temp1:
    avg_total_per_person.append(x/y)

#Summarizing the data in a Dataframe.

gender_purchases = pd.DataFrame({
    "Gender":["Male","Female","Other / Non-disclosed"],
    "Purchase Count":[652,113,15],
    "Average Purchase Price" :["$3.01","$3.20","$3.34"],
    "Total Purchase Value":["$1967.64","$361.94","$50.19"],
    "Avg Total Purchase per Person":["$4.07","$4.47","$4.56"]
})
gender_purchases

#AGE DEMOGRAPHICS

#Establish bins for ages

#Categorize the existing players using the age bins. 

#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

#Binning the data after dropping duplicates and taking count and percentage.

csv_nodup = csv_file.drop_duplicates(subset=['SN'], keep='first')

bins=[0,9.9,14.9,19.9,24.9,29.9,34.9,39.9,800]
labels=["<10","10-14","15-19","20-24","25-29","30-34","35-39","40+"]   
    
csv_nodup["age summary"] = pd.cut(csv_nodup["Age"], bins, labels=labels)

Count_each_bin = csv_nodup.groupby(["age summary"]).count()
Percentage_each_bin = ((Count_each_bin/576)*100).round(2).astype(str) + '%'

#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

#Calculating the sum ,average ,number and total average per person purchase on age and price basis.

bins = [0,9.9,14.9,19.9,24.9,29.9,34.9,39.9,800]
labels = ["<10","10-14","15-19","20-24","25-29","30-34","35-39","40+"]   
    
csv_file["age summary"] = pd.cut(csv_file["Age"], bins, labels = labels)


agewise_total_purchase = csv_file.groupby(["age summary"]).sum()["Price"].rename("Agewise Total Purchase value").map("${:,.2f}".format)
agewise_avg_purchase = csv_file.groupby(["age summary"]).mean()["Price"].rename("Agewise Average Purchase Price").map("${:,.2f}".format)
agewise_purchase_count = csv_file.groupby(["age summary"]).count()["Price"].rename("Agewise Purchase Count")



Purchase_list = [ 77.13,82.78,412.89,1114.06,293.00,214.00,147.67,38.24 ]
Bin_count_csvfile = [17,22,107,258,77,52,31,12]

avg_a = []
temp_age = zip(Purchase_list , Bin_count_csvfile)

for (x,y) in temp_age:
    avg_a.append(x/y)
print(avg_a)
agewise_total_perperson = avg_a



Age_Demographics = pd.DataFrame({"Purchase Count":agewise_purchase_count ,                               
                                 "Average Purchase Price" :agewise_avg_purchase,
                                 "Total Purchase value":agewise_total_purchase,
                                 "Avg Total Per Person":["$4.54","$3.76","$3.86","$4.32","$3.81","$4.12","$4.76","$3.19"]
                                                               
                                })
Age_Demographics

#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

#Grouping by Screen Name to calculate the highest amount spent by players.

sn_grouped = csv_file.groupby(["SN"])

sn_grouped = pd.DataFrame(sn_grouped["Price"].sum())

sn_grouped_sorted = sn_grouped.sort_values("Price",ascending=False)

sn_grouped_sorted.head()

#Top 5 spenders = [18.96,15.45,13.83,13.62,13.10]   

#To find the purchase count of the top spenders we can alternatively use:-

Total_purchases1 = csv_file.loc[csv_file["SN"]=="Lisosia93"].count()
Total_purchases2 = csv_file.loc[csv_file["SN"]=="Idastidru52"].count()
Total_purchases3 = csv_file.loc[csv_file["SN"]=="Chamjask73"].count()
Total_purchases4 = csv_file.loc[csv_file["SN"]=="Iral74"].count()
Total_purchases5 = csv_file.loc[csv_file["SN"]=="Iskadarya95"].count()

Purchase_Count = [5,4,3,4,3]


#OR

pcounts = csv_file["SN"].value_counts()
pcounts.head(10)

#To find the Average Purchase Price of the top spenders

avg_p=[]

temp = zip(sn_top5,Purchase_Count)

for (x,y) in temp:
    avg_p.append(x/y)
print(avg_p) 

#Summarizing the data in a Dataframe.

Top_spenders = pd.DataFrame({
    "SN":["Lisosia93","Idastidru52","Chamjask73","Iral74","Iskadarya95"],                                              
    "Purchase Count":[5,4,3,4,3],
    "Total Purchase Value" :["$18.96","$15.45","$13.83","$13.62","$13.10"],
    "Average Purchase Price":["$3.79","$3.86","$4.61","$3.40","$4.37"]                                        
})

Top_spenders

#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


#Calculating the number of all the items after extracting columns

item_data = csv_file.loc[:,["Item ID", "Item Name", "Price"]]
item_count = item_data.groupby(["Item ID", "Item Name"]).count()["Price"].rename("Purchase Count")

#Calculating the Total purchase value and the Mean Item Price

total_item_purchase = item_data.groupby(["Item ID", "Item Name"]).sum()["Price"].rename("Total Purchase Value")
average_item_purchase = item_data.groupby(["Item ID", "Item Name"]).mean()["Price"]

# Create a new DataFrame and sort it

item_data_pd = pd.DataFrame({"Total Purchase Value": total_item_purchase, 
                             "Item Price": average_item_purchase, "Purchase Count": item_count})

item_data_count_sorted = item_data_pd.sort_values("Purchase Count", ascending=False)

# Minor Data Munging

item_data_count_sorted["Item Price"] = item_data_count_sorted["Item Price"].map("${:,.2f}".format)
item_data_count_sorted["Purchase Count"] = item_data_count_sorted["Purchase Count"].map("{:,}".format)
item_data_count_sorted["Total Purchase Value"] = item_data_count_sorted["Total Purchase Value"].map("${:,.2f}".format)
item_popularity = item_data_count_sorted.loc[:,["Purchase Count", "Item Price", "Total Purchase Value"]]

item_popularity.head(5)

#M0ST 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

#Sorting the data in a Dataframe 

item_data_count_sorted = item_data_pd.sort_values("Total Purchase Value", ascending=False)
item_data_count_sorted.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11811406351263772, 'fraction_numerical': 0.043907971484121844, 'mean_word_length': 4.591032608695652, 'pattern_counts': {'":': 20, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '611564', 'license': 'MIT', 'n_tokens_mistral': 4359, 'n_tokens_neox': 3863, 'n_words': 1237, 'path': 'Pandas_HW_UCBERKELEY/ Pymoli Data Analysis.ipynb', 'repo_name': 'Aminprv/Pandas_HW', 'size': '12344'}