【问题标题】:df. drop results in unsupported operand type(s) for &: 'float' and 'bool'df。 drop 导致 &: 'float' 和 'bool' 的操作数类型不受支持
【发布时间】:2021-03-31 21:40:27
【问题描述】:

我想删除具有以下条件的行,但遇到以下错误: 我们如何删除具有不同 cariable 类型的 2 个条件的行?

result['LastDigit']= result['IP'].str.strip().str[-1].astype(int)

result = result.drop(result[result['Type']=='A'] & result[result['LastDigit'] %2 ==0], axis=1)

错误:

Exception has occurred: TypeError
unsupported operand type(s) for &: 'float' and 'bool'

示例:

    UniqueCode  ID     IP_Address       Name    Type LastDigit
0      QQ       22     172.16.1.67      Name1     A     7
2      XX       33     172.2.12.68      Name2     A     8
4      ZZ       44     10.21.22.2       Name3     B     2

【问题讨论】:

    标签: python python-3.x pandas python-2.7 dataframe


    【解决方案1】:

    使用 boolean indexing~ 反转原始掩码,并添加 () 因为运算符的优先级:

    result = result[~((result['Type']=='A') & (result['LastDigit'] %2 ==0))]
    

    或反转掩码以测试不等于| 按位OR

    result = result[(result['Type']!='A') | (result['LastDigit'] %2 !=0)]
    print (result)
      UniqueCode  ID   IP_Address   Name Type  LastDigit
    0         QQ  22  172.16.1.67  Name1    A          7
    4         ZZ  44   10.21.22.2  Name3    B          2
    

    【讨论】:

    • 我添加了代码,但什么也没发生。但是有多个具有上述条件的行。
    • @SaraDaniel - 是否可以为测试解决方案添加一些示例数据,例如 2-5 行?
    • 确定已共享。
    • @SaraDaniel - 对我来说工作得很好,只是添加到答案中。
    • 这是我的错。非常感谢。它工作正常。
    猜你喜欢
    • 2021-03-03
    • 2018-12-26
    • 1970-01-01
    • 2013-05-08
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多