<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 = os.path.join('Resources', 'purchase_data.csv')

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

#display dataframe
purchase_data_df.head()<jupyter_output><empty_output><jupyter_text>Player Count * Display the total number of players<jupyter_code>#find unique user names in the data frame 
uniquenames = purchase_data_df['SN'].nunique()

#create a dataframe for total players
total_players_df = pd.DataFrame({'Total Players': [uniquenames]})

#display dataframe
total_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>#Finding number of unique items
unique_items = purchase_data_df['Item Name'].nunique()

#Finding average price, amount of purchases, and total revenue
average_price = purchase_data_df['Price'].mean()
purchases_amount = len(purchase_data_df['Price'])
total_rev = purchase_data_df['Price'].sum()

#Create sum table with new dataframe
summary_purchases_df = pd.DataFrame({
    "Unique Items": [unique_items],
    "Average Sale Price": [average_price],
    "Amount of Purchases": [purchases_amount],
    "Total Revenue": [total_rev]
})

#add format to prices and revenue
summary_purchases_df['Average Sale Price'] = summary_purchases_df['Average Sale Price'].map("${:.2f}".format)
summary_purchases_df['Total Revenue'] = summary_purchases_df['Total Revenue'].map("${:.2f}".format)

#display dataframe
summary_purchases_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>#create a gender group
gender_group = purchase_data_df.groupby(['Gender'])

#count the totals of each gender and calculate the percentages
count = gender_group['SN'].nunique()
percentage = count / uniquenames * 100

#create new data frame for gender summary
gender_df = pd.DataFrame({'Total count': count, 
                          'Percentages': percentage
                         })

#add format to percentage column
gender_df['Percentages'] = gender_df['Percentages'].map("{:.2f}%".format)

#sort the values so that highest value(male) is first
gender_df = gender_df.sort_values('Percentages', ascending=False)

#display dataframe
gender_df<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>#create variables for basic calcualtions
total_purchases_gender = gender_group['Item Name'].count()
average_price_gender = gender_group['Price'].mean()
total_purchase_val = gender_group['Price'].sum()
purchases_per_person = total_purchase_val / count

#create sum table with new dataframe
calc_gender_df = pd.DataFrame({'Purchase count': total_purchases_gender, 
                               'Average Purchase Price': average_price_gender, 
                               'Total Purchase Value': total_purchase_val, 
                               'Average Total Purchase/Person': purchases_per_person
                              })

#fix format for prices
calc_gender_df['Average Purchase Price'] = calc_gender_df['Average Purchase Price'].map("${:.2f}".format)
calc_gender_df['Total Purchase Value'] = calc_gender_df['Total Purchase Value'].map("${:.2f}".format)
calc_gender_df['Average Total Purchase/Person'] = calc_gender_df['Average Total Purchase/Person'].map("${:.2f}".format)

#display dataframe
calc_gender_df.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>#creating bins and labels for set age ranges
bins = [0, 9.9, 14.9, 19.9, 24.9, 29.9, 34.9, 39.9, 100]
bin_labels = ['< 10', '10-14', '15-19', '20-24', '25-29', '30-34', '35-39', '> 40']
purchase_data_df['Age Range'] = pd.cut(purchase_data_df['Age'], bins, labels=bin_labels)

#create a group to categorize range of ages
age_group = purchase_data_df.groupby(['Age Range'])

#create variables for total for each range and percentages
total_arange = age_group['SN'].nunique()
total_arange_p = total_arange / uniquenames * 100
#sum table with a new dataframe
age_df = pd.DataFrame({'Total count': total_arange, 
                    'Percentage of Players': total_arange_p
                      }) 

#fixing percentage format
age_df['Percentage of Players'] = age_df['Percentage of Players'].map("{:.2f}%".format)

#display sum table
age_df<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>#find unique user names in each age group
age_unique = age_group['SN'].nunique()

