从每个列表中提取第n个元素并将其存储在新列中

时间:2019-01-14 12:34:43

标签: python pandas list jupyter-notebook

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

    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”的新列,该列将在成绩列表中存储第3个元素。

示例输出:

      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  

最好的解决办法是什么?

2 个答案:

答案 0 :(得分:3)

str一起使用索引,因为使用可迭代项:

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

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

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

答案 1 :(得分:1)

GET http://magento.local/static/version1547468917/frontend/Magento/luma/en_US/mage/requirejs/mixins.js net::ERR_ABORTED 404 (Not Found) (index):22 GET http://magento.local/static/version1547468917/frontend/Magento/luma/en_US/requirejs/require.js net::ERR_ABORTED 404 (Not Found) (index):25 GET http://magento.local/static/version1547468917/frontend/Magento/luma/en_US/mage/polyfill.js net::ERR_ABORTED 404 (Not Found) (index):23 GET http://magento.local/static/version1547468917/frontend/Magento/luma/en_US/mage/requirejs/mixins.js net::ERR_ABORTED 404 (Not Found) (index):25 GET http://magento.local/static/version1547468917/frontend/Magento/luma/en_US/mage/polyfill.js 404 (Not Found) (index):65 Uncaught TypeError: require.config is not a function at (index):65 将完成工作