如何通过 class 列获取一列组的范围?在 Pandas

How get ranges of one column gruop by class column? In Pandas

我正在练习 Pandas,我想通过另一列的值从数据框中获取列的范围。

示例数据集:

     Points    Grade
1     7.5        C
2     9.3        A
3     NaN        A
4     1.3        F
5     8.7        B
6     9.5        A
7     7.9        C
8     4.5        F
9     8.0        B
10    6.8        D
11    5.0        D

我想要每个年级的分数范围,这样我就可以得出缺失值。

为了这个目标,我需要得到这样的东西:

Grade      Points
  A      [9.5, 9.3]
  B      [8.7, 8.0]
  C      [7.5, 7.0]
  D      [6.8, 5.0]
  F      [1.3, 4.5]

我可以用 for 之类的东西得到它,但是用 pandas 可以用一些简单的方法得到它吗?

我尝试了所有我知道的 groupby 组合,但一无所获。有什么建议吗?

您可以先用 notnull and then groupby and tolist with reset_index 过滤 df:

print df
    Points Grade
0      7.5     C
1      9.3     A
2      NaN     A
3      1.3     F
4      8.7     B
5      9.5     A
6      7.9     C
7      4.5     F
8      8.0     B
9      6.8     D
10     5.0     D
print df['Points'].notnull()
0      True
1      True
2     False
3      True
4      True
5      True
6      True
7      True
8      True
9      True
10     True
Name: Points, dtype: bool

print df.loc[df['Points'].notnull()]
    Points Grade
0      7.5     C
1      9.3     A
3      1.3     F
4      8.7     B
5      9.5     A
6      7.9     C
7      4.5     F
8      8.0     B
9      6.8     D
10     5.0     D

print df.loc[df['Points'].notnull()].groupby('Grade')['Points']
                                                   .apply(lambda x: x.tolist()).reset_index()
  Grade      Points
0     A  [9.3, 9.5]
1     B  [8.7, 8.0]
2     C  [7.5, 7.9]
3     D  [6.8, 5.0]
4     F  [1.3, 4.5]