奥运奖牌积分制,金牌3枚,银牌2枚,布朗茨1枚

2024-06-13 08:03:48 发布

您现在位置:Python中文网/ 问答频道 /正文

写一个函数来创建一个叫做“Points”的序列,这个序列是一个加权值,其中每个金牌(Gold.2)代表3分,银牌(Silver.2)代表2分,铜牌(Bronze.2)代表1分。函数应该只返回您创建的列(一个系列对象)。在

此函数应返回一个名为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()

如果有任何帮助,我们将不胜感激。在


Tags: csv函数answerpandasdfindex代表序列
2条回答

一些类似的东西会起作用

def answer_four():
    df['Points'] = df['Gold.2']*3 + df['Silver.2']*2 + df['Bronze.2'] 
    return df['Points']
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()

相关问题 更多 >