【问题标题】:python-Dataframe count rows with conditionpython-Dataframe 计算有条件的行
【发布时间】:2020-11-02 19:12:20
【问题描述】:

我有一个 python 代码从这样的数据帧 (df1) 中收集信息

for ind, data in enumerate(df1.Link):
         print(data)
         
         
         result = getInformation(driver, links)
         
         for i in result['information']:
             df1.loc[ind, "numOfWorkers"] = i["numOfWorkers"]

输出被保存到如图所示的数据框:

在返回具有这种情况的数据帧之前,是否有更新我的代码: 如果 noOfWorkers >=30,一旦我们有 2 个链接具有此条件,代码将中断并返回结果

有人可以帮忙吗?

【问题讨论】:

    标签: python dataframe spyder


    【解决方案1】:

    最好将逻辑放在您已有的代码中。我会记录匹配条件的记录数,然后使用 break(而不是 while 循环)退出循环:

         ...
         workers_threshold = 30
         records_matching_threshold = 0
         max_records_for_matching_records = 2
         for i in result['information']:
             df1.loc[ind, "numOfWorkers"] = i["numOfWorkers"]
             if i["numOfWorkers"] > workers_threshold:
                 records_matching_threshold += 1
             if records_matching_threshold > max_records_for_matching_records:
                 break
    

    请注意,为了在我的示例中明确它们的目的,上面的变量名故意加长。

    【讨论】:

      【解决方案2】:
      i = 2
      while i != 0:
          if numOfWorkers >= 30:
              i- = 1
      

      【讨论】:

      • 感谢您的回答。你认为它应该在循环中吗? (for i in result['information']) ?
      • 此代码存在一些问题:i 已被用于其他用途; numOfWorkers 实际上没有设置;不需要使用 while 循环(我们已经在循环中);如果使用不当,这有可能成为无限循环。
      • 是的,我知道,但这只是为了向他展示程序应该做什么,我从不代替其他人编写代码,这会妨碍他们学习
      猜你喜欢
      • 2017-03-01
      • 2022-11-10
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2023-04-06
      • 2014-10-28
      相关资源
      最近更新 更多