编写一个函数,创建一个名为" 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()
这方面的任何帮助都将不胜感激。
发布于 2017-02-16 08:31:12
一些类似这样的东西就可以解决这个问题。
def answer_four():
df['Points'] = df['Gold.2']*3 + df['Silver.2']*2 + df['Bronze.2']
return df['Points']
发布于 2019-02-20 06:31:14
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()
发布于 2020-06-16 20:36:07
您可以从检查列名开始,如果需要,执行一些重命名:
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()
https://stackoverflow.com/questions/42149037
复制相似问题