我有一个字符串列 ('b'),我想获取与同一列中的子字符串类似的字符串。例如,在下面的数据框列 'b' 中,world 是 helloworld 的子串,ness 是 greatness 的子串。我想在列表中获取字符串 world 和 ness。您能否提出一个解决方案。
a b
0 test world
1 teat helloworld
2 gor bye
3 jhr greatness
4 fre ness
列表中的期望输出
listofsubstrings
Out[353]: ['world', 'ness']
请您参考如下方法:
您可以使用:
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']
交叉连接的替代解决方案:
b = df.b.unique()
df['tmp'] = 1
df1 = pd.merge(df[['b','tmp']],df[['b','tmp']], on='tmp')
df1 = df1[df1.apply(lambda x: x.b_x in x.b_y, axis=1) & (df1.b_x != df1.b_y)]
print (df1)
b_x tmp b_y
1 world 1 helloworld
23 ness 1 greatness
print (df1.b_x.tolist())
['world', 'ness']