#create variables for calculations in purchase count, average purchase price, etc.
age_pcount = age_group['Item Name'].count()
age_avg_pcount = age_group['Price'].mean()
age_ptotal = age_group['Price'].sum()
age_avg_totalper = age_ptotal / age_unique

#create dataframe for new sum table
age_sum_purchase_df = pd.DataFrame({'Purchase Count': age_pcount, 
                                    'Average Purchase Price': age_avg_pcount, 
                                    'Total Purchases ($)': age_ptotal, 
                                    'Avg Total ($) / Person': age_avg_totalper
                                   })

#format prices and round
age_sum_purchase_df['Average Purchase Price'] = age_sum_purchase_df['Average Purchase Price'].map("${:.2f}".format)
age_sum_purchase_df['Total Purchases ($)'] = age_sum_purchase_df['Total Purchases ($)'].map("${:.2f}".format)
age_sum_purchase_df['Avg Total ($) / Person'] = age_sum_purchase_df['Avg Total ($) / Person'].map("${:.2f}".format)

#display summary dataframe for ages
age_sum_purchase_df<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>#create a group for usernames
user_group = purchase_data_df.groupby(['SN'])

#create variable for purchases per user
purchasetotal = purchase_data_df['SN'].value_counts()
totalperuser = user_group['Price'].sum()
avgperuser = totalperuser / purchasetotal

#create sum table with new dataframe
user_df = pd.DataFrame({'Purchase Count': purchasetotal, 
                        'Average Purchase ($)': avgperuser, 
                        'Total Purchase ($)': totalperuser
                       })

#sort the values so that total purchase price is at its highest
user_df = user_df.sort_values('Total Purchase ($)', ascending=False)

#format price values
user_df['Average Purchase ($)'] = user_df['Average Purchase ($)'].map("${:.2f}".format)
user_df['Total Purchase ($)'] = user_df['Total Purchase ($)'].map("${:.2f}".format)

#display sum dataframe for users
user_df.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, average 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>#create group for item id and Item Name
group_id = purchase_data_df.groupby(['Item ID', 'Item Name'])

#create variables to calculate purchases
item_idpurchase = group_id['Purchase ID'].count()
item_idtotal = group_id['Price'].sum()
item_idcost = item_idtotal / item_idpurchase

#create sum table for data frame
item_id_df = pd.DataFrame({'Purchase Count': item_idpurchase, 
                           'Item Price ($)': item_idcost, 
                           'Total Purchase ($)': item_idtotal
                          })

#sort purchase column in descending order
item_id_df = item_id_df.sort_values(['Purchase Count'], ascending=False)

#format price values
item_id_df['Item Price ($)'] = item_id_df['Item Price ($)'].map("${:.2f}".format)
item_id_df['Total Purchase ($)'] = item_id_df['Total Purchase ($)'].map("${:.2f}".format)

#display sum id dataframe
item_id_df.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>#create sum table for most profit chart
most_profit_df = pd.DataFrame({'Purchase Count': item_idpurchase, 
                               'Item Price ($)': item_idcost, 
                               'Total Purchase ($)': item_idtotal 
                              })

#sort total purchasae column in descending order
most_profit_df = most_profit_df.sort_values(['Total Purchase ($)'], ascending=False)

#format price values
most_profit_df['Item Price ($)'] = most_profit_df['Item Price ($)'].map("${:.2f}".format)
most_profit_df['Total Purchase ($)'] = most_profit_df['Total Purchase ($)'].map("${:.2f}".format)

#display sum id dataframe
most_profit_df.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10689455388180764, 'fraction_numerical': 0.007145616067979915, 'mean_word_length': 4.565287479849543, 'pattern_counts': {'":': 4, '<': 42, '<?xml version=': 0, '>': 42, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '465551', 'license': 'MIT', 'n_tokens_mistral': 3155, 'n_tokens_neox': 2970, 'n_words': 942, 'path': 'HeroesOfPymoli/HeroesOfPymoli_starter.ipynb', 'repo_name': 'alexmartinez1745/Pandas-Challenge', 'size': '10356'}