5

How can I convert two columns in a dataframe into an interposed list?

ex: I want to do something like

df

             Open  Close
Date
2016-12-23  1      2
2016-12-27  3      4
2016-12-28  5      6
2016-12-29  0      -1

someFunction(df)

>>> [1, 2, 3, 4, 5, 6, 0, -1]

Closest I've found is list(zip(df.Open, df.Close) but that returns a bunch of tuples in the list like this: [(1, 2), (3, 4), (5, 6), (0, -1)]

1

5 Answers 5

5

Try this:

df.values.flatten()                                                                                                                                                                  
# array([ 1,  2,  3,  4,  5,  6,  0, -1])
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, what if there are a bunch of other columns in between? Is there a more pythonic way than just grabbing the first 2 columns into its own DF or dropping the rest of the columns?
If you want, you can just pick the columns you want to flatten: df[['Open', 'Close']].values.flatten()
this is: df.stack().values
2

IIUC

df.values.ravel().tolist()#df.to_numpy().ravel().tolist()

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

1 Comment

may I know the reason downvote ?
2

How about:

df.stack().values
#array([ 1,  2,  3,  4,  5,  6,  0, -1])

Comments

1

You can obtain the values, and reshape it to a 1d array:

>>> df[['Open', 'Close']].values.reshape(-1)
array([ 1,  2,  3,  4,  5,  6,  0, -1])

or convert that to a list:

>>> list(df[['Open', 'Close']].values.reshape(-1))
[1, 2, 3, 4, 5, 6, 0, -1]

Comments

1

You could use a list comprehension in combination with df.values:

[y for x in df.values for y in x]
[1, 2, 3, 4, 5, 6, 0, -1]

x will be an array with the rows, and y will be the values in those rows

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.