代码之家  ›  专栏  ›  技术社区  ›  Cláudio Ribeiro

向量化:序列的真值是模糊的

  •  1
  • Cláudio Ribeiro  · 技术社区  · 4 年前

    我正在尝试使用熊猫来应用矢量化的概念。我已经成功地使用了粗循环,但是在同一个代码上,当我尝试矢量化并将整个序列传递给我得到的函数时

    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
    

    我的功能相当简单:

    def price_function(x):
        if x >= 50:
            return "High"
        else:
            return "low"
    

    price 数据帧系列,包括:

    listing_price = price_function(listings_dataframe_big['price'])
    

    错误由以下行触发:

    if x >= 50:
    

    你知道为什么会这样,怎么解决吗?

    2 回复  |  直到 4 年前
        1
  •  0
  •   Wouter    4 年前

    将函数应用于一个系列的所有值的方法是 map .

    listing_price = listings_dataframe_big['price'].map(price_function)
    

    np.were 更容易,更可能更快。

        2
  •  0
  •   tdy TheChimp    4 年前

    请注意 apply() map() 矢量化,只是伪装的循环。

    np.where() 是矢量化的,因此 generally the fastest method

    listing_price = np.where(listings_dataframe_big['price'] >= 50, 'High', 'Low')
    

    x 是一个系列, x >= 50 因为熊猫不知道你是否想要 (x >= 50).any() (x >= 50).all() .