Pandas DataFrame column values in to list

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

I have a pandas DataFrame like following

                          clusters 0                              [4] 1                  [9, 14, 16, 19] 2           [6, 7, 10, 17, 18, 20] 3  [1, 2, 3, 5, 8, 11, 12, 13, 15] 

I need to get only the integer values in the cluster column separately. Like following(This can be four lists no need of having another DataFrame)

0                              4 1                  9, 14, 16, 19 2           6, 7, 10, 17, 18, 20 3  1, 2, 3, 5, 8, 11, 12, 13, 15 

I tried different things. Could not achieve the expected output.

In [36]: clustlist = list(firstclusters.clusters.values) Out[36]:        [array([4]), array([ 9, 14, 16, 19]), array([ 6,  7, 10, 17, 18, 20]), array([ 1,  2,  3,  5,  8, 11, 12, 13, 15])]  In [37]: np.ravel(clustlist) Out[37]:     [array([4]) array([ 9, 14, 16, 19]) array([ 6,  7, 10, 17, 18, 20])      array([ 1,  2,  3,  5,  8, 11, 12, 13, 15])]  In [38]: np.hstack(clustlist) Out[38]:     [ 4  9 14 16 19  6  7 10 17 18 20  1  2  3  5  8 11 12 13 15] 

回答1:

If each item is just a list, you can use the tolist Series method:

In [11]: df.clusters.tolist() Out[11]: [[4], [9, 14, 16, 19], [6, 7, 10, 17, 18, 20], [1, 2, 3, 5, 8, 11, 12, 13, 15]] 

Or, if these are numpy arrays you need to apply tolist to each item first:

In [12]: df.clusters.apply(np.ndarray.tolist).tolist() Out[12]: [[4], [9, 14, 16, 19], [6, 7, 10, 17, 18, 20], [1, 2, 3, 5, 8, 11, 12, 13, 15]] 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!