Gabriela M
Gabriela M

Reputation: 615

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!!!

Upvotes: 8

Views: 10554

Answers (3)

R Walser
R Walser

Reputation: 494

Though it is not recommended for large dataframes, you can also use apply

import pandas as pd
df = pd.DataFrame([['Apples', '014'], 
                   ['Oranges', '015'],
                   ['Bananas', '017'],
                   ['Grapes', '021']], columns = ['Fruit', 'Value'])

my_fruits = tuple(df[['Fruit','Value']].apply(tuple, axis=1))
my_fruits

Giving:

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

Use df.columns instead of explicitly typing out the column names if you want it to be more generic.

Upvotes: 0

TheHCA
TheHCA

Reputation: 346

Would something like this work?

tuple(df.itertuples(index=False, name=None))

Upvotes: 12

akuiper
akuiper

Reputation: 215137

You need to zip the two columns:

tuple(zip(df.Description, df.Code))
# (('Apples', 14), ('Oranges', 15), ('Bananas', 17), ('Grapes', 21))

Upvotes: 3

Related Questions