引用资料下载:NBA球员数据.csv
编写python程序,输入数目n,输出n个最有效率的球员。计算效率需要将整个效率除以该球员的比赛场数。详细公式如下:
Efficiency = ((pts + reb + asts + stl + blk) - ((fga - fgm) + (fta - ftm) + turnover ) )/ gp
命名 | 含义 |
---|---|
pts | 得分 |
asts | 助攻 |
stl | 抢断 |
blk | 盖帽 |
fga | 投篮次数 |
fgm | 命中次数 |
minutes | 上场时间 |
reb | 篮板 |
fta | 罚球次数 |
ftm | 罚球命中次数 |
turnover | 失误 |
gp | 比赛场数 |
windows:打开cmd命令行,pip install pandas 或在编译器中引用pandas,编译器会提示你安装pandas库。
linux:打开终端,pip install pandas
import pandas as pd
#给定一个全局变量@filename
filename = 'player_regular_season.csv'
df = pd.read_csv(filename,delimiter=",")
# 这里初始化一个DataFrame变量,后面会用到
df_result = pd.DataFrame()
def load():
global df_result
for index, row in df.iterrows():
#根据题目设定,当gp(场数为无效值,整条清掉)
if row['gp'] == 'N':
df.drop(index, axis=0, inplace=True)
#二次过滤,如果gp中还有无效值将替换为pd中的NaN无效值
pd.to_numeric(df['gp'], errors='coerce')
#将gp列dtype强制转换为int(64)类型
df['gp'] = df['gp'].astype(int)
#效率值计算并添加为新的列
df['Efficiency'] = ((df['pts'] + df['reb'] + df['stl'] + df['blk']) - ((df['fga'] - df['fgm']) + (df['fta'] - df['ftm']) + df['turnover']))/df['gp']
#根据题目设定,过滤掉效率为负数的成员。
for index, row in df.iterrows():
if row['Efficiency'] < 0:
df.drop(index, axis=0, inplace=True)
#按照效率值排序df并存入df_result
df_result = df.sort_values('Efficiency',ascending=False)
def showSock(n,print_type):
global df_result
global df
index_num = 0
times = 27 - len("Name") - len(print_type) / 2
print(5 * " ", "Name", " " * int(times), print_type)
print(45 * "-")
df_result = df.sort_values(print_type, ascending=False)
for index,row in df_result.iterrows():
if index_num == n :
break
else:
name = row['firstname'] + row['lastname']
result = str(row[print_type])
length = len(name)
length2 = len(result)
times = 20 - length
space = " " * times
times2 = 20 - length2
space2 = " " * times2
print(name, space, ":",space2,result)
index_num += 1
print(45 * "-")
def sreach():
print("程序加载完成!")
print("请输入要查询的值(英文缩写):")
print("-" * 45)
print("pts:得分 asts:助攻 stl:抢断 blk:盖帽")
print("fga:投篮次数 fgm:命中次数 minutes:上场时间 reb:篮板")
print("fta:罚球次数 ftm:罚球命中次数 turnover:失误 Efficiency:效率值")
print("-" * 45)
print_type = input()
type_list = ["pts","asts","st1","blk","fga","fgm","minutes","reb","fta","ftm","turnover","Efficiency"]
if print_type not in type_list:
print("输入类型有误,请重新输入!")
sreach()
print("-" * 45)
print("请输入查询数量:")
print("-" * 45)
n = int(input())
print("-" * 45)
showSock(n, print_type)
print("程序预加载中,请稍后···")
load()
sreach()