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)]

Michael
  • 776
  • 4
  • 19
  • Does this answer your question? [Pythonic way to combine two lists in an alternating fashion?](https://stackoverflow.com/questions/3678869/pythonic-way-to-combine-two-lists-in-an-alternating-fashion) – Simon Crane Dec 25 '19 at 23:21

5 Answers5

5

Try this:

df.values.flatten()                                                                                                                                                                  
# array([ 1,  2,  3,  4,  5,  6,  0, -1])
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
2

IIUC

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

[1, 2, 3, 4, 5, 6, 0, -1]
BENY
  • 317,841
  • 20
  • 164
  • 234
2

How about:

df.stack().values
#array([ 1,  2,  3,  4,  5,  6,  0, -1])
ansev
  • 30,322
  • 5
  • 17
  • 31
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]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
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

KenHBS
  • 6,756
  • 6
  • 37
  • 52