首页 > 解决方案 > 组合/合并熊猫中的值

问题描述

我有一列中的单个类有多个值,我想组合/合并它们。我尝试了以下代码,但它只是根据每个等级合并值。

df.groupby('Grades')['Students'].apply(' '.join).reset_index()

我不想要这个。假设我们有以下 DataFrame:

+----------------------------------+--------+
|             Students             | Grades |
+----------------------------------+--------+
| Student1                         |      0 |
| Student1                         |      1 |
| Student1                         |      2 |
| Student2                         |      3 |
| Student2                         |      5 |
| Student2                         |      0 |
| Student3                         |      1 |
| Student3                         |      0 |
| Student3                         |      0 |
+----------------------------------+--------+

我想要以下数据框:

+----------------------------------+--------+
|             Students             | Grades |
+----------------------------------+--------+
| Student1                         |      1 |
| Student2                         |      3 |
| Student3                         |      0 |
+----------------------------------+--------+

我想合并学生并随机取他/她的一个成绩。即使除了成绩之外还有更多列,我希望在合并它们时为每个学生随机选择它们。

标签: pythonpandas-groupby

解决方案


乍一看,我找到了两种方法来完成相同的任务,但可能还有很多其他方法。

第一个将整个 DataFrame 打乱,并且对于每个组(学生的成绩),取第一(随机)行:

df.sample(frac=1.0).groupby("Students").first().reset_index()

相反,第二种方法为每个学生随机取一行(从而避免整个数据集的混洗):

df.groupby("Students").apply(lambda x: x.sample(n=1)).reset_index(drop=True)

推荐阅读