【问题标题】:Logical Operator Python two == does not work in iteration dataframe逻辑运算符 Python 两个 == 在迭代数据帧中不起作用
【发布时间】:2020-06-19 22:33:47
【问题描述】:

我有一个数据框,想选择两行以使用自定义函数在这些行之间进行插值。问题是我只看到一行并且不明白为什么我的声明不起作用。数据如下所示:

        DataPoint   Rank
1       -9.360001   1.0
2       -9.080002   2.0
3       -9.039993   3.0
4       -7.529999   4.0
5       -7.479996   5.0
...     ...     ...     ...     ...

我想插入例如在等级 2.0 和 3.0 之间。代码如下所示:

Rank = data[['DataPoint']].count().values[0]*(1-0.99)
check_int = isinstance(Rank, int)
if not check_int:
        #loop 
        for ind in data.index:
            if (data['DataPoint'][ind] == (2.0 and 3.0)):
                print(data['DataPoint'][ind], data['Rank'][ind])

作为输出我只收到:

-9.03999300000001 3.0

但不是额外的

-9.080002 2.0

【问题讨论】:

  • data['DataPoint'][ind] == (2.0 and 3.0) 等价于data['DataPoint'][ind] == 3.0。因为2.0 and 3.0 被评估为3.0

标签: python pandas dataframe if-statement logical-operators


【解决方案1】:

试试这个,看看它是否适合你:
基本上声明 (2.0 and 3.0) 只选择等级为 3.0 的行 您需要像下面那样手动指定范围:

ank = data[['DataPoint']].count().values[0]*(1-0.99)
check_int = isinstance(Rank, int)
if not check_int:
        #loop 
        for ind in data.index: # Below line, picks ranks more than 2.0 but less than 3.0
            if (data['Rank'][ind] >= 2.0 and data['Rank'][ind] <= 3.0):
                print(data['DataPoint'][ind], data['Rank'][ind])

【讨论】:

    【解决方案2】:

    (2.0 and 3.0) 的计算结果为 3.0,因为这是要计算的最后一件事。这就是您缺少2.0 的原因。

    您可以将其更改为 in 以保持一行。

    if data['Rank'][ind] in (2.0, 3.0):
        ...
    

    【讨论】:

    • 根据PEP8,用(2.0, 3.0)代替(2.0, 3.0,)
    • 感谢这个解决方案也有效。但我喜欢这两种方法,但只能选择一种。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    相关资源
    最近更新 更多