繁体   English   中英

是否有一个 numpy 函数可以根据列表索引将 str 替换为 int 值

[英]Is there a numpy function to replace str to int values based on list index

有没有办法在没有 for 循环的情况下完成下面的代码?

我根据它的索引位置将 int 值分配给 str 。

import numpy as np
icing_types=[
    "none",
    "l-mixed",
    "l-rime",
    "l-clear",
    "m-mixed",
    "m-rime",
    "m-clear",
]
idx=np.array(icing_types)
#validtime=basetime+index hr
forecast_icing=[
    "none", 
    "none", 
    "l-rime",
    "m-rime"
]
arr=np.array([np.where(ice==idx)for ice in forecast_icing]).flatten()

没有,但我不是 100% 确定。

无论如何,即使有,您也可以通过使用映射 dict (icing_type -> idx) 获得更好的性能:

icing_type_to_idx = {icinig_type: idx for idx, icing_type in enumerate(icing_types)}
arr = np.array([icing_type_to_idx[ice] for ice in forecast_icing])

借用这个答案,您可以生成地图并对函数进行矢量化。 值得注意的是,这里的另一个答案更快。

import numpy as np
icing_types=[
    "none",
    "l-mixed",
    "l-rime",
    "l-clear",
    "m-mixed",
    "m-rime",
    "m-clear",
]


forecast_icing=np.array([
    "none", 
    "none", 
    "l-rime",
    "m-rime"
])

np.vectorize({b:a for a,b in enumerate(icing_types)}.get)(forecast_icing)
In [103]: arr = np.array(forecast_icing)
In [104]: idx,arr
Out[104]: 
(array(['none', 'l-mixed', 'l-rime', 'l-clear', 'm-mixed', 'm-rime',
        'm-clear'], dtype='<U7'),
 array(['none', 'none', 'l-rime', 'm-rime'], dtype='<U6'))

我们可以使用以下方法相互测试 2 个数组:

In [105]: arr[:,None]==idx
Out[105]: 
array([[ True, False, False, False, False, False, False],
       [ True, False, False, False, False, False, False],
       [False, False,  True, False, False, False, False],
       [False, False, False, False, False,  True, False]])

True是:

In [106]: np.where(_)
Out[106]: (array([0, 1, 2, 3]), array([0, 0, 2, 5]))

第二个数组给出了idxarr的匹配:

In [107]: _[1]
Out[107]: array([0, 0, 2, 5])

如果你能保证一场而且只有一场比赛,我认为你不需要做任何更有趣的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM