我有一个数据集,其中包含在多个赛季的大量足球比赛中拍摄的所有镜头。我编写了以下脚本来为每个比赛和相应的赛季制作子集。import pandas as pdimport csvshots = 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 年是一个实际值。另外,如何编写一个以pandas数据框的名义自动包含比赛和季节的函数?
1 回答
繁星淼淼
TA贡献1775条经验 获得超11个赞
我认为问题是2014整数,所以需要删除'':
.get_group(2014)
但这里更好的是 create dictionary of DataFrameslike,因为不推荐使用全局变量:
dfs = dict(tuple(shots_premier_league.groupby(['Season'])))
然后通过键选择每个数据帧,例如:
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())
添加回答
举报
0/150
提交
取消