我有工作代码,可以根据列表字典中的规则对数据进行分类。我想知道是否可以通过使用list/dictionary理解或.values()去掉嵌套的for循环来提高代码的效率。

import pandas as pd


df=pd.DataFrame({'Animals': [ 'Python', 'Anaconda', 'Viper', 'Cardinal',
                 'Trout', 'Robin', 'Bass', 'Salmon', 'Turkey', 'Chicken'],
                 'Noise': ['Hiss','SSS','Hisss','Chirp','Splash','Chirp',
                 'Gulp','Splash','Gobble','Cluck'],
                 })


snakenoise =['Hiss','SSS','Hisss', 'Wissss', 'tseee']
birdnoise =['Chirp', 'squeak', 'Cluck', 'Gobble']
fishnoise =['Splash', 'Gulp', 'Swim']


AnimalDex = {'Snake':['0', 'slither',snakenoise],
              'Bird':['2','fly', birdnoise],
              'Fish':['0','swim',fishnoise],
              }

df['movement'] = ''

for key, value in AnimalDex.items():
    for i in range(len(AnimalDex[key][2])):
        df.loc[df.Noise.str.contains(AnimalDex[key][2][i]),'movement'] = AnimalDex[key][1]

print (df)

这是输出
    Animals   Noise movement
0    Python    Hiss  slither
1  Anaconda     SSS  slither
2     Viper   Hisss  slither
3  Cardinal   Chirp      fly
4     Trout  Splash     swim
5     Robin   Chirp      fly
6      Bass    Gulp     swim
7    Salmon  Splash     swim
8    Turkey  Gobble      fly
9   Chicken   Cluck      fly

最佳答案

如果只使用值而不是键和索引,则可以真正简化循环。

for animal in AnimalDex.values():
    for value in animal[2]:
        df.loc[df.Noise.str.contains(value),'movement'] = animal[1]

关于python - Python 3有效地遍历列表字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29916372/

10-13 07:00