【问题标题】:Olympic Medals Points system, 3 for Gold, 2 for Silver, 1 for Bronze奥运奖牌积分系统,金牌3分,银牌2分,铜牌1分
【发布时间】:2020-06-16 20:36:07
【问题描述】:

编写一个函数来创建一个名为“Points”的系列,这是一个加权值,其中每枚金牌 (Gold.2) 计为 3 分,银牌 (Silver.2) 计为 2 分,铜牌 (@987654323 @) 1 分。该函数应该只返回您创建的列(一个 Series 对象)。

此函数应返回一个名为 Points 的系列,长度为 146

我是 python 和 pandas 的新手,我不知道我是否在正确的轨道上使用这段代码,但我遇到了一个关键错误

KeyError: "['Gold.2' 'Silver.2' 'Bronze.2'] not in index" for this code: 

import pandas as pd

df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)

def answer_four():

    df['Points'] = df[(df[['Gold.2','Silver.2','Bronze.2']], [3,2,1])]
    #df[['Gold.2','Silver.2','Bronze.2']].apply(lambda x:(x,[3,2,1]))
    olympic_points_df = df[['Points']]


    return olympic_points_df

answer_four()

对此的任何帮助将不胜感激。

【问题讨论】:

  • 所以...这个声明...df['Points'] = df[(df[['Gold.2','Silver.2','Bronze.2']], [3,2,1])] ...你到底想在这里给df['Points']分配什么???
  • 通常您首先排序黄金,然后是白银,然后是青铜。 2 金永远比 1 金 + 12 银值钱。

标签: python


【解决方案1】:

一些类似的方法可以解决问题

def answer_four():
    df['Points'] = df['Gold.2']*3 + df['Silver.2']*2 + df['Bronze.2'] 
    return df['Points']

【讨论】:

  • 当我尝试这样的事情时,我得到 KeyError: 'Gold.2'' 我该如何解决这个问题?
  • 如果你只在'Gold.2'中遇到了一个键错误,那么问题肯定出在那个键上,检查拼写,''等等。
【解决方案2】:
def answer_four():
    df['Points'] = df['Gold.2']*3 + df['Silver.2']*2 + df['Bronze.2']
    Points = pd.Series(df['Points'],index=df.index)
    return Points

answer_four()

【讨论】:

    【解决方案3】:

    您可以从检查列名开始,如有必要,进行一些重命名:

    import pandas as pd
    
    df = pd.read_csv('olympics.csv',
                     index_col=0,
                     skiprows=1
                    )
    
    for col in df.columns:
        if 'gold' in col.lower():
            print(col)
            # and maybe perform a rename if needed: 
            # df.rename(columns={col:'Gold'+'.2'},
            #           inplace=True)
    
    
    def answer_four():
        df['Points'] = pd.Series((df['Gold.2']*3) + (df['Silver.2']*2) + df['Bronze.2'])
        return df['Points']
    
    
    answer_four()
    

    【讨论】:

      猜你喜欢
      • 2016-12-11
      • 2012-08-07
      • 1970-01-01
      • 2018-05-05
      • 2019-07-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      相关资源
      最近更新 更多