python - 将与不同值关联的重复条目转换为包含这些值列表的条目?

标签 python pandas

<分区>

我不确定如何命名。

假设以下 Pandas DataFrame:

    Student ID      Class   
1   John    99124   Biology
2   John    99124   History
3   John    99124   Geometry
4   Sarah   74323   Physics
5   Sarah   74323   Geography
6   Sarah   74323   Algebra
7   Alex    80045   Trigonometry
8   Alex    80045   Economics
9   Alex    80045   French

我想通过创建每个学生正在上的类(class)列表,然后将其放入“类(class)”列来减少此 DataFrame 中的行数。这是我想要的输出:

    Student ID      Class
1   John    99124   ["Biology","History","Geometry"]
2   Sarah   74323   ["Physics","Geography","Algebra"]
3   Alex    80045   ["Trigonometry","Economics","French"]

我正在使用一个大型 DataFrame,它不像这个例子那样组织得很好。感谢您的帮助。

最佳答案

您需要groupbyStudentID 上,然后使用 agg .

df.groupby(['Student', 'ID'], as_index=False).agg({'Class': list})

输出:

  Student     ID                              Class
0    Alex  80045  [Trigonometry, Economics, French]
1    John  99124       [Biology, History, Geometry]
2   Sarah  74323      [Physics, Geography, Algebra]

关于python - 将与不同值关联的重复条目转换为包含这些值列表的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332350/

相关文章:

python - wx.html 中的超链接 - 如何在同一 html 页面内导航

python - 如何使用 python 从我的控制台捕获所有内容并通过电子邮件发送?

python - 在 Pandas/Python 中使用 loc 和仅使用方括号过滤列有什么区别?

python - 无法从 read_csv 索引 Pandas 数据框中的日期

python - 添加/删除列表中的项目

python - 验证文件未被修改

python - 如何使数据框中的每个组具有相同的大小?

python - 按列位置掩码 2 df

python - 在 Python 脚本中使用 "apt-get install xxx"

python - 如何处理用 Pandas 导入的数据?