【问题标题】:Python multiple conditions with numpy.where [duplicate]带有numpy.where的Python多个条件[重复]
【发布时间】:2018-12-22 10:31:02
【问题描述】:

我正在尝试对 pandas 数据框进行一些简单的操作。我已将 pandas 导入为 pd,将 numpy 导入为 np,并导入了一个 csv 以创建一个名为“dfe”的数据框。

我已成功使用以下代码根据一个条件填充新列:

dfe['period'] = np.where(dfe['Time'] >= "07:30:00.000" , '1', '2')

但是当我尝试使用类似的技术根据两个条件填充同一列时,我收到一个错误(&: 'bool' 和 'str' 的操作数类型不受支持)

这是我对多条件版本的尝试:

dfe['period'] = np.where(dfe['Time'] >= "07:30:00.000" & dfe['Time'] <= "10:00:00.000" , '1', '2')

我已经查看了许多类似问题的解决方案,但鉴于我刚刚开始并希望有人能给我一些关于为什么这不起作用的线索,它们都对我来说有点太复杂了。

谢谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你很接近,() 丢失了,因为运营商的优先级:

    dfe['period'] = np.where((dfe['Time'] >= "07:30:00.000") & 
                             (dfe['Time'] <= "10:00:00.000") , '1', '2')
    

    between 的另一种解决方案:

    dfe['period'] = np.where(dfe['Time'].between("07:30:00.000", "10:00:00.000") , '1', '2')
    

    【讨论】:

    • 谢谢。中间版本真的很整洁
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2014-04-13
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    相关资源
    最近更新 更多