编写一个函数,创建一个名为“Points”的系列,这是一个加权值,其中每枚金牌(Gold.2
)计3分,银牌(Silver.2
)2分,青铜奖牌(Bronze.2
)1分。该函数应仅返回您创建的列(Series对象)。
此函数应返回长度为146
的名为Points
的系列
我是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()
非常感谢任何帮助。
答案 0 :(得分:1)
有些类似于此的技巧
def answer_four():
df['Points'] = df['Gold.2']*3 + df['Silver.2']*2 + df['Bronze.2']
return df['Points']
答案 1 :(得分:0)
@PostMapping(path = "{make}",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public RequestBody<Object> create(@PathVariable("make") String make,
@org.springframework.web.bind.annotation.RequestBody RequestBody<Object> body) {
// please change the name of "RequestBody" entity, in order to avoid name clash with the annotation
}
答案 2 :(得分:0)
您可以先检查列名,然后在必要时进行一些重命名:
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()