【问题标题】:iterate over pandas series, if and isin for different actions迭代 pandas 系列,if 和 isin 以执行不同的操作
【发布时间】:2020-01-20 15:46:29
【问题描述】:

检查:

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Iterate over pandas series

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iteritems.html

我尝试做的是,基于一系列值采取不同的行动:

import pandas as pd
s = pd.Series([1,2,3, 4, 5, 6], name='number')
check_1 = ([1,2,3])
check_2 = ([4, 5, 6])
enter code here

不同的动作:

for index, value in s.items():
    if s.isin([check_1]).any():
        print('checked_1')
    elif s.isin([check_2]).any():
        print('checked_2')
    else:
        print ('nothing')

我得到的是:

nothing --> *should be checked_1*  
nothing --> *should be checked_1*
nothing --> *should be checked_1*
nothing --> *should be checked_2*
nothing --> *should be checked_2*
nothing --> *should be checked_2*

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我会这样做:

    for index, value in s.items():
        if value in check_1:
            print('checked_1')
        elif value in check_2:
            print('checked_2')
        else:
            print ('nothing')
    

    【讨论】:

      【解决方案2】:

      您的代码不起作用,因为首先您将 check_1 保留在方括号中,即:您将列表保留在方括号中。即使你删除它,它也不起作用:它会一直给出结果checked_1。 原因:

      s.isin(check_1) #If you execute this it will return below:
          0     True
          1     True
          2     True
          3    False
          4    False
          5    False
          Name: number, dtype: bool
      

      当您在上述输出上运行 .any() 时,您将始终得到 True。因为 .any 如果任何一个值为 True,则返回 True,如果所有值为 false,它将返回 False。因此,您将永远不会越过“if”,也永远不会到达 else 块。

      s.isin(check_1).any()
      > True
      

      至于回答,我会做同样的 hichame.yessou 的回答:因此不转发。

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        • 1970-01-01
        • 2018-11-28
        • 1970-01-01
        • 1970-01-01
        • 2019-12-14
        相关资源
        最近更新 更多