# 程序员用Python分析和詹姆斯和伦纳德在NBA的职业生涯的差距

NBA数据集获取路径：登录kesci.com-点击「K-Lab」-找到「NBA数据集」

K-Lab是科赛网重点打造的在线数据分析协作平台。它涵盖了Python、R等主流语言，完成了90%以上数据分析&挖掘相关库的部署(如题主所提到的pandas, numpy, matplotlib)，免去了本地搭建环境的烦恼，实现了即刻线上动手做分析项目。

1）数据维度

2）数据处理

# 导入必要的包.

# 导入必要的包.import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport warningsimport numpy as npimport pylab%matplotlib inlinewarnings.filterwarnings('ignore')

pd.set_option('display.max_columns',30)player_avg[(player_avg['姓名'] == 'Kawhi Leonard') & (player_avg['赛季'] == '16--17')]

pd.set_option('display.max_columns',50)L_1617_avg = player_avg[(player_avg['姓名'] == 'LeBron James') & (player_avg['赛季'] == '16--17')]L_1617_avg

class Radar(object): n = 1 angles =None def __init__(self, fig, titles, labels, rect=None): if rect is None: rect = [0.05, 0.05, 0.95, 0.95] self.n = len(titles) self.angles = np.arange(90, 90+360, 360.0/self.n) self.axes = [fig.add_axes(rect, projection="polar", label="axes%d" % i) for i in range(self.n)] self.ax = self.axes[0] self.ax.set_thetagrids(self.angles, labels=titles, fontsize=14) for ax in self.axes[1:]: ax.patch.set_visible(False) ax.grid("off") ax.xaxis.set_visible(False) for ax, angle, label in zip(self.axes, self.angles, labels): ax.set_rgrids(range(1, 6), angle=angle, labels=label) ax.spines["polar"].set_visible(False) ax.set_ylim(0, 5) def angle(self, values, *args, **kw): return np.deg2rad(np.r_[self.angles]),np.r_[values],values def plot(self, values, *args, **kw): angle = np.deg2rad(np.r_[self.angles, self.angles[0]]) values = np.r_[values, values[0]] self.ax.plot(angle, values, *args, **kw)titles_ = ['score','shoot','rebound','assist','three','penalty','steal','block']titles = ['得分','投篮','篮板','助攻','三分','罚球','抢断','盖帽']# titles = list("ABCDE")

# data_statistics函数主要是方便categoricl型的数据的统计显示，方便后续绘图使用def data_statistics(Kawhi_season1617, Lebron_season1617, name): Kawhi_season1617_ = pd.DataFrame(Kawhi_season1617.groupby(name)['球员'].count()) Kawhi_season1617_.columns = ['K_次数'] Kawhi_season1617_.reset_index(inplace=True) Lebron_season1617_ = pd.DataFrame(Lebron_season1617.groupby(name)['球员'].count()) Lebron_season1617_.columns = ['L_次数'] Lebron_season1617_.reset_index(inplace=True) data = pd.merge(Lebron_season1617_,Kawhi_season1617_,on = name , how ='outer') data = data.fillna(0) data = data.sort_values(name) return data

rebounds['K_次数'] = rebounds['K_次数'] * -1plt.figure(figsize=[16,6])sns.barplot(x = '篮板', y = 'L_次数', data = rebounds, color='red')sns.barplot(x = '篮板',y = 'K_次数', data = rebounds, color ='blue')

score['K_次数'] = score['K_次数'] * -1plt.figure(figsize=[16,6])sns.barplot(x = '得分', y = 'L_次数', data = score, color='red')sns.barplot(x = '得分',y = 'K_次数', data = score, color ='blue')

plt.figure(figsize= [12,5])total = pd.concat([Kawhi_season1617,Lebron_season1617])total['Is_Kawhi'] = 0total.loc[total['球员'] == 'Kawhi Leonard','Is_Kawhi'] = 1total['A'] = 0sns.violinplot(x= 'A' , y = '得分', hue = 'Is_Kawhi', data = total, split=True)

0 - 15分 定为档1

15 - 19 定为档2

20 - 24 定为档3

25 - 29 定为档4

30 - 定为档5

shoot = data_statistics(Kawhi_season1617, Lebron_season1617, '投篮')shoot# sns.distplot(Kawhi_season1617.groupby('得分')['球员'].count(),color='b')# sns.distplot(Lebron_season1617.groupby('得分')['球员'].count(),color='r')Kawhi_season1617.groupby('得分')['球员'].count().plot(figsize=(12,6),color='b',marker='*')Lebron_season1617.groupby('得分')['球员'].count().plot(figsize=(12,6),color = 'r', marker='o')

steal = data_statistics(Kawhi_season1617, Lebron_season1617, '抢断')stealsteal['K_次数'] = steal['K_次数'] * -1plt.figure(figsize=[16,6])sns.barplot(x = '抢断', y = 'L_次数', data = steal, color='red')sns.barplot(x = '抢断',y = 'K_次数', data = steal, color ='blue')

block = data_statistics(Kawhi_season1617, Lebron_season1617, '盖帽')blockblock['K_次数'] = block['K_次数'] * -1plt.figure(figsize=[16,6])sns.barplot(x = '盖帽', y = 'L_次数', data = block, color='red')sns.barplot(x = '盖帽',y = 'K_次数', data = block, color ='blue')

fault_num = data_statistics(Kawhi_season1617, Lebron_season1617, '失误')fault_numfault_num['K_次数'] = fault_num['K_次数'] * -1plt.figure(figsize=[16,6])sns.barplot(x = '失误', y = 'L_次数', data = fault_num, color='red')sns.barplot(x = '失误',y = 'K_次数', data = fault_num, color ='blue')

3）最终结论

py2：print语句，语句就意味着可以直接跟要打印的东西，如果后面接的是一个元组对象，直接打印

py3：print函数，函数就以为这必须要加上括号才能调用，如果接元组对象，可以接收多个位置参数，并可以打印

py2：input_raw()

py3：input()

py2：必须显示的在参数中写上基类

py：直接无参数调用即可

1/2的结果

py2：返回0

py3：返回0.5，没有了int和long的区别

py2：默认编码ascii

py3：默认编码utf-8

py2：当中许多返回列表的方法，如range,字典对象的 dict.keys()、dict.values() 方法, map、filter、zip；并且迭代器必须实现next方法

py3：将返回列表的方法改为了返回迭代器对象，内置了__next__，不用特意去实现next

nonlocal

py2：没有办法在嵌套函数中将变量声明为一个非局部变量，只能在函数中声明全局变量

True和False

py2：True 和 False 在 Python2 中是两个全局变量，可以为其赋值或者进行别的操作，初始数值分别为1和0，虽然修改是违背了python设计的原则，但是确实可以更改

py3：修正了这个变量，让True或False不可变

• 发表于:
• 原文链接http://kuaibao.qq.com/s/20180330A1WUR800?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2022-05-26

2022-05-26

2022-05-26

2022-05-26

2022-05-26

2022-05-26

2022-05-26

2022-05-26

2022-05-26

2022-05-26

2022-05-26

2022-05-26