繁体   English   中英

如何在 FOR 循环中更改全局变量

[英]How to change a Global Variable while being in a FOR loop

import pandas as pd
df = pd.read_csv (r'result_withoutTotal.csv', index_col=0) 
df['Total'] = (((5/100)*(df['Ass1']+df['Ass3']))+((15/100)*(df['Ass2']+df['Ass4']))+((60/100)*df['Exam']))


df.loc[df['Total'] > 100, 'Total'] = 100 #

df['Final'] = round(df['Total']) #rounds up the Total to the nearest integer and saves it in column Final

print(df) 

for index, row in df.iterrows():
    if row['Total'] >= 50 and row['Exam'] >= 48:
        print('Student ID:', str(index) + ' Passed')
        
    elif row['Exam'] < 48 and row['Final'] > 44:
        print('Student ID:', str(index) + ' Failed and Will have 44')
        print('')

print(df)

问题

  • 如果学生未通过跨栏(考试 >= 48),则最终最高分数为 44。如果最终分数 <44,则最终分数不变。

因此,在 For 循环(ELIF)部分中,如果数据帧(df)中的条件语句为真,我需要将“Final”列中的任何值更改为 44,我只是想不通,我尝试了 row['Final] = 44 但这只是在 for 循环中改变它。

row是 dataframe 中行的副本。 修改它不会修改原始框架。

您需要索引原始帧,然后您可以使用df.ix[index, "Final"] = 44

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM