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]] 
8
  • Possible duplicate of Pandas DataFrame to List of Lists Commented Nov 27, 2019 at 2:14
  • 1
    I checked that @NatheerAlabsi. I've referenced the differences in the question Commented Nov 27, 2019 at 2:21
  • Don’t use .values. For the sake of curiosity, why do you need to do this? Commented Nov 27, 2019 at 5: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. Commented Nov 27, 2019 at 5:36
  • yep this works. I need it for a later function. Specifically, to iterate more efficiently. Did you down vote everyones post? Commented Nov 27, 2019 at 5:46

4 Answers 4

1

IIUC

df.X.values[:,None].tolist() Out[85]: [[1], [2], [3], [4], [5], [2], [3], [4], [5], [6]] 
Sign up to request clarification or add additional context in comments.

Comments

1

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

res_list = [[elem] for elem in df['X']] 

Comments

0

Try this:

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

output:

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

1 Comment

I’m pretty sure you could just do .map(list).tolist().
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()] 

1 Comment

Why the .values.tolist()?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.