有没有从列表字典中创建虚拟变量数据帧的方法?

2024-09-22 16:35:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在《熊猫》中,我有一本字典,它看起来像下面的一本:

{'Anemones & allies': ['Carnivore'],
'Ants, bees & wasps': ['Omnivore',  'Herbivore',  'Nectar',  'Insects', 'Parasite'],
'Beetles & bugs': ['Herbivore', 'Carnivore', 'Nectar', 'Insects'],
'Birds': ['Carnivore'],
'Fishes': ['Carnivore', 'Plankton or Particles']}

我想把它转换成一个数据帧,在这个框架里你可以看到动物类型可能吃什么。因此它看起来与下图类似:

What the DataFrame should look like.

当我试图生成这样一个表时,我有一种不正确的感觉,因为我需要相当多的代码行。所以我的问题是,有没有一个很好的函数将这个字典映射到一个数据帧,这样它看起来像上表中的内容?在


Tags: 数据字典bugsantsomnivoreparasiteinsectsbees
2条回答

dict(d)创建DataFrame,然后使用get_dummies

pd.get_dummies(pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.items() ])).stack()).sum(level=1)
Out[130]: 
                    Carnivore  Herbivore  Insects  Nectar  Omnivore  Parasite  \
Anemones & allies           1          0        0       0         0         0   
Ants, bees & wasps          0          1        1       1         1         1   
Beetles & bugs              1          1        1       1         0         0   
Birds                       1          0        0       0         0         0   
Fishes                      1          0        0       0         0         0   
                    Plankton or Particles  
Anemones & allies                       0  
Ants, bees & wasps                      0  
Beetles & bugs                          0  
Birds                                   0  
Fishes                                  1  

最简单的方法
使用pd.str.get_dummies

dct = {
    'Anemones & allies': ['Carnivore'],
    'Ants, bees & wasps': ['Omnivore',  'Herbivore',  'Nectar',  'Insects', 'Parasite'],
    'Beetles & bugs': ['Herbivore', 'Carnivore', 'Nectar', 'Insects'],
    'Birds': ['Carnivore'],
    'Fishes': ['Carnivore', 'Plankton or Particles']
}

pd.Series(dct).str.join('|').str.get_dummies()

                    Carnivore  Herbivore  Insects  Nectar  Omnivore  Parasite  Plankton or Particles
Anemones & allies           1          0        0       0         0         0                      0
Ants, bees & wasps          0          1        1       1         1         1                      0
Beetles & bugs              1          1        1       1         0         0                      0
Birds                       1          0        0       0         0         0                      0
Fishes                      1          0        0       0         0         0                      1

更复杂
但可能是推荐的

^{pr2}$

相关问题 更多 >