gpt4 book ai didi

python - 如何在 Pandas 中添加基于选定行过滤器的列?

转载 作者:行者123 更新时间:2023-12-04 16:36:40 26 4
gpt4 key购买 nike

你好,我想根据学生目前的分数+他们最喜欢的科目的分数给他们一个最终分数。

import pandas as pd
new_data = [['tom', 31, 50, 30, 20, 'English'], ['nick', 30, 42, 23, 21, 'Math'], ['juli', 39, 14, 40, 38, 'Science']]
df = pd.DataFrame(new_data, columns = ['Name','Current_Score','English','Science','Math','Favourite_Subject'])
for subj in df['Favourite_Subject'].unique():
mask = (df['Favourite_Subject'] == subj)
df['Final_Score'] = df[mask].apply(lambda row: row['Current_Score'] + row[subj], axis=1)

Name Score English Science Math Favourite_Subject Final_Score
0 tom 31 50 30 20 English NaN
1 nick 30 42 23 21 Math NaN
2 juli 39 14 40 38 Science 79.0

当我应用上述函数时,我在“Final_Score”列的其他 2 个条目中得到了 NaN,如何在不覆盖 NaN 的情况下获得以下结果?谢谢!


Name Score English Science Math Favourite_Subject Final_Score
0 tom 31 50 30 20 English 81
1 nick 30 42 23 21 Math 51
2 juli 39 14 40 38 Science 79

最佳答案

我们可以使用lookup找到Favourite_Subject对应的分数,然后将它们与Current_Score相加计算Final_Score

i = df.columns.get_indexer(df['Favourite_Subject'])
df['Final_Score'] = df['Current_Score'] + df.values[df.index, i]

   Name  Current_Score  English  Science  Math Favourite_Subject Final_Score
0 tom 31 50 30 20 English 81
1 nick 30 42 23 21 Math 51
2 juli 39 14 40 38 Science 79

关于python - 如何在 Pandas 中添加基于选定行过滤器的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69055069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com