【问题标题】:Iterating inside an IF statement conditioned by a list in Python在 Python 中以列表为条件的 IF 语句中进行迭代
【发布时间】:2020-06-12 16:54:13
【问题描述】:

假设我有一个 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']

【问题讨论】:

  • 我觉得你可以使用df[~df.Age.isin(list_age)] 来获取年龄不等于list_age 中任何年龄的行。听起来不像是 Ahole,但有一种说法是,如果你对 pandas 对象使用 for 循环,你可能会做错事
  • 为什么不替换age != 13 and .... for `age not in list_age`?
  • 是的@Jano 我实际上忘记了“不在”..
  • 无论如何,最好的选择是@Buckeye14Guy 提供的那个。 df[~df.Age.isin(list_age)]['Surname'] .tolist() 如果您希望它是一个专门的列表,请添加它

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


【解决方案1】:

你也可以直接使用pandas dataframe的masking技术来达到最终的效果,

试试这个,

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

当你执行>>>print(list_n)

输出:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      list_n = [surname for age, surname in zip(df.Age, df.Surname)
                if age not in {10, 11, 13}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-24
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多