将列表中的元素转换为单独的行

LdM*_*LdM 1 python pandas

我的数据框大约有 30 列。其中一些列有项目列表,例如

    Student           Subject  \
0   J.M.  [mathematics, history, literature]   
1   M.G.  [physics, mathematics, geography, history]   
2   L.D.  [latin, literature, mathematics]   

                            Score    # + other 27 columns
0       [10, 8, 8.5]  
1       [5, 4, 8, 8.5]  
2       [4, 5, 5]  
Run Code Online (Sandbox Code Playgroud)

如何将列表中的元素转换为单独的行,以使主题和分数位于行而不是列表中?

一般来说,

Student     Subject                          Score
student 1  student 1's subject 1         student 1' score for subject 1
student 1  student 1's subject 2         student 1' score for subject 2
Run Code Online (Sandbox Code Playgroud)

May*_*wal 5

假设df是:

In [2893]: df = pd.DataFrame({'Student':['J.M.', 'M.G.', 'L.D.'], 'Subject':[['mathematics', 'history', 'literature'], ['physics', 'mathematics', 'geography', 'history'], ['latin', 'literature', 'mathematics']], 'Score':[[10, 8, 8.5], [5, 4, 8, 8.5], [4,
      ...:  5, 5]]})

In [2894]: df
Out[2894]: 
  Student                                     Subject           Score
0    J.M.          [mathematics, history, literature]    [10, 8, 8.5]
1    M.G.  [physics, mathematics, geography, history]  [5, 4, 8, 8.5]
2    L.D.            [latin, literature, mathematics]       [4, 5, 5]
Run Code Online (Sandbox Code Playgroud)

df.explode与以下一起使用df.apply

In [2898]: df = df.apply(pd.Series.explode)

In [2899]: df
Out[2899]: 
  Student      Subject Score
0    J.M.  mathematics    10
1    J.M.      history     8
2    J.M.   literature   8.5
3    M.G.      physics     5
4    M.G.  mathematics     4
5    M.G.    geography     8
6    M.G.      history   8.5
7    L.D.        latin     4
8    L.D.   literature     5
9    L.D.  mathematics     5
Run Code Online (Sandbox Code Playgroud)