Python Pandas在同一列中找到元素(子字符串)

2024-09-27 00:21:16 发布

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

我有一个字符串列('b'),希望得到在同一列中类似于子字符串的字符串。例如,在下面的dataframe列'b'中,world是helloworld的子串,ness是greatess的子串。我想把弦乐世界和尼斯列在一张单子里。你能提出一个解决办法吗。在

     a           b
0  test       world
1  teat  helloworld
2   gor         bye
3   jhr   greatness
4   fre        ness

列表中所需的输出

^{pr2}$

Tags: 字符串testdataframeworld世界helloworld单子bye
3条回答

如果行索引是列标题的子字符串,我们可以创建一个真值数组。在

l = df.b.dropna().values  # grab values from b
# double comprehension
a = np.array([[j in i for i in l] for j in l])
# of course strings are sub-strings of themselves
# lets ignore them by making the diagonal `False`
np.fill_diagonal(a, False)

# find the indices where the array is `True`
i, j = np.where(a)

l[i].tolist()

['world', 'ness']

我觉得更好

^{pr2}$

您可以使用:

from itertools import product

#get unique values only
b = df.b.unique()
#create all combination
df1 = pd.DataFrame(list(product(b, b)), columns=['a', 'b'])
#filtering
df1 = df1[df1.apply(lambda x: x.a in x.b, axis=1) & (df1.a != df1.b)]
print (df1)
        a           b
1   world  helloworld
23   ness   greatness

print (df1.a.tolist())
['world', 'ness']

交叉连接的替代解决方案:

^{pr2}$

这可能对您有用:

df_cross = pd.DataFrame(data=np.asarray(df.b) + " " + df.b[:,None], columns=df.b)
df_indicator = df_cross.applymap(lambda x: x.split()[0] in x.split()[1])
df_indicator.sum(axis=0)[lambda x: x>1].index

Out[231]: Index([u'world', u'ness'], dtype='object')

相关问题 更多 >

    热门问题