2

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
  • 2
    The obvious question: why? :0 Commented Mar 6, 2014 at 6:00

1 Answer 1

8

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Output of tolist() is similar to the one that I get from the In [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])]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.