【问题标题】:How do I pass dataframe column values to my custom function to store total amount?如何将数据框列值传递给我的自定义函数以存储总量?
【发布时间】:2019-02-02 22:30:47
【问题描述】:

我有一个 Python 脚本,用于组织来自网站的有关 NHL 球员的数据。这些值被放入数据框中。我还构建了一个函数,可以获取球员姓名和球队名称来获得球员阵容的总工资。我想将数据框中的球员姓名(F1、F2、F3)传递给函数(姓名)并将结果存储在我的 Excel 表(totalSalary)中。

我尝试将 iloc 函数传递给函数,但我很困惑。

from bs4 import BeautifulSoup
import requests
import pandas as pd
import colorama
import crayons
import datetime
import xlsxwriter
import nhl_player_salary as nps

def playerProductionData():

#Getting today's date
#today = str(datetime.date.today())
today = datetime.date.today().strftime("%m-%#d")
today = str(today).replace("-","/")  
#print (today)
#Make it work on Windows machines

colorama.init()

# parameters for pandas display
def start():
    options = {
        'display': {
            'max_columns': None,
            'max_colwidth': 200,
            'expand_frame_repr': False,  # Don't wrap to multiple pages
            'max_rows': 20,
            'max_seq_items': 50,         # Max length of printed sequence
            'precision': 4,
            'show_dimensions': False,
            'colheader_justify': 'left'
        },
        'mode': {
            'chained_assignment': None   # Controls SettingWithCopyWarning
        }
    }



    for category, option in options.items():
        for op, value in option.items():
            pd.set_option(f'{category}.{op}', value)  # Python 3.6+

if __name__ == '__main__':
    start()
    del start  # Clean up namespace in the interpreter
#Set Agent Header to scrape data
headers = {"User-Agent":'Mozilla/5.0 (Windows NT 6.3; WOW64) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}

page_link = 'https://www.leftwinglock.com/line-production/index.php?type=3'

#https://leftwinglock.com/articles.php?id=3049

page_response = requests.get(page_link, headers=headers, allow_redirects=False, timeout=5)

# here, we fetch the content from the url, using the requests library
page_content = BeautifulSoup(page_response.content, "html.parser")

#column_headers = page_content.findAll('tr')[0]
column_headers = [th.getText() for th in page_content.findAll('tr')[0].findAll('th')]

data_rows = page_content.findAll('tr')[1:]
player_data = [[td.getText() for td in data_rows[i].findAll('td', limit=14)] for i in range(len(data_rows))] #PLAYER DATA 

#print (column_headers)
df = pd.DataFrame(player_data,columns=['Team', 'F1', 'F2', 'F3', 'GF', 'GA', 'GF%', 'SATF', 'SAT%', 'USATF', 'USAT%', 'SH%', 'SV%', 'SHSV%'])
#initilize total salary
df['TotalSalary'] = 0

#nps.getPlayerSalary(player_data.teamAbbrv)
#df['TotalSalary'] = nps.getPlayerSalary(df.iloc[:,0], ["ARVIDSSON","JOHANSEN", "FORSBERG"])

#print (df)

convert_fill(df)
df['SATF'] = df['SATF'].astype(int)
df['GF'] = df['GF'].astype(int)

#Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('player_line_production_data.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Player Line Production Data')

# Close the Pandas Excel writer and output the Excel file.
writer.save()       

return 'Run Successful'

def convert_fill(df):
return df.stack().apply(pd.to_numeric, errors='ignore').fillna(0).unstack()


 print(playerProductionData())

import pandas as pd
from pandas import DataFrame

def getPlayerSalary(teamAbbrv, names):
#Get Most Recent Draft Kings Salary List
DKSalary = (pd.read_csv('DKSalaries.csv'))
DKSalary_DF = DataFrame(DKSalary, columns=['Position', 'Name', 'Salary', 'AvgPointsPerGame', 'TeamAbbrev'])
i = 0

def getDataFrameForNameTeam(teamAbbrv, name):

    filterName = DKSalary_DF[DKSalary_DF['Name'].str.contains(name.title())]
    filterName = filterName[filterName['TeamAbbrev'].str.contains(teamAbbrv)]
    return filterName

nameDF = getDataFrameForNameTeam(teamAbbrv, names[0])

while i < len(names) - 1:
    newframe = getDataFrameForNameTeam(teamAbbrv, names[i + 1])
    nameDF = pd.concat([nameDF, newframe])
    i += 1


return  nameDF['Salary'].sum()

print (getPlayerSalary ('NSH', ["ARVIDSSON","JOHANSEN", "FORSBERG"])) 

【问题讨论】:

标签: python function dataframe


【解决方案1】:

一旦你建立了你的 DataFrame,你就可以通过如下方式查询单个玩家以获得他们的薪水:

df['Name' == 'Bob']['Salary'].sum()

您可能意识到的问题是无法保证名称是唯一的。它们在您的示例中未编入索引...因此,上述内容将获取任何团队中名为“Bob”的任何球员并添加他们。

从您的帖子中可以看出,您正在寻找团队总数,只需使用 pandas 'groupie()' 函数对团队求和:

df.groupby('Team')['Salary'].sum()

上述按团队对 df 进行分组,然后对每个组的“Salary”列求和。

【讨论】:

  • 我想将 Team、F1、F2 和 F3 从 playerProductionData 传递给 getPlayerSalary,然后将结果存储在行中
  • 我想在整个数据帧中应用函数 getPlayerSalary (Team, Names) 并将结果存储在一个名为 TotalSalary 的列中。
猜你喜欢
  • 2021-11-22
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多