要列出的 Pandas DataFrame 列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/22216111/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas DataFrame column values in to list
提问by Nilani Algiriyage
I have a pandas DataFramelike following
我有一只DataFrame像下面这样的Pandas
                          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)
我只需要分别获取簇列中的整数值。喜欢以下(这可以是四个列表,不需要另一个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]
回答by Andy Hayden
If each item is just a list, you can use the tolist Series method:
如果每个项目只是一个列表,则可以使用 tolist Series 方法:
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:
或者,如果这些是 numpy 数组,您需要先将 tolist 应用于每个项目:
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]]

