Home > OS >  Python: Save a tuple in a list
Python: Save a tuple in a list

Time:01-18

From data saved in a DataFrame, I have to re-create the format below (i.e. list(tuple(tuples))), so it should have the same structure as:

coord = [((9, 9), (10, 6), (11, 3),(12, 6))]

So far I have been able to create the tuples from DataFrame by this code:

coord_y = tuple(data_df['data'].iloc[i:])
coord_x = tuple(data_df['data'].index.values[i:])

coord = list(zip(coord_x, coord_y)) # stack into (x,y) coord

which yields:

[(9, 9), (10, 6), (11, 3), (12, 6)]

Which is wrong because it is missing the "outer" tuple and should look like this:

[((9, 9), (10, 6), (11, 3),(12, 6))]

What am I doing wrong?

CodePudding user response:

tuple() creates a tuple with all the data instead of a list(), and enclosing brackets [] create a new list with one element - early created tuple:

coord = [tuple(zip(coord_x, coord_y))] # stack into (x,y) coord

CodePudding user response:

One of these should do:

[(tuple(zip(coord_x, coord_y), ))]

or

[(*zip(coord_x, coord_y), )]

CodePudding user response:

Just wrap your zip in a tuple.

coord_y = tuple(data_df['data'].iloc[int(time_steps[-1]-l-1):])
coord_x = tuple(data_df['data'].index.values[int(time_steps[-1]-l-1):])

coord = [tuple(zip(coord_x, coord_y))] # stack into (x,y) coord

CodePudding user response:

if your dataframe is df = pd.DataFrame({"data":[9,9,10,6,11,3,12,6]})

you could ise the itertools module:

from itertools import islice
import pandas as pd
def group_elements(lst, chunk_size):
    lst = iter(lst)
    return iter(lambda: tuple(islice(lst, chunk_size)), ())
df = pd.DataFrame({"data":[9,9,10,6,11,3,12,6]})
print([x for x in group_elements(df["data"],2)])
  •  Tags:  
  • Related