python - 组合/合并熊猫中的值
问题描述
我有一列中的单个类有多个值,我想组合/合并它们。我尝试了以下代码,但它只是根据每个等级合并值。
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 |
+----------------------------------+--------+
我想合并学生并随机取他/她的一个成绩。即使除了成绩之外还有更多列,我希望在合并它们时为每个学生随机选择它们。
解决方案
乍一看,我找到了两种方法来完成相同的任务,但可能还有很多其他方法。
第一个将整个 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)
推荐阅读
- pyspark - 在pyspark的任何列中删除具有特定值的行
- reactjs - 在子组件上触发点击事件
- django - 如何动态创建 Tables2 类
- android-studio - Android Studio 和 Kotlin:更改以编程方式添加的列表视图图像
- swift - 使用 LLDB 时如何修复错误“无法创建 Swift 临时上下文”
- r - 获取每个 seqnames 的最长范围
- firebase - 如何创建可以在读取数据库时触发的firebase云功能
- xamarin - MvvmCross CreateBindingSet 的预期用途
- html - CSS Card Flip 在 Apple 设备上不起作用
- go - runtime:unexpected return pc for runtime.gopark 调用 from0x0