Pandas and DataFrames

In this lesson we will be exploring data analysis using Pandas.

  • College Board talks about ideas like
    • Tools. "the ability to process data depends on users capabilities and their tools"
    • Combining Data. "combine county data sets"
    • Status on Data"determining the artist with the greatest attendance during a particular month"
    • Data poses challenge. "the need to clean data", "incomplete data"
  • From Pandas Overview -- When working with tabular data, such as data stored in spreadsheets or databases, pandas is the right tool for you. pandas will help you to explore, clean, and process your data. In pandas, a data table is called a DataFrame.
from PIL import Image
dfimage = Image.open("../_notebooks/files/table_dataframe.png")
display(dfimage)
'''Pandas is used to gather data sets through its DataFrames implementation'''
import pandas as pd

Cleaning Data

When looking at a data set, check to see what data needs to be cleaned. Examples include:

  • Missing Data Points
  • Invalid Data
  • Inaccurate Data

Run the following code to see what needs to be cleaned

df = pd.read_json('files/grade.json')

print(df)
# What part of the data set needs to be cleaned?
# The data which needs to be cleaned are the ones which are inconsistent(ex. words for grades, no student ids)

# From PBL learning, what is a good time to clean data?  Hint, remember Garbage in, Garbage out?
# A good time to clean would be when we are getting the data in. So, we could remove the garbage when getting data from the dataframe.
   Student ID Year in School   GPA
0         123             12  3.57
1         246             10  4.00
2         578             12  2.78
3         469             11  3.45
4         324         Junior  4.75
5         313             20  3.33
6         145             12  2.95
7         167             10  3.90
8         235      9th Grade  3.15
9         nil              9  2.80
10        469             11  3.45
11        456             10  2.75

Extracting Info

Take a look at some features that the Pandas library has that extracts info from the dataset

DataFrame Extract Column

print(df[['GPA']])

print()

#try two columns and remove the index from print statement
print(df[['Student ID','GPA']].to_string(index=False))
     GPA
0   3.57
1   4.00
2   2.78
3   3.45
4   4.75
5   3.33
6   2.95
7   3.90
8   3.15
9   2.80
10  3.45
11  2.75

Student ID  GPA
       123 3.57
       246 4.00
       578 2.78
       469 3.45
       324 4.75
       313 3.33
       145 2.95
       167 3.90
       235 3.15
       nil 2.80
       469 3.45
       456 2.75

DataFrame Sort

print(df.sort_values(by=['GPA']))

print()

#sort the values in reverse order
print(df.sort_values(by=['GPA'], ascending=False))
   Student ID Year in School   GPA
11        456             10  2.75
2         578             12  2.78
9         nil              9  2.80
6         145             12  2.95
8         235      9th Grade  3.15
5         313             20  3.33
3         469             11  3.45
10        469             11  3.45
0         123             12  3.57
7         167             10  3.90
1         246             10  4.00
4         324         Junior  4.75

   Student ID Year in School   GPA
4         324         Junior  4.75
1         246             10  4.00
7         167             10  3.90
0         123             12  3.57
3         469             11  3.45
10        469             11  3.45
5         313             20  3.33
8         235      9th Grade  3.15
6         145             12  2.95
9         nil              9  2.80
2         578             12  2.78
11        456             10  2.75

DataFrame Selection or Filter

print(df[df.GPA > 3.00])
   Student ID Year in School   GPA
0         123             12  3.57
1         246             10  4.00
3         469             11  3.45
4         324         Junior  4.75
5         313             20  3.33
7         167             10  3.90
8         235      9th Grade  3.15
10        469             11  3.45

DataFrame Selection Max and Min

print(df[df.GPA == df.GPA.max()])
print()
print(df[df.GPA == df.GPA.min()])
  Student ID Year in School   GPA
4        324         Junior  4.75

   Student ID Year in School   GPA
11        456             10  2.75

Create your own DataFrame

Using Pandas allows you to create your own DataFrame in Python.

Python Dictionary to Pandas DataFrame

import pandas as pd

#the data can be stored as a python dictionary
dict = {
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}
#stores the data in a data frame
print("-------------Dict_to_DF------------------")
df = pd.DataFrame(dict)
print(df)

print("----------Dict_to_DF_labels--------------")

#or with the index argument, you can label rows.
df = pd.DataFrame(dict, index = ["day1", "day2", "day3"])
print(df)
-------------Dict_to_DF------------------
   calories  duration
0       420        50
1       380        40
2       390        45
----------Dict_to_DF_labels--------------
      calories  duration
