写这段代码的有效和干净的方法

2024-04-20 01:46:20 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
1条回答
网友
1楼 · 发布于 2024-04-20 01:46:20

假设您有以下数据框:

In [100]: df
Out[100]:
  StudentId  Assignment1  Assignment2  Assignment3  Test
0  xxxxxxxx           11           15            7    50
1  yyyyyyyy            5           10            2    31

首先计算score

In [101]: df['score'] = df.filter(regex=r'(?:Assignment\d*|Test)').sum(1)

现在我们可以使用pd.cut()方法对分数进行分类:

In [102]: df['grade'] = pd.cut(df.score, bins=[0, 51, 60, 70, 80, 200], labels=list('FDCBA'))

In [103]: df
Out[103]:
  StudentId  Assignment1  Assignment2  Assignment3  Test  score grade
0  xxxxxxxx           11           15            7    50     83     A
1  yyyyyyyy            5           10            2    31     48     F

相关问题 更多 >