Advertisement
Guest User

Analysing the occurance of loss-streaks in Phil Jackson positive teams

a guest
Feb 15th, 2024
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.32 KB | None | 0 0
  1. import pandas as pd
  2. import time
  3. from nba_api.stats.endpoints import LeagueStandings
  4. from nba_api.stats.endpoints import TeamGameLog
  5. from nba_api.stats.endpoints import TeamYearByYearStats
  6. import matplotlib.pyplot as plt
  7. import numpy as np
  8.  
  9.  
  10.  
  11. #LUT
  12.  
  13. years = []
  14.  
  15. final_df = pd.DataFrame(columns = ['SeasonID','TeamID', 'TeamName', 'WinPCT', 'Record', 'Season'])
  16.  
  17. for i in range(53):
  18.     if 71+i < 100:
  19.         years.append(str(1970+i) + '-' + str(71+i))
  20.     elif 71+i<110:
  21.         years.append(str(1970+i) + '-0' + str(71+i-100))
  22.     else:
  23.         years.append(str(1970+i) + '-' + str(71+i-100))
  24.    
  25. for seasonVar in years:
  26.     # print(season)
  27.     data = LeagueStandings(league_id='00',season=seasonVar,season_type='Regular Season')
  28.     time.sleep(2)
  29.     df = data.get_data_frames()[0]
  30.    
  31.     df = df.loc[df['WinPCT'] >= 0.67]
  32.     df['Season'] = seasonVar
  33.     final_df = pd.concat([final_df,df],join='inner')
  34.    
  35. export_data = []
  36.  
  37. for index, row in final_df.iterrows():
  38.     data = TeamGameLog(season=row['Season'], season_type_all_star='Regular Season', team_id=row['TeamID'])
  39.     time.sleep(1)
  40.     df = data.get_data_frames()[0]
  41.     df = df.assign(streak=(df['WL'] != df['WL'].shift()).cumsum())
  42.     df= (df.assign(streak=(df['WL'] != df['WL'].shift()).cumsum()).groupby('streak').filter(lambda g:(g['WL'].iloc[0] == 'L') & (len(g) > 1)).drop_duplicates('streak'))
  43.     data2 = TeamYearByYearStats(team_id=row['TeamID'],league_id='00',per_mode_simple='PerGame',season_type_all_star='Regular Season')
  44.     time.sleep(1)
  45.     df2 = data2.get_data_frames()[0]
  46.     myYear = row['Season']
  47.     export_data.append({
  48.          'Team':row['TeamName'],
  49.          'Season':row['Season'],
  50.          'Record':row['Record'],
  51.          'Loss Streaks in season':len(df),
  52.          'Finals Appereance': df2.query('YEAR==@myYear')['NBA_FINALS_APPEARANCE'].iloc[0]
  53.          })
  54.    
  55. df_export_data = pd.DataFrame(export_data)
  56. df_export_data.to_csv('lossStreaks.csv')
  57.    
  58. ## Processing some data
  59.  
  60. plt.figure
  61. bins = np.arange(0,10,1)
  62. plt.hist(df_export_data.loc[(df_export_data['Finals Appereance'] == 'LEAGUE CHAMPION')]['Loss Streaks in season'], bins,edgecolor='black', align='left')
  63. plt.title('NBA Champions and numbers of loss streaks in the season')
  64. plt.xlabel('Number of loss streaks during the season')
  65. plt.xticks(bins)
  66. plt.savefig('winners.png')
  67. plt.show()
  68.  
  69.  
  70. plt.figure
  71. bins = np.arange(0,10,1)
  72. plt.hist(df_export_data.loc[(df_export_data['Finals Appereance'] == 'FINALS APPEARANCE')]['Loss Streaks in season'], bins,edgecolor='black', align='left')
  73. plt.title('NBA Runner-Ups and numbers of loss streaks in the season')
  74. plt.xlabel('Number of loss streaks during the season')
  75. plt.xticks(bins)
  76. plt.savefig('runnerUps.png')
  77. plt.show()
  78.  
  79.  
  80.  
  81. plt.figure
  82. bins = np.arange(0,11,1)
  83. plt.hist(df_export_data.loc[(df_export_data['Finals Appereance'] == 'N/A')]['Loss Streaks in season'], bins,edgecolor='black', align='left')
  84. plt.title('Phil Jackson non-finalists and numbers of loss streaks in the season')
  85. plt.xlabel('Number of loss streaks during the season')
  86. plt.xticks(bins)
  87. plt.savefig('nonFinalists.png')
  88. plt.show()
  89.  
  90. ## Seeing if there is any trend yearly
  91.  
  92. fig, ax = plt.subplots(figsize=(15, 5))
  93. #plt.xticks()
  94. ax.plot(np.arange(0,42,1),df_export_data.loc[(df_export_data['Finals Appereance'] == 'LEAGUE CHAMPION')]['Loss Streaks in season'],linewidth=4)
  95. ax.set_xticks(np.arange(0,42,1), labels=df_export_data.loc[(df_export_data['Finals Appereance'] == 'LEAGUE CHAMPION')]['Season'])
  96. ax.tick_params(axis='x', rotation=90)
  97. fig.suptitle('Yearly trends for champions', fontsize=16)
  98. ax.set_xlabel('Seasons', fontsize=16)
  99. ax.set_ylabel('Number of loss-streak occurances during the season', fontsize=13)
  100. fig.savefig('championsTrends.png')
  101. fig.show()
  102.  
  103. fig, ax = plt.subplots(figsize=(15, 5))
  104. #plt.xticks()
  105. ax.plot(np.arange(0,30,1),df_export_data.loc[(df_export_data['Finals Appereance'] == 'FINALS APPEARANCE')]['Loss Streaks in season'],linewidth=4)
  106. ax.set_xticks(np.arange(0,30,1), labels=df_export_data.loc[(df_export_data['Finals Appereance'] == 'FINALS APPEARANCE')]['Season'])
  107. ax.tick_params(axis='x', rotation=90)
  108. fig.suptitle('Yearly trends for runner-ups', fontsize=16)
  109. ax.set_xlabel('Seasons', fontsize=16)
  110. ax.set_ylabel('Number of loss-streak occurances during the season', fontsize=13)
  111. fig.savefig('runnerUPTrends.png')
  112. fig.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement