What you should Have to Start

Lesson Portion 1: ReIntroduction to Data Analysis, numpy, and Pandas, Why is it important?

Data Analysis.

  • Data Analysis is the process of examining data sets in order to find trends and draw conclusions about the given information. Data analysis is important because it helps businesses optimize their performances.

What is numpy and Pandas

  • Pandas library involves a lot of data analysis in Python. NumPy Library is mostly used for working with numerical values and it makes it easy to apply with mathematical functions.
  • Imagine you have a lot of toys, but they are all mixed up in a big box. NumPy helps you to put all the same types of toys together, like all the cars in one pile and all the dolls in another. Pandas is like a helper that helps you to remember where each toy is located. So, if you want to find a specific toy, like a red car, you can ask Pandas to find it for you.
  • Just like how it's easier to find a toy when they are sorted and organized, it's easier for grown-ups to understand and analyze big sets of numbers when they use NumPy and Pandas.

Lesson Portion 2 More into numpy

What we are covering;

  • Explanation of NumPy and its uses in data analysis
  • Importing NumPy library
  • Examining NumPy arrays
  • Creating NumPy arrays and performing intermediate array operations
  • Popcorn Hacks, Make your own percentile numpy array

What is numpy's use in data analysis/ how to import numpy.

NumPy is a tool in Python that helps with doing math and data analysis. It's great for working with large amounts of data, like numbers in a spreadsheet. NumPy is really good at doing calculations quickly and accurately, like finding averages, doing algebra, and making graphs. It's used a lot by scientists and people who work with data because it makes their work easier and faster.

import numpy as np

List of numpy Functions, what they do, and examples.

Example of Using numpy in Our Project

This code calculates the total plate appearances for a baseball player using NumPy's sum() function, similar to the original example. It then uses NumPy to calculate the total number of bases (hits plus walks) for the player, and divides that by the total number of plate appearances to get the on-base percentage. The results are then printed to the console.

import numpy as np

# Example data
player_hits = np.array([3, 1, 2, 0, 1, 2, 1, 2])  # Player's hits in each game
player_walks = np.array([1, 0, 0, 1, 2, 1, 1, 0])  # Player's walks in each game
player_strikeouts = np.array([2, 1, 0, 2, 1, 1, 0, 1])  # Player's strikeouts in each game

# array to store plate appearances (PA) for the player
total_pa = np.sum(player_hits != 0) + np.sum(player_walks) + np.sum(player_strikeouts)

# array to store on-base percentage (OBP) for the player
total_bases = np.sum(player_hits) + np.sum(player_walks)
obp = total_bases / total_pa

# Print the total plate appearances and on-base percentage for the player
print(f"Total plate appearances: {total_pa}")
print(f"On-base percentage: {obp:.3f}")

Activity 1; PopCorn Hacks; Creating a numpy Array and Analyzing the Data using Array Operations

import numpy as np

grades = np.array([89, 70, 94, 93, 79, 93, 86, 94, 100, 85, 84, 83, 74])
percentiles = np.percentile(grades, [25, 50, 75])

# Print the results
print("The 25th percentile grade is", str(percentiles[0]) + "%")
print("The 50th percentile grade is", str(percentiles[1]) + "%")
print("The 75th percentile grade is", str(percentiles[2]) + "%")

# Determine the number of players who are in the top 10% tallest
top_10_percent = np.percentile(grades, 90)
highest_grades = grades[grades >= top_10_percent]

print("There are", len(highest_grades), "students with the top 10% of grades; they have " + ", ".join(
    [str(grade) + "%" for grade in highest_grades]
))
The 25th percentile grade is 83.0%
The 50th percentile grade is 86.0%
The 75th percentile grade is 93.0%
There are 3 students with the top 10% of grades; they have 94%, 94%, 100%

Lesson Portion 3 More into Pandas

What we are Covering

  • Explanation of Pandas and its uses in data analysis
  • Importing Pandas library
  • Loading data into Pandas DataFrames from CSV files
  • Manipulating and exploring data in Pandas DataFrames
  • Example of using Pandas for data analysis tasks such as filtering and sorting

What are pandas and what is its purpose?

  • Pandas is a software library that is used in Python
  • Pandas are used for data analysis and data manipulation
  • Pandas offer data structures and operations for manipulating numerical tables and time series.
  • Pandas is free

Things you can do using pandas

  • Data Cleansing; Identifying and correcting errors, inconsistencies, and inaccuracies in datasets.
  • Data fill; Filling in missing values in datasets.
  • Statistical Analysis; Analyzing datasets using statistical techniques to draw conclusions and make predictions.
  • Data Visualization; Representing datasets visually using graphs, charts, and other visual aids.
  • Data inspection; Examining datasets to identify potential issues or patterns, such as missing data, outliers, or trends.

Pandas and Data analysis

The 2 most important data structures in Pandas are:

  • Series ; A Series is a one-dimensional labeled array that can hold data of any type (integer, float, string, etc.). It is similar to a column in a spreadsheet or a SQL table. Each element in a Series has a label, known as an index. A Series can be created from a list, a NumPy array, a dictionary, or another Pandas Series.
  • DataFrame ;A DataFrame is a two-dimensional labeled data structure that can hold data of different types (integer, float, string, etc.). It is similar to a spreadsheet or a SQL table. Each column in a DataFrame is a Series, and each row is indexed by a label, known as an index. A DataFrame can be created from a dictionary of Series or NumPy arrays, a list of dictionaries, or other Pandas DataFrame.

Dataframes

import pandas as pd
pd.__version__

Importing CSV Data

  • imports the Pandas library and assigns it an alias 'pd'.
  • Loads a CSV file named 'nba_player_statistics.csv' into a Pandas DataFrame called 'df'.
  • Specifies a player's name 'Jimmy Butler' to filter the DataFrame for that player's stats. It creates a new DataFrame called 'player_stats' which only contains rows where the 'NAME' column matches 'Jimmy Butler'.
  • Displays the player's stats for points per game (PPG), rebounds per game (RPG), and assists per game (APG) using the print() function and string formatting.
  • The code uses the double square brackets [[PPG', 'RPG', 'APG']] to select only the columns corresponding to the player's points per game, rebounds per game, and assists per game from the player_stats DataFrame.
  • In summary, the code loads NBA player statistics data from a CSV file, filters it for a specific player, and displays the stats for that player's PPG, RPG, and APG using a Pandas DataFrame.
import pandas as pd
# Load the CSV file into a Pandas DataFrame
df = pd.read_csv('nba_player_statistics.csv')
# Filter the DataFrame to only include stats for a specific player (in this case, Jimmy Butler)
player_name = 'Jimmy Butler'
player_stats = df[df['NAME'] == player_name]
# Display the stats for the player
print(f"\nStats for {player_name}:")
print(player_stats[['PPG', 'RPG', 'APG']])

In this code segment below we use Pandas to read a CSV file containing NBA player statistics and store it in a DataFrame.

The reason Pandas is useful in this scenario is because it provides various functionalities to filter, sort, and manipulate the NBA data efficiently. In this code, the DataFrame is filtered to only include the stats for the player you guys choose.

  • Imports the Pandas library and assigns it an alias 'pd'.
  • Loads a CSV file named 'nba_player_statistics.csv' into a Pandas DataFrame called 'df'.
  • Asks the user to input a player name using the input() function and assigns it to the variable player_name.
  • Filters the DataFrame for the specified player name using the df[df['NAME'] == player_name] syntax, and assigns the resulting DataFrame to the variable player_stats.
  • Checks if the player_stats DataFrame is empty using the empty attribute. If it is empty, prints "No stats found for that player." Otherwise, it proceeds to step 6.
  • Displays the player's stats for points per game (PPG), rebounds per game (RPG), assists per game (APG), and total points + rebounds + assists (P+R+A) using the print() function and string formatting.
  • In summary, this code loads NBA player statistics data from a CSV file, asks the user to input a player name, filters the DataFrame for that player's stats, and displays the player's stats for PPG, RPG, APG, and P+R+A. If the player is not found in the DataFrame, it prints a message indicating that no stats were found.
import pandas as pd
df = pd.read_csv('nba_player_statistics.csv')
# Load CSV file into a Pandas DataFrame
player_name = input("Enter player name: ")
# Get player name input from user
player_stats = df[df['NAME'] == player_name]
# Filter the DataFrame to only include stats for the specified player
if player_stats.empty:
    print("No stats found for that player.")
else:
# Check if the player exists in the DataFrame
    print(f"\nStats for {player_name}:")
print(player_stats[['PPG', 'RPG', 'APG', 'P+R+A']])
# Display the stats for the player inputted.

Lesson Portion 4

What we will be covering

  • Example of analyzing data using both NumPy and Pandas libraries
  • Importing data into NumPy and Pandas Performing basic data analysis tasks such as mean, median, and standard deviation Visualization of data using Matplotlib library

Example of analyzing data using both NumPy and Pandas libraries

import numpy as np
import pandas as pd

# Load CSV file into a Pandas DataFrame

df = pd.read_csv('nba_player_statistics.csv')

# Filter the DataFrame to only include stats for the specified player

player_name = input("Enter player name: ")
player_stats = df[df['NAME'] == player_name]
if player_stats.empty:
    print("No stats found for that player.")
else:

    # Convert the player stats to a NumPy array
    player_stats_np = np.array(player_stats[['PPG', 'RPG', 'APG', 'P+R+A']])

    # Calculate the average of each statistic for the player

    player_stats_avg = np.mean(player_stats_np, axis=0)

    # Print out the average statistics for the player

    print(f"\nAverage stats for {player_name}:")
    print(f"PPG: {player_stats_avg[0]:.2f}")
    print(f"RPG: {player_stats_avg[1]:.2f}")
    print(f"APG: {player_stats_avg[2]:.2f}")
    print(f"P+R+A: {player_stats_avg[3]:.2f}")
Average stats for LeBron James:
PPG: 21.00
RPG: 11.00
APG: 5.00
P+R+A: 37.00

NumPy impacts the given code because it performs operations on arrays efficiently. Specifically, it converts a Pandas DataFrame object to a NumPy array object, and then calculates the average statistics for a the player you guys inputted. Without NumPy, it would be more difficult and less efficient to perform these calculations on large data sets. It does the math for us.

Importing data into NumPy and Pandas Performing basic data analysis tasks such as mean, median, and standard deviation Visualization of data using Matplotlib library

Matplotlib is used essentially to create visuals of data. charts,diagrams,etc.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Load the CSV file into a Pandas DataFrame
df = pd.read_csv('nba_player_statistics.csv')

# Print the first 5 rows of the DataFrame
print(df.head())

# Calculate the mean, median, and standard deviation of the 'Points' column
mean_minutes = df['MPG'].mean()
median_minutes = df['MPG'].median()
stddev_minutes = df['MPG'].std()

# Print the results
print('Mean Minutes: ', mean_minutes)
print('Median Minutes: ', median_minutes)
print('Standard Deviation Minutes: ', stddev_minutes)

# Create a histogram of the 'Points' column using Matplotlib
plt.hist(df['MPG'], bins=20)
plt.title('MPG Histogram')
plt.xlabel('MPG')
plt.ylabel('Frequency')
plt.show()

In this example code, we first import the necessary libraries, including NumPy, Pandas, and Matplotlib. We then load the CSV file into a Pandas DataFrame using the pd.read_csv() function. We print the first 5 rows of the DataFrame using the df.head() function. Next, we calculate the mean, median, and standard deviation of the 'MPG' column using the appropriate Pandas methods, and print the results. And, we create a histogram of the 'MPG' column using Matplotlib by calling the plt.hist() function and setting appropriate axis labels and a title. We then call the plt.show() method to display the plot. Even though NumPy is not directly used in this code, it is an important underlying component of the pandas and Matplotlib libraries, which are used to load, manipulate and visualize data. It allows them to work more efficiently

Lesson Portion 5; Summary

Summary/Goals of Lesson:

One of our goals was to make you understand data analysis and how it can be important in optimizing business performance. We also wanted to make sure you understood the use of Pandas and NumPy libraries in data analysis, with a focus on NumPy. As someone who works with data, we find Pandas incredibly useful for manipulating, analyzing, and visualizing data in Python. The way we use pandas is to calculate individual player and team statistics. We are a group that works with numerical data, so NumPy is one of our favorite tools for working with arrays and applying mathematical functions to them. It is very fast at computing and manipulating arrays making it a very valuable tool for tracking statistics which is important to our group. For example, if you have an array of the points scored by each player in a game, you can use NumPy to calculate the total points scored, average points per player, or the highest and lowest scoring players.

Lesson Portion 6 Hacks

Printing a CSV File (0.5)

  • Use this link https://github.com/ali-ce/datasets to select csv file of a topic you are interested in, or you may find one online.
  • Once you select your topic make sure it is a csv file and then you want to press on the button that says raw.
  • After that copy that information and create a file with a name and .csv at the end and paste your information.
  • Below is a start that you can use for your hacks.
  • Your goal is to print 2 specific parts from data (example could be like population and country).

Popcorn Hacks (0.2)

  • Lesson Portion 1. #### Answering Questions (0.2)
  • Found Below.

Submit By Thursday 8:35 A.M.

  • How to Submit: Slack a Blog Post that includes all of your hacks to "Joshua Williams" on Slack.
import pandas as pd
# read the CSV file
df = pd.read_csv("insurance.csv")

# select and parse a few columns
domains = df["Domain"].tolist()
prices = df["Price"].str.replace(',', '').str.replace('$', '').str.replace('£', '').astype(float).tolist()
years = df["Year of sale"].tolist()

# print the parsed columns
print("Domains:", domains)
print("Prices:", prices)
print("Years:", years)

# display the data in a table
print(df)
Domains: ['AltaVista.com', 'Asseenontv.com', 'Beer.com', 'Business.com', 'Candy.com', 'Casino.com', 'Clothes.com', 'Diamond.com', 'Fb.com', 'Fund.com', 'GiftCard.com', 'Hotels.com ', 'iCloud.com', 'IG.com', 'Insurance.com ', 'Insure.com ', 'Internet.com ', 'Loans.com', 'Medicare.com', 'Mi.com', 'Porn.com', 'PrivateJet.com ', 'Sex.com', 'Slots.com ', 'Toys.com', 'VacationRentals.com ', 'Whisky.com', 'Yp.com']
Prices: [3300000.0, 5100000.0, 7000000.0, 7500000.0, 3000000.0, 5500000.0, 4900000.0, 7500000.0, 8500000.0, 9990000.0, 4000000.0, 11000000.0, 6000000.0, 4600000.0, 35600000.0, 16000000.0, 18000000.0, 3000000.0, 4800000.0, 3600000.0, 9500000.0, 30100000.0, 14000000.0, 5500000.0, 5100000.0, 35000000.0, 3100000.0, 3800000.0]
Years: [1998, 2000, 2004, 1999, 1009, 2003, 2008, 2006, 2010, 2008, 2012, 2001, 2011, 2013, 2010, 2009, 2009, 2000, 2014, 2014, 2007, 2012, 2010, 2010, 2009, 2007, 2013, 2008]
                  Domain        Price  Year of sale
0          AltaVista.com   $3,300,000          1998
1         Asseenontv.com   $5,100,000          2000
2               Beer.com   $7,000,000          2004
3           Business.com   $7,500,000          1999
4              Candy.com   $3,000,000          1009
5             Casino.com   $5,500,000          2003
6            Clothes.com   $4,900,000          2008
7            Diamond.com   $7,500,000          2006
8                 Fb.com   $8,500,000          2010
9               Fund.com   £9,990,000          2008
10          GiftCard.com   $4,000,000          2012
11           Hotels.com   $11,000,000          2001
12            iCloud.com   $6,000,000          2011
13                IG.com   $4,600,000          2013
14        Insurance.com   $35,600,000          2010
15           Insure.com   $16,000,000          2009
16         Internet.com   $18,000,000          2009
17             Loans.com   $3,000,000          2000
18          Medicare.com   $4,800,000          2014
19                Mi.com   $3,600,000          2014
20              Porn.com   $9,500,000          2007
21       PrivateJet.com   $30,100,000          2012
22               Sex.com  $14,000,000          2010
23            Slots.com    $5,500,000          2010
24              Toys.com   $5,100,000          2009
25  VacationRentals.com   $35,000,000          2007
26            Whisky.com   $3,100,000          2013
27                Yp.com   $3,800,000          2008
/tmp/ipykernel_1341/2301951595.py:7: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.
  prices = df["Price"].str.replace(',', '').str.replace('$', '').str.replace('£', '').astype(float).tolist()

Question Hacks;

What is NumPy and how is it used in data analysis?

NumPy, short for Numerical Python, is a popular library in Python that offers powerful tools for numerical computing. It's particularly useful in data analysis for its ability to handle large, multi-dimensional arrays and perform efficient mathematical operations. With NumPy, analysts can quickly manipulate and process data, making it an essential tool for tasks like statistical analysis, linear algebra, and more.

What is Pandas and how is it used in data analysis?

Pandas is another powerful Python library designed for data manipulation and analysis. It introduces two key data structures: Series and DataFrame, which simplify handling and processing large datasets. Pandas enables easy data cleaning, filtering, aggregation, and visualization, making it an indispensable tool for data analysts working with structured data.

How is numpy different than Pandas for data analysis?

While both NumPy and Pandas are essential for data analysis, their primary difference lies in the data structures they handle. NumPy is more focused on numerical arrays and mathematical operations, whereas Pandas excels at handling structured data through Series and DataFrames. Though Pandas is built on top of NumPy, it offers additional functionalities like data alignment, handling missing data, and advanced indexing, making it more suitable for complex data analysis tasks.

What is a DataFrame?

A DataFrame is a two-dimensional, size-mutable, and heterogeneous data structure provided by the Pandas library. It resembles a table with rows and columns, where each column can have a different data type. DataFrames allow for efficient data manipulation, indexing, and slicing, making them an ideal tool for handling structured data in data analysis.

What are some common operations you can perform with numpy?

With NumPy, you can perform a wide range of operations, including array creation, reshaping, slicing, and indexing. Additionally, NumPy offers mathematical functions like addition, subtraction, multiplication, and division, along with more advanced operations such as linear algebra, statistics, and element-wise functions.

How Can You Incorporate Either of these Data Analysis Tools (numpy, Pandas) into your project?

Incorporating NumPy or Pandas into your project is straightforward. First, you'll need to install the libraries using pip or another package manager. Once installed, you can import them into your Python script with import numpy as np or import pandas as pd. Then, you can leverage their powerful functionalities to analyze, manipulate, and process your data more efficiently, allowing you to focus on generating valuable insights for your project.