长度> 1的数组系列的比较和索引

问题描述 投票:0回答:2

标题听起来比事实更复杂。给定数据

data = [
    np.array(['x'], dtype='object'),
    np.array(['y'], dtype='object'),
    np.array(['z'], dtype='object'),
    np.array(['x', 'z', 'y'], dtype='object'),
    np.array(['y', 'x'], dtype='object'),
]    

s = pd.Series(data)

我想检索

s
的元素,其中
s == np.array(['x'])
。显而易见的方法

c = np.array(['x'])
s[s==c]

不起作用,因为比较中存在 ValueError,抱怨“'长度必须匹配才能比较',(5,), (1,)”。我也试过了

s[s=='x']

仅当

s
的元素本身都只有一个元素时才有效。

有没有办法检索

s
的所有元素,其中
s == c
无需将元素转换为字符串?

arrays pandas indexing comparison series
2个回答
1
投票
使用列表理解

numpy.array_equal

:

c = np.array(['x']) out = s[[np.array_equal(a, c) for a in s]]
如果您需要重复执行此操作(对于较短的语法),可以使用 

partial

 函数替代:

from functools import partial eq_c = partial(np.array_equal, c) out = s[map(eq_c, s)]
输出:

0 [x] dtype: object
    

0
投票
如果我们使用循环,我认为这是一种更简单的方法。

out = s[s.apply(lambda x: x.tolist() == ['x'])]
输出:

0 [x] dtype: object


检查示例

import pandas as pd import numpy as np data1 = [ np.array(['x'], dtype='object'), np.array(['y'], dtype='object'), np.array(['z'], dtype='object'), np.array(['x', 'z', 'y'], dtype='object'), np.array(['y', 'x'], dtype='object'), ] * 1000000 s1 = pd.Series(data)
    
© www.soinside.com 2019 - 2024. All rights reserved.