![](/img/trans.png)
[英]Python: Creating a function that returns a list of scores in a competition
[英]Creating a function that takes a DataFrame as an argument and returns a dictionary of scores
我正在嘗試創建一個 function ,它將 DataFrame 作為參數,然后計算每個團隊擁有的“聯賽積分”的總數,然后返回一個按分數排序的值的字典。 我已經創建了可以讓我獲得所需 output 的函數,但我只想知道如何將它們全部包裝在一個 function 下。
function 需要這樣啟動:
func(df, w=3, l=0, d=1):
我制作了一個簡單的數據集,因為實際問題是一個更大的數據集。 每一行是兩隊之間的一場足球比賽:
import pandas as pd
import numpy as np
data = {'Home Team': ['Swindon', 'Bath', 'Northampton','Manchester', "Newcastle", 'Reigate'],
'Away Team': ['Reigate', 'Manchester', 'Newcastle','Swindon', 'Bath', 'Northampton'],
'Home Goals':[3,1,3,0,1,2],
'Away Goals':[2,1,4,1,0,1],}
df = pd.DataFrame (data, columns = ['Home Team','Away Team','Home Goals','Away Goals','Home League Points', 'Away League Points'])
我創建了一個 function ,它會連續顯示每支球隊從比賽中獲得的聯賽積分。 然后我將其應用於創建新列的整個數據集:
創建 function:
def leaguetablescore(row, w=3, l=0, d=1):
if row['Home Goals'] < row['Away Goals'] :
return [l , w]
elif row['Home Goals'] == row['Away Goals']:
return [d , d]
else:
return [w , l]
將 function 應用於 dataframe:
df[['Home League Points', 'Away League Points']] = df.apply(lambda x : leaguetablescore(x), axis = 1,
result_type ='expand')
然后,我創建了一個 function ,它將返回一個包含每支球隊使用這個新數據集和新列的總聯賽積分的字典:
def TeamsPointsDict(df, teamslist):
mydictionary = dict()
for team in range(len(teamslist)):
mydictionary[teamslist[team]] = (df.loc[df['Home Team'] == teamslist[team],
'Home League Points'].sum()) + (df.loc[df['Away Team'] == teamslist[team],
'Away League Points'].sum())
return(mydictionary)
Output (以及我試圖創建的單個 function 中的 output 雖然需要排序):
{'Swindon': 6,
'Bath': 1,
'Northampton': 0,
'Manchester': 1,
'Newcastle': 6,
'Reigate': 3}
但是,我也很好奇如何將我的 dataframe 輸入 function 並使用 SINGLE ZC1C425268E68385D1AB5074C17A94F14 返回字典(或數據幀)。 我知道我已經創建了所有這些步驟,但是有沒有辦法可以定義一個 function 可以從輸入中完成所有操作? 我需要 function 以指定方式開始的原因是因為我希望我能夠改變每支球隊從贏 (w)、平 (d) 或輸 (l) 中獲得的聯賽積分數,如果我需要。
我希望這是有道理的,任何建議都將不勝感激。 我很高興試圖解決這個問題,所以我希望你這樣做::)
附言
請讓我知道這篇文章的格式是否可以,因為我對堆棧溢出比較陌生!
我不太確定你在問什么,但我認為你在說的是,你希望為贏、輸、平而獲得的積分是可配置的?
我認為其他兩個功能都很好。 要將它們合二為一,只需創建一個 function 以接收 dataframe 即可。
另外作為旁注,字典/json結構本身並不是“有序的”。 現在 python 確實有一些方法可以“排序”它們,但只知道從技術上講,它們沒有順序。
所以給出:
import pandas as pd
import numpy as np
data = {'Home Team': ['Swindon', 'Bath', 'Northampton','Manchester', "Newcastle", 'Reigate'],
'Away Team': ['Reigate', 'Manchester', 'Newcastle','Swindon', 'Bath', 'Northampton'],
'Home Goals':[3,1,3,0,1,2],
'Away Goals':[2,1,4,1,0,1],}
df = pd.DataFrame (data, columns = ['Home Team','Away Team','Home Goals','Away Goals'])
def leaguetablescore(row, points_awarded):
if row['Home Goals'] < row['Away Goals'] :
return [points_awarded['l'] , points_awarded['w']]
elif row['Home Goals'] == row['Away Goals']:
return [points_awarded['d'], points_awarded['d']]
else:
return [points_awarded['w'], points_awarded['l']]
def TeamsPointsDict(df, teamslist):
mydictionary = dict()
for team in range(len(teamslist)):
mydictionary[teamslist[team]] = (df.loc[df['Home Team'] == teamslist[team],
'Home League Points'].sum()) + (df.loc[df['Away Team'] == teamslist[team],
'Away League Points'].sum())
return(mydictionary)
制作一本字典或其他方式來尋找你想要的贏、輸、平的價值觀。 然后 function 接收 dataframe 並完成工作:
points_awarded = {'w':3,
'l':0,
'd':1}
def get_dict(df):
df[['Home League Points', 'Away League Points']] = df.apply(lambda x : leaguetablescore(x,points_awarded), axis = 1,
result_type ='expand')
teamslist = list(df['Home Team']) + list(df['Away Team'])
mydictionary = TeamsPointsDict(df, list(set(teamslist)))
return mydictionary
dictionary = get_dict(df)
print(dictionary)
Output:
{'Reigate': 3, 'Bath': 1, 'Northampton': 0, 'Manchester': 1, 'Swindon': 6, 'Newcastle': 6}
你想要這個嗎 -
home_df = df[['Home Team','Home League Points']].rename(columns = {'Home Team': 'Team', 'Home League Points': 'Points'})
away_df = df[['Away Team','Away League Points']].rename(columns = {'Away Team': 'Team', 'Away League Points': 'Points'})
result = dict(pd.concat([home_df,away_df]).groupby('Team',as_index=False).sum().to_dict(orient='split')['data'])
想法是創建2個單獨的df home/away並將它們連接起來(按行)->然后使用groupby sum->最后,將數據轉換為dict。
輸出-
{'Bath': 1,
'Manchester': 1,
'Newcastle': 6,
'Northampton': 0,
'Reigate': 3,
'Swindon': 6}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.