<jupyter_start><jupyter_text>Heroes Of Pymoli Data Analysis* Of the 1163 active players, the vast majority are male (84%). There also exists, a smaller, but notable proportion of female players (14%).* Our peak age demographic falls between 20-24 (44.8%) with secondary groups falling between 15-19 (18.60%) and 25-29 (13.4%).  -----  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

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

#Read Purchasing File and store into Pandas data frame
pDataDf = pd.read_csv(file_to_load)

#Show head to see the sample of the data
pDataDf.head()<jupyter_output><empty_output><jupyter_text>Player Count * Display the total number of players<jupyter_code>#Calculate Total Player
#Use len to do the count of the data
tPlayers = len(pDataDf["SN"].value_counts())

pCounts = pd.DataFrame({"Total Players":[tPlayers]})
pCounts<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>#Calculation of the data
nUniqueitems = len(pDataDf['Item Name'].value_counts())
avgPP = pDataDf['Price'].mean()
tPurchases = pDataDf['Price'].sum()

#Put data into a frame
pAnalysisDF = pd.DataFrame({'Number of Unique Items':[nUniqueitems],
             'Average Price':[avgPP],
             'Number of Purchases': [len(pDataDf)],
             'Total Purchases':[tPurchases]})
pAnalysisDF

#Add $ sign
pAnalysisDF.style.format({'Average Price': '${:.2f}', 'Total Purchases': '${:,.2f}'})<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>#Use drop_duplicates to drop all the same Gender and SN 
#Do declare and do calculation
gender = pDataDf[['SN', 'Gender']]
gData = gender.drop_duplicates()
gCounts = gData['Gender'].value_counts()

totalC = gCounts.sum()
pMale = gCounts[0]/totalC*100
pFemale = gCounts[1]/totalC*100
pOthers = gCounts[2]/totalC*100

gDemographics = pd.DataFrame({"Total count":[gCounts[0], gCounts[1], gCounts[2]],
                            "Percentage of Players":[pMale, pFemale, pOthers]})
gDemographics.index = (["Male", "Female", "Others/Non-Disclosed"])
gDemographics["Percentage of Players"] = gDemographics["Percentage of Players"].map("{:.2f}%".format)
gDemographics<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>#Purchasing Analysis (Gender)
purchaseGender = pDataDf.groupby(['Gender'])

#Do calculation on the data of purchase for gender: count, mean, sum
puCounts = purchaseGender['Price'].count()
priceMean = purchaseGender['Price'].mean()
totalPu = purchaseGender['Price'].sum()

#AveragePP = totalPu/puCounts
averageToPP = totalPu/gCounts

puAnalysisDF = pd.DataFrame({'Purchase Count': puCounts,
                            'Average Purchase Price': priceMean,
                            'Total Purchase Value': totalPu,
                            'Avg Total Purchase Per Person': averageToPP})
#Add $ sign 
puAnalysisDF.style.format({'Average Purchase Price': '${:.2f}', 
                           'Total Purchase Value': '${:,.2f}', 
                           'Avg 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>#Set Bins for Ages
#Give a range for the number
ageBins = [0, 9.5, 14.5, 19.5, 24.5, 29.5, 34.5, 39.5, 109.5]
ageRanges = ['<10', '10-14', '15-19', '20-24', '25-29', '30-34', '35-39', '40+']

pDataDf['Age Demographics'] = pd.cut(pDataDf['Age'], ageBins, labels=ageRanges)

aDemographicsgroup = pDataDf.groupby('Age Demographics')

countDf = aDemographicsgroup.agg({'SN': 'nunique'})
totalAge = countDf.sum()
percentPlayersDF = round((countDf/totalAge)*100, 2)

#Reset the index
countDf = countDf.reset_index()
percentPlayersDF = percentPlayersDF.reset_index()

aDemoDf = countDf.merge(percentPlayersDF, on= 'Age Demographics')
aDemoDf.set_index('Age Demographics', inplace = True)

aDemoDf = aDemoDf.rename(columns={'SN_x': 'Total Count', 
                                  'SN_y': 'Percentage of Players'}) 

aDemoDf["Percentage of Players"] = aDemoDf["Percentage of Players"].map("{:.2f}%".format)

#Drop index name 'Age Demographics'
aDemoDf.index.name = None

aDemoDf<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>#Do the calculations of the data and group them

purchaseID = aDemographicsgroup["Purchase ID"].count()
averageP = round(aDemographicsgroup["Price"].mean(), 2)
totalPricevalue = round(aDemographicsgroup["Price"].sum(), 2)
countTotal = countDf.set_index("Age Demographics")
countTotal2 = countTotal.merge(totalPricevalue, on="Age Demographics")
totalPricepp= (countTotal2["Price"]/countTotal2["SN"])

puAA = pd.DataFrame({'Purchase Count': purchaseID,
                     'Average Purchase Price': averageP,
                     'Total Purchase Value': totalPricevalue,
                     'Avg Total Purchase per Person': totalPricepp})

puAA.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>#Find top Spender 
#Group 'SN'
#Sort by top spender
topSpenderg = pDataDf.groupby(['SN'])
topSpendera = round(topSpenderg['Price'].mean(),2)
topSpender = topSpenderg['Price'].sum()
topCount = topSpenderg['SN'].count()

spender = pd.DataFrame({'Purchase Count': topCount,
                        'Average Purchase Price': topSpendera,
                        'Total Purchase Value': topSpender})

spenderSort = spender.sort_values(by = 'Total Purchase Value', ascending = False)

spenderSort['Average Purchase Price'] = spenderSort['Average Purchase Price'].map('${:.2f}'.format)
spenderSort['Total Purchase Value'] = spenderSort['Total Purchase Value'].map('${:.2f}'.format)


spenderSort.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>#Get the Item Id out and then we group by item id and item name 
#Then do count price, item price, total purchase value
#Sort the purchase count column in descending order 

mostPopitems = pDataDf[['Item ID', 'Item Name', 'Price']]
mostPopiG = mostPopitems.groupby(['Item ID','Item Name'])
purchaseCount = mostPopiG['Item Name'].count()
totalPu = mostPopiG['Price'].sum()
itemPrice = totalPu/purchaseCount

mpiDf = pd.DataFrame({'Purchase Count': purchaseCount,
                    'Item Price': itemPrice,
                    'Total Purchase Value': totalPu})

mpiSort = mpiDf.sort_values("Purchase Count",ascending=False)

#map $ sign
mpiSort['Item Price'] = mpiSort['Item Price'].map('${:.2f}'.format)
mpiSort['Total Purchase Value'] = mpiSort['Total Purchase Value'].map('${:.2f}'.format)

mpiSort.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>#Sort the data

mpiSort = mpi.sort_values("Total Purchase Value",ascending=False)

mpiSort['Item Price'] = mpiSort['Item Price'].map('${:.2f}'.format)
mpiSort['Total Purchase Value'] = mpiSort['Total Purchase Value'].map('${:.2f}'.format)

mpiSort.head(10)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11951801997394702, 'fraction_numerical': 0.013894919669995658, 'mean_word_length': 4.808953341740227, 'pattern_counts': {'":': 3, '<': 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': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '493268', 'license': 'ADSL', 'n_tokens_mistral': 2994, 'n_tokens_neox': 2734, 'n_words': 886, 'path': 'HeroesOfPymoli/HeroesOfPymoli_starter.ipynb', 'repo_name': 'yonas-hub/Pandas_HW_FOUR', 'size': '9212'}