确定 pandas 序列的元素是否包含不同序列的元素作为子字符串
Determine whether elements of a pandas sequence contain elements of a different sequence as substrings
鉴于以下情况:
s1 = pd.Series(["onee", "twoo", "threee", "fourr"])
s2 = pd.Series(["one", "two"])
如何找到 s3
作为 [True, True, False, False]
。
对于 s1
中的每个元素,如果 s2
中的元素是
substring s3
对应的元素应该是 True
.
注意 - 列表大小可能会有所不同,因此解决方案取决于是否存在
s2
中设置的元素数量不可行。
我有以下方案,我认为可行,但我认为这不是一个很好的解决方案
s1 = pd.Series(["onee", "twoo", "threee", "fourr"])
s2 = pd.Series(["one", "two"])
res = []
for s_2 in s2:
for s_1 in s1:
if s_2 in s_1:
res.append(1)
else:
res.append(0)
solution = np.array(res).reshape((2, len(s1))).sum(axis=0)
这导致
array([1, 1, 0, 0])
使用
s1.str.contains('|'.join(s2.str.replace('|', ''))).astype(int).values
输出
array([1, 1, 0, 0])
鉴于以下情况:
s1 = pd.Series(["onee", "twoo", "threee", "fourr"])
s2 = pd.Series(["one", "two"])
如何找到 s3
作为 [True, True, False, False]
。
对于 s1
中的每个元素,如果 s2
中的元素是
substring s3
对应的元素应该是 True
.
注意 - 列表大小可能会有所不同,因此解决方案取决于是否存在
s2
中设置的元素数量不可行。
我有以下方案,我认为可行,但我认为这不是一个很好的解决方案
s1 = pd.Series(["onee", "twoo", "threee", "fourr"])
s2 = pd.Series(["one", "two"])
res = []
for s_2 in s2:
for s_1 in s1:
if s_2 in s_1:
res.append(1)
else:
res.append(0)
solution = np.array(res).reshape((2, len(s1))).sum(axis=0)
这导致
array([1, 1, 0, 0])
使用
s1.str.contains('|'.join(s2.str.replace('|', ''))).astype(int).values
输出
array([1, 1, 0, 0])