【问题标题】:I want create a list from values in a dataset based on a specific condition我想根据特定条件从数据集中的值创建一个列表
【发布时间】:2019-09-09 04:29:16
【问题描述】:

我正在使用一个数据集,其中包含自 1985 年以来每场疯狂三月比赛的信息。我想知道哪些球队赢得了所有比赛以及每个球队赢得了多少次。

我屏蔽了主数据集并创建了一个新数据集,其中仅包含有关冠军赛的信息。现在我正在尝试创建一个循环来比较两支球队在冠军赛中的得分,检测获胜者并将该球队添加到列表中。这是数据集的样子:https://imgur.com/tXhPYSm

tourney = pd.read_csv('ncaa.csv')

champions = tourney.loc[tourney['Region Name'] == "Championship", ['Year','Seed','Score','Team','Team.1','Score.1','Seed.1']]

list_champs = []

for i in champions:
    if champions['Score'] > champions['Score.1']:
        list_champs.append(i['Team'])
    else:
        list_champs.append(i['Team.1'])

【问题讨论】:

    标签: python pandas loops dataframe if-statement


    【解决方案1】:

    让您的代码正常运行的极简更改(不是最有效的):

    tourney = pd.read_csv('ncaa.csv')
    
    champions = tourney.loc[tourney['Region Name'] == "Championship", ['Year','Seed','Score','Team','Team.1','Score.1','Seed.1']]
    
    list_champs = []
    
    for row in champions.iterrows():
        if row['Score'] > row['Score.1']:
            list_champs.append(row['Team'])
        else:
            list_champs.append(row['Team.1'])
    
    

    否则,您可以这样做:

    df.apply(lambda row: row['Team'] if row['Score'] > row['Score.1'] else row['Team.1'], axis=1).values
    

    【讨论】:

      【解决方案2】:

      为什么需要遍历DataFrame

      基本过滤应该可以正常工作。像这样的:

      champs1 = champions.loc[champions['Score'] > champions['Score.1'], 'Team']
      champs2 = champions.loc[champions['Score'] < champions['Score.1'], 'Team.1']
      
      list_champs = list(champs1) + list(champs2)
      

      【讨论】:

      • 谢谢。我的小经历让我认为循环是最有效的方式。
      猜你喜欢
      • 1970-01-01
      • 2018-10-24
      • 2018-05-01
      • 2018-10-17
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多