【问题标题】:Extracting the nth element from each list and storing it in a new column [duplicate]从每个列表中提取第 n 个元素并将其存储在新列中 [重复]
【发布时间】:2019-01-14 12:34:43
【问题描述】:

我有一个数据框(称为“df”),其中包含一个名为“等级”的列。此列包含成绩列表。此列中的数据属于“对象”类型。

    student_id    grades
0       11      [A,A,B,A]
1       12      [B,B,B,C]
2       13      [C,C,D,B]
3       21      [B,A,C,B] 

我希望创建一个名为“maths_grades”的新列,它将存储成绩列表中的第三个元素。

示例输出:

      student_id   grades    maths_grade
0       11      [A,A,B,A]        B
1       12      [B,B,B,C]        B
2       13      [C,C,D,B]        D
3       21      [B,A,C,B]        C  

最好的办法是这样做吗?

【问题讨论】:

    标签: python pandas list jupyter-notebook


    【解决方案1】:

    str 使用索引,因为使用可迭代对象:

    df['maths_grade'] = df['grades'].str[2]
    

    如果没有缺失值和性能很重要,则列出理解:

    df['maths_grade'] = [x[2] for x in df['grades']]
    

    【讨论】:

    • @DanielMesejo - 是的,你是对的,但它也适用于可迭代对象,因此如果列中的列表返回第三个元素。
    【解决方案2】:

    df[‘math_grade’] = df[‘grades’].apply(lambda x : x[2]) 将完成这项工作

    【讨论】:

      猜你喜欢
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 2011-03-19
      • 1970-01-01
      相关资源
      最近更新 更多