1

How can you convert a single df column to a list of lists? using the df below, how can you return X to a list of lists.

df = pd.DataFrame({                
    'X' : [1,2,3,4,5,2,3,4,5,6],
    'Y' : [11,12,13,14,15,11,12,13,14,15],
    })

l = df['X'].values.tolist()

[1, 2, 3, 4, 5, 2, 3, 4, 5, 6]

Converting two columns is possible:

l = df.values.tolist()
[[1, 11], [2, 12], [3, 13], [4, 14], [5, 15], [2, 11], [3, 12], [4, 13], [5, 14], [6, 15]]

But I just want X.

[[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]]
sashaaero
  • 2,618
  • 5
  • 23
  • 41
jonboy
  • 415
  • 4
  • 14
  • 45
  • Possible duplicate of [Pandas DataFrame to List of Lists](https://stackoverflow.com/questions/28006793/pandas-dataframe-to-list-of-lists) – Natheer Alabsi Nov 27 '19 at 02:14
  • 1
    I checked that @NatheerAlabsi. I've referenced the differences in the question – jonboy Nov 27 '19 at 02:21
  • Don’t use `.values`. For the sake of curiosity, why do you need to do this? – AMC Nov 27 '19 at 05:31
  • Also, could you tell me if the solution I posted works correctly? I don’t have access to a computer right now, so I want to be entirely certain. – AMC Nov 27 '19 at 05:36
  • yep this works. I need it for a later function. Specifically, to iterate more efficiently. Did you down vote everyones post? – jonboy Nov 27 '19 at 05:46
  • @jonboy It seems like it, in the end. Do you want to know why, for any particular one? I am curious to know what kind of iteration requires singleton lists. Presumably it is more efficient that using Pandas? – AMC Nov 27 '19 at 05:47
  • Inefficiency for the down votes I assume? I need to animate in a later function. – jonboy Nov 27 '19 at 05:50
  • @jonboy For the downvotes, you mean? Ooh, animation, I definitely did not expect that one. – AMC Nov 27 '19 at 05:52

4 Answers4

1

IIUC

df.X.values[:,None].tolist()
Out[85]: [[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]]
BENY
  • 317,841
  • 20
  • 164
  • 234
1

Some of these solutions seem overcomplicated. I believe this should do the job.

res_list = [[elem] for elem in df['X']]
AMC
  • 2,642
  • 7
  • 13
  • 35
0

If you want this output

[[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]]

when starting with the input: [1,2,3,4,5,2,3,4,5,6]

then this should work fine

l = [[i] for i in df['X'].values.tolist()]
MoonMist
  • 1,232
  • 6
  • 22
0

Try this:

 df['X'].apply(lambda x: [x]).tolist() 

output:

[[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]]
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24