从允许空值且未找到的查找表返回索引

2024-04-18 07:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在允许未找到元素和不存在元素(null)的查找表中查找索引。你知道吗

例如,在下面的测试数据中,变量“A”将映射到查找表中的“A”,并返回索引0(查找表中“A”的位置)

我正在研究使用searchsorted函数,但它没有解释是返回0还是N。你知道吗

如果没有合适的索引,则返回0或N(其中N是a的长度)

从下面,我想返回的数据是: [0,1,2,3,2]

0-匹配, 1-匹配B, 2-找不到其他人, 3-无值,因此为空, 2-未找到其他项。你知道吗

按照规则:

如果匹配返回匹配的索引, 如果NaN返回NULL, 如果找不到,返回其他。你知道吗

testData = np.array(['A','B','B ',NAN,'Other'])
testLookup =np.array(['A','B','ELSE','NULL'])

>>> np.searchsorted(testLookup,testData)
array([0, 1, 2, 0, 4], dtype=int32)

Tags: 数据函数元素规则npnanarraynull
1条回答
网友
1楼 · 发布于 2024-04-18 07:15:08

NumPy不是为混合类型数组设计的。但是如果您打算使用NumPy,您可以在使用np.searchsorted之前通过布尔索引将值转换为适当的值。你知道吗

请记住指定dtype=object以避免np.nan值被自动转换为字符串。你知道吗

testData = np.array(['A','B','B ',np.nan,'Other'], dtype=object)
testLookup = np.array(['A','B','ELSE','NULL'])

arr = testData.copy()
nulls = np.array([x != x for x in arr])
arr[nulls] = 'NULL'
arr[~np.in1d(arr, testLookup[:2]) & ~nulls] = 'ELSE'  # or use np.isin

res = np.searchsorted(testLookup, arr)

# array([0, 1, 2, 3, 2], dtype=int64)

相关问题 更多 >