将Mat Formular转换为python时出现问题

希望您能提供帮助。

我正在使用fifa20数据集,其中包含约85个描述玩家的变量。我想使用6个变量:attack_finishing,skill_dribbling,power_long_shots,skill_ball_control,mindality_positioning和mentality_penalties。

我有以下简单的公式,它描述了这些变量的玩家值:

attack_finishing:70 技术运球:65 power_long_shots:74 skill_ball_control:67 心态定位:80 mental_penalties:70

进入simpe公式: G_分数=(0.25 * 70)+(0.15 * 65)+(0.1 * 74)+(0.2 * 67)+(0.1 * 80)+(0.2 * 70) G_Score = 65.05

我的意图是构建一个函数,在其中可以使用数据集中的名称调用该函数,并且它将根据上述变量中​​的玩家值为我提供该玩家的G_Score。

我尝试使用以下代码:

import pandas as pd 
fifa20 = pd.read_csv('players_20.csv',delimiter=',')

def Gscore(long_name): --> create the function,which takes the name of the player(long_name)
    for i in fifa20(attacking_finishing,skill_dribbling,power_long_shots,skill_ball_control,mentality_positioning,mentality_penaltites): --> the variables the function should take in fifa20 dataset
    i = (0.25 * 'attacking_finishing') + (0.15 * 'skill_dribbling') + (0.1 * 'power_long_shots') + (0.2 * 'skill_ball_control') + (0.1 * 'mentality_positioning') + (0.2 * 'mentality_penalties') --> try to put the formular in here
retrun (i) --> return the sum

Gscore('Alan Pulido') --> me calling trying to call the function,with a player name

我没有从函数中得到一个错误,但是当我尝试调用时,我得到了:

NameError: name 'attacking_finishing' is not defined

我现在知道,这里有很多错误。

数据集的格式如下

谢谢!


lisheng1987 回答:将Mat Formular转换为python时出现问题

我不会为您的问题提供解决方案,而是要帮助您解决问题:

首先,如果要在python代码中添加注释,请使用:#

# this is a comment

因此,您的前两行看起来正确:

import pandas as pd 
fifa20 = pd.read_csv('players_20.csv',delimiter=',')

然后定义函数:

def Gscore(long_name):

'long_name'是.csv中存储名称的列的名称吗? 无论如何,您都选择将此参数传递给函数,但是您在函数中并未对其进行任何操作。

计算机很笨,只能执行您告诉他的操作(但是他执行得非常快)。

如果我们用英语写下您要达到的目标:

  • 您要在数据集中搜索播放器名称出现的那一行
  • 然后,您要将公式应用于在找到播放器的那一行中找到的数据
  • 您要返回此值

因此,要按列搜索数据集,请使用:

for column in fifa20:

但是在这里我们要逐行检查,我不知道该怎么做,所以我用谷歌搜索发现可以使用:

for index,row in fifa20.iterrows():

正在读取的行的内容存储在变量行中,因此,如果我们正在寻找播放器的名称,并且该名称存储在“ long_name”列中,我们可以检查是否找到了播放器,正在寻找:

if row['long_name'] == long_name:

然后我们可以计算播放器的gscore:

score = row['attacking_finishing'] * 0.15 + ... 

如果数据是作为字符串而不是数字存储和解析的,则可能需要在将它们相乘之前将值强制转换为浮点数:

score = float(row['attacking_finishing']) * 0.15 + ... 

然后您可以返回结果:

return score

这里重要的是,我们用英语写下了我们想要做的事情,然后将这些任务切成小动作,最后将其翻译成我们想要的任何语言。

您的问题不在于python,而是与您要执行的操作的描述和定义有关。

请随时评论此答案,如果您需要其他帮助,我会加以改进。

本文链接:https://www.f2er.com/3165368.html

大家都在问