Generating tuples from DataFrame row elements

Viewed 1350

I hope this is not me doing something stupid programmatically.

I have a one row Dataframe with numerical Values:

df1                          A            B            C          D

 01-02-2003T00:00:00         5.0         7.0          2.0        4.0   ....

I want to generate a list of tuples based on the values in the dataframe. I do the following:

my_array = numpy.array(df1)

which give me:

           0            1            2          3

 0        5.0          7.0          2.0        4.0   ....

Then I do:

 my_tuple_of_tuples =  tuple((0.5*x, 1.5*x) for x in my_array)

I expect this:

((2.5,7.5),(3.5,10.5),(1.0,3.0),(2.0,6.0))

but I get this:

((2.5,3.5,1.0,2.0),(7.5,10.5,3.0,6.0)) 

What am I doing wrong?

1 Answers

Just index the first row, then your code should work:

tup = tuple((0.5 * x, 1.5 * x) for x in df.values.tolist()[0])
print(tup)
# ((2.5, 7.5), (3.5, 10.5), (1.0, 3.0), (2.0, 6.0))

This works because

df.values.tolist()[0]
# [5.0, 7.0, 2.0, 4.0]

Returns a list of all elements in the first row only. Now, iteration as you do it will work.


If you need this to work for multiple rows, you can convert this to a nested loop, or use chain.from_iterable.

from itertools import chain
tup = tuple(
    (0.5 * x, 1.5 * x) for x in chain.from_iterable(df.values.tolist()))
print(tup)
# ((2.5, 7.5), (3.5, 10.5), (1.0, 3.0), (2.0, 6.0))
Related