【问题标题】:numpy.where contains string condition [duplicate]numpy.where 包含字符串条件 [重复]
【发布时间】:2021-09-03 11:17:40
【问题描述】:

为了缩短执行时间,我用 np.where() 中的条件替换了一个理解列表。它在值匹配的地方工作正常,但我希望有一个条件,即字符串中的值不相等:

import numpy as np
currencies = np.array(["USD","NZL","EUR","KWR"])
currencie = [x for x in list(currencies) if x in "USDKLR EUR"]
#returns ["USD","EUR"]
#What works:
currencie = currencies[np.where(currencies == "EUR")]
#returns ["EUR"]

我想要的是 in 条件,但使用 np.where 或 numpy 函数,没有列表处理。

currencie = currencies[np.where(currencies in "USDKLR EUR")]

【问题讨论】:

  • 我已经更新了我的问题。很抱歉造成混乱。
  • where 仅与其条件参数一样好。它不是一个迭代器。它只是找到 True 元素。虽然 numpy 有一组字符串函数,但它们使用字符串方法并且并不比列表理解快。

标签: python numpy


【解决方案1】:

问题基本上已经被here问过了。

解决办法是:

In [6]: currencie = currencies[ 
   ...:     np.where( 
   ...:         np.core.defchararray.find( 
   ...:             "USDKLR EUR", currencies 
   ...:         ) != -1 
   ...:     ) 
   ...: ]                            

In [7]: currencie                                                                                                             
Out[7]: array(['USD', 'EUR'], dtype='<U3')

有关解释,请参阅链接的问题。

【讨论】:

  • np.char.find 也可以。
猜你喜欢
  • 2014-05-12
  • 2012-11-14
  • 2017-09-01
  • 2019-09-22
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多