Aim*_*mee 2 python combinations matching pandas
我有一个单词列表,如果声明,我想做,下面是我的列表:
list = ['camera','display','price','memory'(will have 200+ words in the list)]
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
def check_it(sentences):
if 'camera' in sentences and 'display' in sentences and 'price' in sentences:
return "Camera/Display/Price"
if 'camera' in sentences and 'display' in sentences:
return "Camera/Display"
...
return "Others"
h.loc[:, 'Category'] = h.Mention.apply(check_it)
Run Code Online (Sandbox Code Playgroud)
对于这些组合将有太多组合,并且我希望单独返回行.有谁知道如何制作这个样本并单独返回单词而不是做'相机/显示/价格'?
str.findall正则表达式使用- 将所有列表值加入|,最后一个str.join值由/:
df = pd.DataFrame({'Mention':['camera in sentences and display in sentences',
'camera in sentences price']})
L = ['camera','display','price','memory']
pat = '|'.join(r"\b{}\b".format(x) for x in L)
df['Category'] = df['Mention'].str.findall(pat).str.join('/')
print (df)
Mention Category
0 camera in sentences and display in sentences camera/display
1 camera in sentences price camera/price
Run Code Online (Sandbox Code Playgroud)
列表理解的另一个解决方案,也用于列表使用生成器join:
df['Category1'] = [[y for y in x.split() if y in L] for x in df['Mention']]
df['Category2'] = ['/'.join(y for y in x.split() if y in L) for x in df['Mention']]
print (df)
Mention Category1 \
0 camera in sentences and display in sentences [camera, display]
1 camera in sentences price [camera, price]
Category2
0 camera/display
1 camera/price
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |