<jupyter_start><jupyter_text>5 Random F1 Facts- Part 1  Data Analysis Edition<jupyter_code>#Let's import some modules:

import pandas as pd
pd.set_option('display.max_columns', None)
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import plotly.express as px
import os
#Setting all graphs to be a specific color and size
sns.set_palette('Set3')
plt.rcParams['figure.figsize']=10,6
#Read in the 13 CSV files:

folder = '../f1db_csv/'

filelist = [file for file in os.listdir(folder) if file.endswith('.csv')]
for file in filelist:
    exec("%s = pd.read_csv('%s')" % (file.split('.')[0], os.path.join(folder,file)))
#Check the dataframes were created correctly:

filelist
#Merging into 1 dataframe:
f1 = results.copy()
f1 = f1.merge(constructors, how='left', on='constructorId')
f1 = f1.merge(races, how='left', on='raceId')
f1 = f1.merge(circuits, how='left', on='circuitId')
f1 = f1.merge(drivers, how='left', on='driverId')
f1 = f1.merge(status, how='left', on='statusId')
f1.head()
f1.info()
#replacing any empty vales with NaN
f1.replace(r'\N', np.nan, inplace=True)
#Focusing the dataframe:
f1 = f1[['year', 'name', 'date', 'driverRef', 'name_x', 'grid',
       'position', 'points', 'laps', 'time_x',
       'milliseconds', 'fastestLap', 'rank', 'fastestLapTime',
       'fastestLapSpeed',  'round',
        'dob', 'nationality_y', 'status']]
f1.position = f1.position.astype(float)
f1 = f1.set_index('date')
f1 = f1.rename(columns={'name_x':'constructor', 'time_x': 'time', 'nationality_y':'nationality'})
f1 = f1.sort_values('year')
f1.head()
f1.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
Index: 24880 entries, 1950-05-13 to 2020-11-01
Data columns (total 18 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   year             24880 non-null  int64  
 1   name             24880 non-null  object 
 2   driverRef        24880 non-null  object 
 3   constructor      24880 non-null  object 
 4   grid             24880 non-null  int64  
 5   position         14154 non-null  float64
 6   points           24880 non-null  float64
 7   laps             24880 non-null  int64  
 8   time             6546 non-null   object 
 9   milliseconds     6545 non-null   object 
 10  fastestLap       6474 non-null   object 
 11  rank             6631 non-null   object 
 12  fastestLapTime   6474 non-null   object 
 13  fastestLapSpeed  6474 non-null   object 
 14  round            24880 non-null  int64  
 15  dob              24880 non-null  object 
 16  nationality      24880 non-null  object 
 17  sta[...]<jupyter_text>Question 1: Who participated in the most races?<jupyter_code>most_races = f1.driverRef.value_counts().head().copy()
most_races = pd.DataFrame(most_races)
most_races = most_races.reset_index()
most_races.columns = ['driver', 'number_of_races']
most_races
sns.barplot(x='driver', y='number_of_races', data=most_races)
plt.title('Who has the most races in F1?', fontsize=20)
plt.ylabel('Number of Races', fontsize=15)
plt.xlabel('Driver', fontsize=15)
plt.xticks(np.arange(5), most_races.driver.str.capitalize(), fontsize=11);<jupyter_output><empty_output><jupyter_text>Question 2: Who has driven in F1 the longest?<jupyter_code>most_years = f1[['year', 'driverRef']].copy()
most_years = most_years.drop_duplicates(['year', 'driverRef'])[['year', 'driverRef']]
most_years = pd.DataFrame(most_years)
most_years = most_years.value_counts('driverRef').reset_index().head(5)
most_years.columns = ['driver', 'number_of_years']
most_years.style.hide_index()
sns.barplot(x='driver', y='number_of_years', data=most_years)
plt.title('Who raced for the longest in F1?', fontsize=20)
plt.ylabel('Number of Years Racing', fontsize=15)
plt.xlabel('Driver', fontsize=15)
plt.xticks(np.arange(5), most_races.driver.str.capitalize(), fontsize=11)
;<jupyter_output><empty_output><jupyter_text>Question 3: Which track has been used the most?<jupyter_code>track_use = f1[['year', 'name']].copy()
track_use = track_use.drop_duplicates(['year', 'name'])[['year', 'name']]
track_use = pd.DataFrame(track_use)
track_use = track_use.value_counts('name').reset_index()
track_use.columns = ['circuit', 'years_used']
most_track_use = track_use.copy().head()
most_track_use.style.hide_index()
sns.barplot(x='circuit', y='years_used', data=most_track_use )
plt.title('Circuit used for the most years in F1', fontsize=20)
plt.ylabel('Number of Years Used', fontsize=15)
plt.xlabel('Circuit Name', labelpad=12, fontsize=15)
plt.xticks(np.arange(5), most_races.driver.str.capitalize(), rotation=15, size=11);<jupyter_output><empty_output><jupyter_text>Question 4: What tracks have only been visited once?<jupyter_code>a = track_use[track_use['years_used']==1]
least = f1.copy()
least.columns
least = a.merge(least, how='left', left_on='circuit', right_on='name')
least = least[['year','circuit', 'years_used']].drop_duplicates().sort_values('year')
least.style.hide_index()<jupyter_output><empty_output><jupyter_text>Question 5: Which circuits have the fastest lap times?<jupyter_code>fastest_lap = f1[['name', 'fastestLapTime', 'driverRef']].copy()
fastest_lap = fastest_lap.sort_values(by='fastestLapTime')
fastest_lap = fastest_lap.drop_duplicates(['name'])[['name', 'fastestLapTime', 'driverRef']].head(5)
fastest_lap
fastest_lap['fastestLapTimeSec'] = (fastest_lap['fastestLapTime'].str.split(':', expand = True)[0].astype('float64') * 60) + fastest_lap['fastestLapTime'].str.split(':', expand = True)[1].astype('float64')
fastest_lap
sns.barplot(x='name', y='fastestLapTimeSec', data=fastest_lap)
plt.title('Which tracks have the fastest lap times in F1?', fontsize=20)
plt.ylabel('Lap Times (Sec)', fontsize=15)
plt.xlabel('Circuit', fontsize=15)
plt.xticks(rotation=15, fontsize=11);<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15450643776824036, 'fraction_numerical': 0.04206008583690987, 'mean_word_length': 4.981519507186858, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '324696', 'license': 'MIT', 'n_tokens_mistral': 2294, 'n_tokens_neox': 2093, 'n_words': 455, 'path': '5_Random_F1_Facts-Part_1.ipynb', 'repo_name': 'lindulan-thisairajah/formula1_analysis', 'size': '5825'}