最简单的方法
Using 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
更复杂
但可能推荐
from sklearn.preprocessing import MultiLabelBinarizer
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']
}
s = pd.Series(dct)
mlb = MultiLabelBinarizer()
d = mlb.fit_transform(s)
c = mlb.classes_
pd.DataFrame(d, s.index, c)
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