首页 文章

根据Groupby函数的输出命名pandas数据帧

提问于
浏览
1

我有一个数据集,包括在很多季节的大量足球比赛中拍摄的所有镜头 . 我编写了以下脚本来为每个比赛和相应的赛季制作子集 .

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年是实际 Value . 另外,如何编写一个自动包含大熊猫数据帧名称中的竞争和季节的函数?

1 回答

  • 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())
    

相关问题