day1       420        50
day2       380        40
day3       390        45

Examine DataFrame Rows

print("-------Examine Selected Rows---------")
#use a list for multiple labels:
print(df.loc[["day1", "day3"]])

#refer to the row index:
print("--------Examine Single Row-----------")
print(df.loc["day1"])
-------Examine Selected Rows---------
      calories  duration
day1       420        50
day3       390        45
--------Examine Single Row-----------
calories    420
duration     50
Name: day1, dtype: int64

Pandas DataFrame Information

print(df.info())
<class 'pandas.core.frame.DataFrame'>
Index: 3 entries, day1 to day3
Data columns (total 2 columns):
 #   Column    Non-Null Count  Dtype
---  ------    --------------  -----
 0   calories  3 non-null      int64
 1   duration  3 non-null      int64
dtypes: int64(2)
memory usage: 180.0+ bytes
None

Example of larger data set

Pandas can read CSV and many other types of files, run the following code to see more features with a larger data set

import pandas as pd

#read csv and sort 'Duration' largest to smallest
df = pd.read_csv('files/data.csv').sort_values(by=['Duration'], ascending=False)

print("--Duration Top 10---------")
print(df.head(10))

print("--Duration Bottom 10------")
print(df.tail(10))
--Duration Top 10---------
     Duration  Pulse  Maxpulse  Calories
69        300    108       143    1500.2
79        270    100       131    1729.0
109       210    137       184    1860.4
60        210    108       160    1376.0
106       180     90       120     800.3
90        180    101       127     600.1
65        180     90       130     800.4
61        160    110       137    1034.4
62        160    109       135     853.0
67        150    107       130     816.0
--Duration Bottom 10------
     Duration  Pulse  Maxpulse  Calories
68         20    106       136     110.4
100        20     95       112      77.7
89         20     83       107      50.3
135        20    136       156     189.0
94         20    150       171     127.4
95         20    151       168     229.4
139        20    141       162     222.4
64         20    110       130     131.4
112        15    124       139     124.2
93         15     80       100      50.5

APIs are a Source for Writing Programs with Data

3rd Party APIs are a great source for creating Pandas Data Frames.

  • Data can be fetched and resulting json can be placed into a Data Frame
  • Observe output, this looks very similar to a Database
'''Pandas can be used to analyze data'''
import pandas as pd
import requests

def fetch():
    '''Obtain data from an endpoint'''
    url = "https://flask.nighthawkcodingsociety.com/api/covid/"
    fetch = requests.get(url)
    json = fetch.json()

    # filter data for requirement
    df = pd.DataFrame(json['countries_stat'])  # filter endpoint for country stats
    print(df.loc[0:5, 'country_name':'deaths']) # show row 0 through 5 and columns country_name through deaths
    
fetch()
  country_name       cases     deaths
0          USA  82,649,779  1,018,316
1        India  43,057,545    522,193
2       Brazil  30,345,654    662,663
3       France  28,244,977    145,020
4      Germany  24,109,433    134,624
5           UK  21,933,206    173,352

Hacks

Early Seed award

  • Add this Blog to you own Blogging site.
  • Have all lecture files saved to your files directory before Tech Talk starts. Have data.csv open in vscode. Don't tell anyone. Show to Teacher.

AP Prep

  • Add this Blog to you own Blogging site. In the Blog add notes and observations on each code cell.
  • In blog add College Board practice problems for 2.3.

The next 4 weeks, Teachers want you to improve your understanding of data. Look at the blog and others on Unit 2. Your intention is to find some things to differentiate your individual College Board project.

  • Create or Find your own dataset. The suggestion is to use a JSON file, integrating with your PBL project would be Fambulous.
When choosing a data set, think about the following:- Does it have a good sample size?    - Is there bias in the data?
- Does the data set need to be cleaned?
- What is the purpose of the data set?
- ...
  • Continue this Blog using Pandas extract info from that dataset (ex. max, min, mean, median, mode, etc.)

Hack Helpers

Here is how Mort started on this assignment by asking ChatGPT ... Regarding Python Pandas, what are some data sets that would be good for learning Pandas?

  • There are many data sets that are suitable for learning pandas, depending on your interests and the skills you want to develop. Here are some suggestions:- Titanic Dataset: This is a classic dataset for data analysis and machine learning, and is often used as an introduction to pandas. The dataset contains information about passengers on the Titanic, including their demographics, ticket class, and survival status.

    • Iris Dataset: This is another classic dataset that is often used in machine learning and data analysis courses. The dataset contains information about iris flowers, including their sepal length, sepal width, petal length, and petal width.

    • NBA Player Stats: This dataset contains information about NBA players, including their stats for various games, their positions, and their salaries. It is a great dataset for learning how to clean and manipulate data using pandas.

    • Housing Prices Dataset: This dataset contains information about housing prices in a particular city or region, including variables such as the number of bedrooms, square footage, and price. It is a great dataset for learning how to manipulate and analyze numerical data using pandas.

    • COVID-19 Dataset: This dataset contains information about the COVID-19 pandemic, including the number of cases, deaths, and recoveries in various countries and regions. It is a great dataset for learning how to manipulate and analyze time-series data using pandas.

    • World Bank Dataset: This dataset contains information about economic indicators from various countries, such as GDP, population, and poverty rates. It is a great dataset for learning how to manipulate and analyze large datasets using pandas.

  • These are just a few examples of the many datasets that are suitable for learning pandas. The best dataset for you will depend on your interests and the specific skills you want to develop.

    Follow up question, "where can I find Titanic data set?"

  • The Titanic dataset is a popular dataset for data analysis and machine learning, and it can be found on various websites and data repositories. Here are a few places where you can find the Titanic dataset:- Kaggle: The Titanic dataset is available on Kaggle, which is a popular platform for data scientists and machine learning enthusiasts. You can download the dataset from the Kaggle website after creating an account.

    • UCI Machine Learning Repository: The Titanic dataset is also available on the UCI Machine Learning Repository, which is a collection of datasets that are commonly used for machine learning research. You can download the dataset from the UCI Machine Learning Repository website.

    • Seaborn library: If you have the Seaborn library installed in your Python environment, you can load the Titanic dataset directly from the library using the following code:

      import seaborn as sns
      titanic_data = sns.load_dataset('titanic')
      

Titanic Data

Look at a sample of data.

import seaborn as sns

# Load the titanic dataset
titanic_data = sns.load_dataset('titanic')

print("Titanic Data")


print(titanic_data.columns) # titanic data set

print(titanic_data[['survived','pclass', 'sex', 'age', 'sibsp', 'parch', 'class', 'fare', 'embark_town']]) # look at selected columns

Use Pandas to clean the data. Most analysis, like Machine Learning or even Pandas in general like data to be in standardized format. This is called 'Training' or 'Cleaning' data.

# Preprocess the data
from sklearn.preprocessing import OneHotEncoder


td = titanic_data
td.drop(['alive', 'who', 'adult_male', 'class', 'embark_town', 'deck'], axis=1, inplace=True)
td.dropna(inplace=True)
td['sex'] = td['sex'].apply(lambda x: 1 if x == 'male' else 0)
td['alone'] = td['alone'].apply(lambda x: 1 if x == True else 0)

# Encode categorical variables
enc = OneHotEncoder(handle_unknown='ignore')
enc.fit(td[['embarked']])
onehot = enc.transform(td[['embarked']]).toarray()
cols = ['embarked_' + val for val in enc.categories_[0]]
td[cols] = pd.DataFrame(onehot)
td.drop(['embarked'], axis=1, inplace=True)
td.dropna(inplace=True)

print(td)

The result of 'Training' data is making it easier to analyze or make conclusions. In looking at the Titanic, as you clean you would probably want to make assumptions on likely chance of survival.

This would involve analyzing various factors (such as age, gender, class, etc.) that may have affected a person's chances of survival, and using that information to make predictions about whether an individual would have survived or not.

  • Data description:- Survival - Survival (0 = No; 1 = Yes). Not included in test.csv file. - Pclass - Passenger Class (1 = 1st; 2 = 2nd; 3 = 3rd)

    • Name - Name
    • Sex - Sex
    • Age - Age
    • Sibsp - Number of Siblings/Spouses Aboard
    • Parch - Number of Parents/Children Aboard
    • Ticket - Ticket Number
    • Fare - Passenger Fare
    • Cabin - Cabin
    • Embarked - Port of Embarkation (C = Cherbourg; Q = Queenstown; S = Southampton)
  • Perished Mean/Average

print(titanic_data.query("survived == 0").mean())
  • Survived Mean/Average
print(td.query("survived == 1").mean())

Survived Max and Min Stats

print(td.query("survived == 1").max())
print(td.query("survived == 1").min())

Machine Learning

From Tutorials Point%20is,a%20consistence%20interface%20in%20Python). Scikit-learn (Sklearn) is the most useful and robust library for machine learning in Python. It provides a selection of efficient tools for machine learning and statistical modeling including classification, regression, clustering and dimensionality reduction via a consistence interface in Python.> Description from ChatGPT. The Titanic dataset is a popular dataset for data analysis and machine learning. In the context of machine learning, accuracy refers to the percentage of correctly classified instances in a set of predictions. In this case, the testing data is a subset of the original Titanic dataset that the decision tree model has not seen during training......After training the decision tree model on the training data, we can evaluate its performance on the testing data by making predictions on the testing data and comparing them to the actual outcomes. The accuracy of the decision tree classifier on the testing data tells us how well the model generalizes to new data that it hasn't seen before......For example, if the accuracy of the decision tree classifier on the testing data is 0.8 (or 80%), this means that 80% of the predictions made by the model on the testing data were correct....Chance of survival could be done using various machine learning techniques, including decision trees, logistic regression, or support vector machines, among others.

  • Code Below prepares data for further analysis and provides an Accuracy. IMO, you would insert a new passenger and predict survival. Datasets could be used on various factors like prediction if a player will hit a Home Run, or a Stock will go up or down.
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Split arrays or matrices into random train and test subsets.
X = td.drop('survived', axis=1)
y = td['survived']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Train a decision tree classifier
dt = DecisionTreeClassifier()
dt.fit(X_train, y_train)

# Test the model
y_pred = dt.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('DecisionTreeClassifier Accuracy:', accuracy)

# Train a logistic regression model
logreg = LogisticRegression()
logreg.fit(X_train, y_train)

# Test the model
y_pred = logreg.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('LogisticRegression Accuracy:', accuracy)

My Hacks

Testing Pandas by myself

I have decided to use a csv file to get my data. This csv file has data from the top streamed songs on Spotify.

  • Spotify contains many songs of many different genres, so this provides a very large sample size.
  • There is not bias in data for the top streamed songs in the data, since this is numerical data. However, this does not represent the most popular songs of all time because songs released when Spotify was an app are more likely to be streamed on Spotify, rather than older songs.
  • The data set is maintained by a user on kaggle, so there does not need to be cleaning.
  • The purpose of this data set is to track the top streamed songs on Spotify.
import pandas as pd
streamdf = pd.read_csv('files/streams.csv') # using csv file for top streamed spotify songs

topsong = streamdf.iloc[0]
streams = streamdf["Streams (Billions)"]
meanstreams = streams.mean()
topstreams = streamdf[streamdf["Streams (Billions)"] > 2.5]

print("The top streamed song on Spotify is:")
print(topsong)
print("--- Break ---")
print("The mean number of streams(in billions) of songs on this database:")
print(meanstreams)
print("--- Break ---")
print("The songs with over 2.5 billion streams are:")
print(topstreams)
The top streamed song on Spotify is:
Song                  Blinding Lights
Artist                     The Weeknd
Streams (Billions)              3.449
Release Date                29-Nov-19
Name: 0, dtype: object
--- Break ---
The mean number of streams of songs on this database:
1.895999999999999
--- Break ---
The songs with over 2.5 billion streams are:
                Song                           Artist  Streams (Billions)  \
0    Blinding Lights                       The Weeknd               3.449   
1       Shape of You                       Ed Sheeran               3.398   
2       Dance Monkey                      Tones And I               2.770   
3  Someone You Loved                    Lewis Capaldi               2.680   
4           Rockstar  Post Malone featuring 21 Savage               2.620   
5          Sunflower         Post Malone and Swae Lee               2.575   
6          One Dance  Drake featuring Wizkid and Kyla               2.556   

  Release Date  
0    29-Nov-19  
1    06-Jan-17  
2    10-May-19  
3    08-Nov-18  
4    15-Sep-17  
5    18-Oct-18  
6    05-Apr-16  

Working with others

Adi and Alex decided to use the tips dataframe, so I decided to work with them. We first imported the dataframe and figured out the columns of the database.

import seaborn as sns

# Load the titanic dataset
tips_data = sns.load_dataset('tips')

print("Tips Data")


print(tips_data.columns) # titanic data set fr

print(tips_data.head())
Tips Data
Index(['total_bill', 'tip', 'sex', 'smoker', 'day', 'time', 'size'], dtype='object')
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3
3       23.68  3.31    Male     No  Sun  Dinner     2
4       24.59  3.61  Female     No  Sun  Dinner     4

Then, we decided to change some of the properties inside the dataframe and add new columns.

from sklearn.preprocessing import OneHotEncoder

td = tips_data

