我有一个数据集,其中包含在多个季节的大量足球比赛中拍摄的所有镜头。我编写了以下脚本来为每个比赛和相应的赛季制作子集。
import pandas as pd
import csv
shots = pd.read_csv("C:/Users/HJA/Desktop/Betting/understatV0.01/shots.csv", encoding='iso-8859-1')
shots_premier_league = shots.groupby(['Competition']).get_group('Premier_League')
shots_bundesliga = shots.groupby(['Competition']).get_group('Bundesliga')
shots_la_liga = shots.groupby(['Competition']).get_group('La_Liga')
shots_ligue_1 = shots.groupby(['Competition']).get_group('Ligue_1')
shots_serie_a = shots.groupby(['Competition']).get_group('Serie_A')
一切正常,直到这一点。但是,现在我想将每个赛季的比赛细分为每个赛季。我使用以下脚本(在这种情况下,我以英超联赛为例:
shots_premier_league_2014 = shots_premier_league.groupby(['Season']).get_group('2014')
shots_premier_league_2015 = shots_premier_league.groupby(['Season']).get_group('2015')
shots_premier_league_2016 = shots_premier_league.groupby(['Season']).get_group('2016')
shots_premier_league_2017 = shots_premier_league.groupby(['Season']).get_group('2017')
shots_premier_league_2018 = shots_premier_league.groupby(['Season']).get_group('2018')
我100%确信2014年是实际值。另外,如何编写一个在熊猫数据框名称中自动包含竞争和季节的函数?
答案 0 :(得分:2)
我认为问题是2014
是整数,因此需要删除''
:
.get_group(2014)
但是更好的方法是像这样创建dictionary of DataFrames
,因为不建议使用globals:
dfs = dict(tuple(shots_premier_league.groupby(['Season'])))
然后按如下所示通过键选择每个DataFrame:
print (dfs[2014])
print (dfs[2015])
如何编写以熊猫数据框的名称自动包含比赛和赛季的功能?
dfs = dict(tuple(shots_premier_league.groupby(['Competition','Season'])))
print (dfs[('Bundesliga', 2014)])
如果要按字符串选择:
d = dict(tuple(df.groupby(['Competition','Season'])))
#python 3.6+ solution with f-strings
dfs = {f'{k1}_{k2}' :v for (k1, k2), v in d.items()}
#python bellow
#dfs = {'{}_{}'.format(k1, k2) :v for (k1, k2), v in d.items()}
print (dfs['Bundesliga_2014'])
如果需要查看数据的所有键:
print (dfs.keys())