<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

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

# Read Purchasing File and store into Pandas data frame
purchase_data = pd.read_csv(file_to_load)<jupyter_output><empty_output><jupyter_text>Player Count * Display the total number of players<jupyter_code>print(f"Total players: {purchase_data['SN'].nunique()}")<jupyter_output>Total players: 576<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>purchase_data.head()
uniqueItems = len(purchase_data["Item ID"].unique())
avgPrice = purchase_data["Price"].mean()
avgPrice = '${:,.2f}'.format(avgPrice)
purchases = purchase_data["Purchase ID"].count()
revenue = purchase_data["Price"].sum()
revenue = '${:,.2f}'.format(revenue)
summarydf = pd.DataFrame([{"Number of Unique Items":uniqueItems, "Average Price":avgPrice,
                         "Number of Purchases":purchases, "Total Revenue":revenue}])
summarydf<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>genderGroup = purchase_data.groupby(["Gender"])
percentages = (genderGroup['SN'].nunique()/purchase_data['SN'].nunique())*100
genderDf = pd.DataFrame({'Total Count':genderGroup['SN'].nunique(),
             'Percentage of Players': percentages})
genderDf['Percentage of Players'] = genderDf['Percentage of Players'].map("{:.2f}%".format)
genderDf = genderDf.sort_values(by='Total Count',ascending=False)
genderDf<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>genPurchDf = pd.DataFrame({
    'Purchase Count':genderGroup['Purchase ID'].count(),
    'Average Purchase Price': genderGroup['Price'].mean(),
    'Total Purchase Value': genderGroup['Price'].sum(),
    'Avg Total Purchase per Person': genderGroup['Price'].sum()/genderGroup['SN'].nunique()
})
genPurchDf['Average Purchase Price'] = genPurchDf['Average Purchase Price'].map("${:.2f}".format)
genPurchDf['Total Purchase Value'] = genPurchDf['Total Purchase Value'].map("${:.2f}".format)
genPurchDf['Avg Total Purchase per Person'] = genPurchDf['Avg Total Purchase per Person'].map("${:.2f}".format)

genPurchDf<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>bins = [-1, 9, 14, 19, 24, 29, 34, 39, purchase_data['Age'].max()]
labels = ["<10","10-14","15-19","20-24","25-29","30-34","35-39","40+"]
purchase_data['Age Range'] = pd.cut(purchase_data['Age'], bins, labels=labels)
ageGroup = purchase_data.groupby(["Age Range"])
percentages = (ageGroup['SN'].nunique()/purchase_data['SN'].nunique())*100
ageDf = pd.DataFrame({'Total Count':ageGroup['SN'].nunique(),
             'Percentage of Players': percentages})
ageDf['Percentage of Players'] = ageDf['Percentage of Players'].map("{:.2f}%".format)
ageDf<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>agePurchDf = pd.DataFrame({
    'Purchase Count':ageGroup['Purchase ID'].count(),
    'Average Purchase Price': ageGroup['Price'].mean(),
    'Total Purchase Value': ageGroup['Price'].sum(),
    'Avg Total Purchase per Person': ageGroup['Price'].sum()/ageGroup['SN'].nunique()
})
agePurchDf['Average Purchase Price'] = agePurchDf['Average Purchase Price'].map("${:.2f}".format)
agePurchDf['Total Purchase Value'] = agePurchDf['Total Purchase Value'].map("${:.2f}".format)
agePurchDf['Avg Total Purchase per Person'] = agePurchDf['Avg Total Purchase per Person'].map("${:.2f}".format)

agePurchDf<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>snGroup = purchase_data.groupby(['SN'])
snPurchDf = pd.DataFrame({
    'Purchase Count': snGroup['Purchase ID'].count(),
    'Average Purchase Price': snGroup['Price'].mean(),
    'Total Purchase Value': snGroup['Price'].sum()
})
snPurchDf = snPurchDf.sort_values(by=['Total Purchase Value'],ascending=False)
snPurchDf['Average Purchase Price'] = snPurchDf['Average Purchase Price'].map("${:.2f}".format)
snPurchDf['Total Purchase Value'] = snPurchDf['Total Purchase Value'].map("${:.2f}".format)


snPurchDf<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>itemDf = pd.DataFrame(purchase_data[['Purchase ID', 'Item ID', 'Item Name', 'Price']])
itemGroup = itemDf.groupby(['Item ID','Item Name'])
itemData = pd.DataFrame({
    'Purchase Count': itemGroup['Purchase ID'].count(),
    'Item Price': itemGroup['Price'].mean(),
    'Total Purchase Value': itemGroup['Price'].sum()
})
itemData = itemData.sort_values(by=['Purchase Count'],ascending=False)
itemData['Item Price'] = itemData['Item Price'].map("${:.2f}".format)
itemData['Total Purchase Value'] = itemData['Total Purchase Value'].map("${:.2f}".format)
itemData.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>profitData = pd.DataFrame({
    'Purchase Count': itemGroup['Purchase ID'].count(),
    'Item Price': itemGroup['Price'].mean(),
    'Total Purchase Value': itemGroup['Price'].sum()
})
profitData = profitData.sort_values(by=['Total Purchase Value'],ascending=False)
profitData['Item Price'] = profitData['Item Price'].map("${:.2f}".format)
profitData['Total Purchase Value'] = profitData['Total Purchase Value'].map("${:.2f}".format)
profitData.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13888138340988923, 'fraction_numerical': 0.00905160767360173, 'mean_word_length': 6.679460580912863, 'pattern_counts': {'":': 4, '<': 41, '<?xml version=': 0, '>': 40, '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': '292521', 'license': 'ADSL', 'n_tokens_mistral': 2322, 'n_tokens_neox': 2179, 'n_words': 652, 'path': 'HeroesOfPymoli/HeroesOfPymoli_starter.ipynb', 'repo_name': 'bhhnguyen/pandas-challenge', 'size': '7402'}