td['sex'] = td['sex'].apply(lambda x: 1 if x == 'Male' else 0)
td['time'] = td['time'].apply(lambda x: 1 if x == 'Dinner' else 0)

td['percentage'] = (td['tip']/td['total_bill']) * 100

print(td.head())
   total_bill   tip  sex smoker  day  time  size  percentage
0       16.99  1.01    0     No  Sun     0     2    5.944673
1       10.34  1.66    0     No  Sun     0     3   16.054159
2       21.01  3.50    0     No  Sun     0     3   16.658734
3       23.68  3.31    0     No  Sun     0     2   13.978041
4       24.59  3.61    0     No  Sun     0     4   14.680765

We also used sklearn to create a plot and a linear regression line of the total bill vs the percentage tip given. Based on this, there appears to be a decreasing trend between cost of meal and the percentage of tip given. I learned that there are many ways to use dataframe data and they can help complete many tasks, from simple data storage to complex analysis.

from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

df = pd.DataFrame(td)

model = LinearRegression()

# fit the model to the data
model.fit(df[['total_bill']], df[['percentage']])

# predict the y values using the model
y_pred = model.predict(df[['total_bill']])

# plot the data and the regression line
plt.scatter(df['total_bill'], df['percentage'])
plt.plot(df['total_bill'], y_pred, color='red')
plt.show()
import pandas as pd

#read csv and sort 'Duration' largest to smallest
df = pd.read_csv('files/nba.csv').sort_values(by=['Name'], ascending=False)

print("--Name Top 10---------")
print(df.head(10))

print("--Name Bottom 10------")
print(df.tail(10))
--Name Top 10---------
                    Name                    Team  Number Position   Age  \
237        Zaza Pachulia        Dallas Mavericks    27.0        C  32.0   
271        Zach Randolph       Memphis Grizzlies    50.0       PF  34.0   
402          Zach LaVine  Minnesota Timberwolves     8.0       PG  21.0   
270       Xavier Munford       Memphis Grizzlies    14.0       PG  24.0   
386      Wilson Chandler          Denver Nuggets    21.0       SF  29.0   
25           Willie Reed           Brooklyn Nets    33.0       PF  26.0   
141  Willie Cauley-Stein        Sacramento Kings     0.0        C  22.0   
385          Will Barton          Denver Nuggets     5.0       SF  25.0   
233      Wesley Matthews        Dallas Mavericks    23.0       SG  29.0   
97        Wesley Johnson    Los Angeles Clippers    33.0       SF  28.0   

    Height  Weight         College      Salary  
237   6-11   275.0             NaN   5200000.0  
271    6-9   260.0  Michigan State   9638555.0  
402    6-5   189.0            UCLA   2148360.0  
270    6-3   180.0    Rhode Island         NaN  
386    6-8   225.0          DePaul  10449438.0  
25    6-10   220.0     Saint Louis    947276.0  
141    7-0   240.0        Kentucky   3398280.0  
385    6-6   175.0         Memphis   3533333.0  
233    6-5   220.0       Marquette  16407500.0  
97     6-7   215.0        Syracuse   1100602.0  
--Name Bottom 10------
                Name                    Team  Number Position   Age Height  \
135    Alan Williams            Phoenix Suns    15.0        C  23.0    6-8   
368    Alan Anderson      Washington Wizards     6.0       SG  33.0    6-6   
428  Al-Farouq Aminu  Portland Trail Blazers     8.0       SF  25.0    6-9   
330     Al Jefferson       Charlotte Hornets    25.0        C  31.0   6-10   
312       Al Horford           Atlanta Hawks    15.0        C  30.0   6-10   
404    Adreian Payne  Minnesota Timberwolves    33.0       PF  25.0   6-10   
328   Aaron Harrison       Charlotte Hornets     9.0       SG  21.0    6-6   
356     Aaron Gordon           Orlando Magic     0.0       PF  20.0    6-9   
152     Aaron Brooks           Chicago Bulls     0.0       PG  31.0    6-0   
457              NaN                     NaN     NaN      NaN   NaN    NaN   

     Weight           College      Salary  
135   260.0  UC Santa Barbara     83397.0  
368   220.0    Michigan State   4000000.0  
428   215.0       Wake Forest   8042895.0  
330   289.0               NaN  13500000.0  
312   245.0           Florida  12000000.0  
404   237.0    Michigan State   1938840.0  
328   210.0          Kentucky    525093.0  
356   220.0           Arizona   4171680.0  
152   161.0            Oregon   2250000.0  
457     NaN               NaN         NaN