1

If I have a df like this:

df1 = pd.DataFrame({'col1': [1, 1, 2, 2], 'col2': [10, 20, 10, 20]}) 

How would I get a list that pairs each row of col1 and col2 like so:

outputlist = [[1, 10], [1, 20], [2, 10], [2, 20]] 

I've found ways to turn lists into df columns, but not the other way around!

0

1 Answer 1

2

You could do (see tolist):

import pandas as pd df1 = pd.DataFrame({'col1': [1, 1, 2, 2], 'col2': [10, 20, 10, 20]}) result = df1.values.tolist() print(result) 

Output

[[1, 10], [1, 20], [2, 10], [2, 20]] 
Sign up to request clarification or add additional context in comments.

5 Comments

Not even sure tolist is needed.
@kabanus What do you mean?
From OP's requirements the value array might be good enough (maybe better?) Anyway, nice answer.
How would I select specific columns? eg if I have a col3, but I only want col1 and col2 to be in the output? I realize I could just drop col3 and then use .tolist(), but I was just curious.
I guess you could do: df1[['col1', 'col2']].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.