【问题标题】:Turn repeat entries associated with different values into one entry with list of those values? [duplicate]将与不同值关联的重复条目转换为包含这些值列表的条目? [复制]
【发布时间】:2019-12-11 10:16:33
【问题描述】:

我不知道如何命名。

假设以下 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

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

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

我正在使用一个大型 DataFrame,它的组织不如这个例子好。任何帮助表示赞赏。

【问题讨论】:

  • 我不确定列表是否真的是理想的解决方案。将对象存储在 DataFrame 中只会为将来的大多数操作造成障碍。例如,检查哪些学生参加了Biology 不再是微不足道的事情,或者至少在没有性能低得多的方法的情况下并非如此。
  • @ALollz 你推荐另一种方法吗?
  • 这取决于你最终需要什么样的操作。具有每行都是唯一键的长格式(如上所示)可能很有用并且很灵活。 pivot 不难,或者从那里得到假人,这可能更适合其他事情。

标签: python pandas


【解决方案1】:

您需要在StudentID 上使用groupby,然后使用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]

【讨论】:

  • 为我工作,感谢您快速准确的回复。
【解决方案2】:
df.groupby('ID')['Class'].apply(list)

【讨论】:

    【解决方案3】:

    让我们看看,使用一些帮助 Apply multiple functions to multiple groupby columns

    你可以写类似的东西

    df= df.groupby('student').agg({'id':'max', 'Class': lambda x: x.tolist()})
    

    希望对你有帮助,朱利奥

    【讨论】:

      【解决方案4】:

      尝试如下

      df.groupby(['Student', 'ID'],as_index=False).agg(lambda x:','.join('"'+x+'"'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-06
        • 2020-07-14
        • 2011-03-04
        • 2016-09-07
        • 1970-01-01
        • 2013-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多