Home > OS >  How do you map the index of a tuple nested in a dictionary using Pandas?
How do you map the index of a tuple nested in a dictionary using Pandas?

Time:06-25

In Pandas, is there a way to map the index of a tuple nested as an element in a dictionary? For example, if I have a dictionary with fruits as keys and an element consisting of a tuple with two fruit characteristics such as color and size.

Fruit_dict = {
    'Apple' : ('red', 'small'),
    'Pear' : ('green', 'small'),
    'Grapefruit' : ('yellow', 'big')
}

I would like to map each characteristic (color and size) to a separate df series. Is it possible to map the index of a tuple? If I apply the map function to the dictionary, it returns the entire tuple.

df['Color'] = df['Fruit'].map(Fruit_dict)

An alternative is to create two separate dictionaries, following this example, one for color one for size and mapping those separately. Such as:

Fruit_color = {
    Apple : red
    Pear : green
    Grapefruit : yellow
}

Fruit_size = {
    Apple : small,
    Pear : small,
    Grapefruit : big
}

df['Color'] = df['Fruit'].map(Fruit_color)
df['Size'] = df['Fruit'].map(Fruit_size)

There would be much less lines of code if I could use one dictionary with tuples as elements.

CodePudding user response:

.map also accepts a callable:

df['Color'] = df['Fruit'].map(lambda fruit: Fruit_dict[fruit][0])

CodePudding user response:

Try:

df["Color"] = df["Fruit"].map(Fruit_dict).str[0]
  • Related