python - Outputting results as a table in pandas -
i have dataset follows:
print(df) name points attempts 'alex' 2 4 'brian' 1 2 'cathy' 3 5 'daniel' 5 7 let's have code of form
for name in df: if points > 2: grade = 'pass' else: grade = 'fail' average_points = points/attempts attempts_left = 10 - attempts and trying achieve here output table (in pandas dataframe) of form
name grade average_points attempts_left 'alex' fail 0.5 6 'brian' fail 0.5 8 'cathy' pass 0.6 5 'daniel' pass 0.71 3 problem is, unsure of return/append functions should employ in code. also, aware may simpler add columns in original dataset 'grade', 'average_points' , 'attempts_left', approach not work in case raw data more complicated working example above.
any appreciated. thanks!
you vectorize operations , use assign
in [839]: df.assign(attempts_left=10 - df.attempts, ...: average_points=df.points / df.attempts, ...: grade=np.where(df.points > 2, 'pass', 'fail')) out[839]: name points attempts attempts_left average_points grade 0 'alex' 2 4 6 0.500000 fail 1 'brian' 1 2 8 0.500000 fail 2 'cathy' 3 5 5 0.600000 pass 3 'daniel' 5 7 3 0.714286 pass
Comments
Post a Comment