【问题标题】:How to check whether a string is a first occurrence in a pandas series?如何检查字符串是否是熊猫系列中的第一次出现?
【发布时间】:2021-07-16 17:59:35
【问题描述】:

如果我有以下系列, s= ['苹果', '苹果', '香蕉', 西瓜, '苹果', '香蕉']

如果我遍历这个系列,那么我想知道索引 1 处的“Apple”是否是第一次出现。

【问题讨论】:

    标签: python pandas series


    【解决方案1】:

    首先,你发的是简单的list,不是PANDAS系列。

    在这种情况下,只需使用index 命令即可;它返回第一次出现的索引。

    if s.index("Apple") == 1:
        # The first occerrence, is, indeed at position 1
    else:
        # No, it isn't ...
    

    【讨论】:

      【解决方案2】:
      s= ['Apple', 'Apple', 'Banana', 'Watermelon', 'Apple', 'Banana']
      temp = set()
      ans = []
      for item in s:
          if item not in temp:
              temp.add(item)
              ans.append(True)
          else:
              ans.append(False)
      print(ans)
      >>> [True, False, True, True, False, False]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-31
        • 1970-01-01
        • 2014-08-30
        • 2021-07-12
        • 2018-03-12
        • 2015-05-31
        • 2021-04-21
        • 2020-09-19
        相关资源
        最近更新 更多