繁体   English   中英

每次在for循环python中满足条件时如何添加到空列表?

[英]how to add to an empty list each time a condition is met in a for loop python?

所以我有一个循环遍历国家的for循环,每个国家都有是或否,我希望每次触发是时将相应的动物添加到列表中。 例如,我有一个清单

国家 = ['Germany','France'..etc 等]

我的 DF 是这样的

animal  Germany  France  
Rabbit    yes       yes
Bear      no        yes
...

我想要一个动物列表,以便在国家列表中选择的国家有一个是的。 所以在上面的例子中,我想要

animal_list = [兔子,兔子,熊]

我的主要代码是这样的,我在下面也有我的尝试,但它不起作用。 有干净的方法吗?

 Countries = ['Germany','France'..etc etc]
 animals_list = []
 for country in Countries:
   animal_list = animal_list.append(df[df[country] == 'yes'],'animal'])

for 循环是必需的,所以我无法使用 pandas 立即完成。

考虑到您有这样的 Dataframe

data = {'animal':['Rabbit', 'Bear'],
    'Germany':['yes', 'no'],
    'France': ['yes', 'no']
   }
df = pd.DataFrame(data)

如果通缉国家列在列表中:

# In Python, Try to use lowercase, underscore seperated names for your variables (PEP8)

countries = ['Germany', 'France']

然后你可以 select 这些列:

# Select the countries that you want
df_subset = df[df.columns.intersection(countries)]

并计算每只动物的yes数:

animals_index_to_num_yes = df_subset.eq('yes').sum(axis=1)

通过这种方式,可以很容易地创建列表:

animals_list = []

for index, animal in df['animal'].iteritems():
    occurences = animals_index_to_num_yes.get(index)
    animals_list.extend(
        [animal] * occurrences
    )

笔记:

  1. 尽量避免 Pandas 中的for循环,一般来说,内置方法会因为使用并发而有更好的性能。 有关更多信息,请参阅这个出色的答案。
  2. 在您的情况下,由于 output 列表中动物的顺序很重要,我不确定是否可以避免循环,因此我使用了for循环。
animals_list=[]
country_list=['germany','france']

for i in range(len(df)):
    for country in country_list:
        if df[country].iloc[i]=='yes':
            animals_list.append(df.animal.iloc[i])

打印(动物列表)

Output:['兔子','兔子','熊']

我找到了一个非常简单的解决方案,似乎对我有用。

Countries = ['Germany','France'..etc etc]
animals_list = []
for country in Countries:
   animals = list(df[df[country] == 'yes'],'animal'])
   animals_list = animals_list + animals

暂无
暂无

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

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