在由Python列表限制的IF语句中进行迭代

时间:2020-02-28 14:56:12

标签: python pandas loops if-statement list-comprehension

假设我有一个df:

     Name    Surname  Age
0    Alex    Jackson   10
1     Bob      Black   12
2  Clarke  Flingston   13
3  Claude      White   11
4   Julia     Waters   10
5  Robert    Ferrari   12
6    Anna        Red    9
7   David       Blue   10
8    Luke        Man   12

并带有:

list_n = []
for age, surname in zip(df.Age, df.Surname):
    if (age != 13 and 
        age != 11 and 
        age != 10):
        list_n.append(surname)

list_n
['Black', 'Ferrari', 'Red', 'Man']

我会得到一个姓氏列表,但不包括一定年龄的姓氏。 是否可以使用年龄列表来迭代if条件?

我尝试使用列表理解,但是它不起作用,因为应该这样:

list_age = [13,11,10]
list_n = []

for age, surname in zip(df.Age, df.Surname):
    [list_n.append(surname) for x in list_Age if age != x]

list_n
['Jackson', 'Jackson',  'Black',  'Black',  'Black', 'Flingston',
 'Flingston',  'White',  'White',  'Waters',  'Waters',  'Ferrari',
 'Ferrari',  'Ferrari',  'Red',  'Red',  'Red',  'Blue',  'Blue',
 'Man',  'Man',   'Man']

3 个答案:

答案 0 :(得分:2)

您还可以直接使用pandas数据框的遮罩技术来获得最终结果,

尝试一下,

list_n = df["Surname"][~df["Age"].isin(list_age)].to_list()

以及执行>>>print(list_n)

输出:

['Black', 'Ferrari', 'Red', 'Man']

答案 1 :(得分:1)

list_n = [surname for age, surname in zip(df.Age, df.Surname)
          if age not in {10, 11, 13}]

答案 2 :(得分:1)

list_n = [surname for age, surname in zip(df.Age, df.Surname) if age not in list_age]