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

标签 python pandas dictionary tuples

在 Pandas 中,有没有办法映射嵌套为字典中元素的元组的索引?例如,如果我有一个以水果为键的字典,以及一个由具有两个水果特征(例如颜色和大小)的元组组成的元素。

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

我想将每个特征(颜色和尺寸)映射到单独的 df 系列。是否可以映射元组的索引?如果我将映射函数应用于字典,它将返回整个元组。

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

另一种方法是按照本例创建两个单独的字典,一个用于颜色,一个用于大小,并分别映射它们。如:

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)

如果我可以使用一个以元组作为元素的字典,代码行就会少得多。

最佳答案

.map 也接受可调用:

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

关于python - 如何使用 Pandas 映射嵌套在字典中的元组的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72749385/

相关文章:

python - 当键对应于列表时仅对字典中的第一个值求和 (Python)

python - 如何在 Vim 中通过 ALE 运行 isort?

python - pip 卸载时出现权限错误

python - 为什么将列表与整数进行比较不会出错?

python - 根据值将数组拆分为多个新数组

python-3.x - 来自 Pandas 数据框的有向加权图

python - 将不同长度的列表作为新列添加到数据框

python - 将索引上的数据框与 Pandas 合并

python - 如何映射到 Pandas 列表列中的值

c++ - 用于高效查找通用字符串的 map 或 hashmap?