简体   繁体   English

如何使用 Pandas 映射嵌套在字典中的元组的索引?

[英]How do you map the index of a tuple nested in a dictionary using Pandas?

In Pandas, is there a way to map the index of a tuple nested as an element in a dictionary?在 Pandas 中,有没有办法将嵌套为字典中元素的元组的索引映射? 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.我想将每个特征(颜色和大小)映射到一个单独的 df 系列。 Is it possible to map the index of a tuple?是否可以映射元组的索引? If I apply the map function to the dictionary, it returns the entire tuple.如果我将 map 函数应用于字典,它会返回整个元组。

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.如果我可以使用一个带有元组作为元素的字典,那么代码行会少得多。

.map也接受一个可调用的:

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

尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM