Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas dataframe to tuple of tuples

I have the following pandas dataframe df:

     Description    Code
0    Apples         014
1    Oranges        015
2    Bananas        017
3    Grapes         021

I need to convert it to a tuple of tuples, like this:

my_fruits = ( ('Apples', '014'), 
              ('Oranges', '015'), 
              ('Bananas', '017'), 
              ('Grapes', '021')
            )

Can you help me, please? I have tried the following code but it does not return what I really want:

list(zip(df.columns,df.T.values.tolist()))

Thanks in advance!!!

like image 754
Gabriela M Avatar asked Aug 17 '18 14:08

Gabriela M


2 Answers

You need to zip the two columns:

tuple(zip(df.Description, df.Code))
# (('Apples', 14), ('Oranges', 15), ('Bananas', 17), ('Grapes', 21))
like image 29
Psidom Avatar answered Oct 02 '22 03:10

Psidom


Would something like this work?

tuple(df.itertuples(index=False, name=None))
like image 156
TheHCA Avatar answered Oct 02 '22 03:10

TheHCA