-2

数据框

我有这个数据框,其中包含用户 ID 和与用户相关的标签。什么是仅过滤掉具有包含此列表中任何一个标签的行的最佳方法。data_science = ['python', 'r', 'matlab', 'sas', 'excel', 'sql'] 我在 pandas 中尝试过以下代码,它确实在一定程度上过滤掉了,但它给出的标签有任何类似于列表的标签。例如,对于 sql,它会抛出 sql-server。你能建议一个更好的方法吗?

df_ds = df_combo[df_combo["Tag"].astype(str).str.contains('(python|excel|sql|matlab)', regex=True)]
4

1 回答 1

0

我认为一种可能更简单的方法,但可能是冗长的:

# create a set with the queried tags
tags = {'python', 'r', 'matlab', 'sas', 'excel', 'sql'}
# create an auxiliary column where all the tags are separated elements of a set 
df_combo['Tag-set'] = df_combo['Tag'].str.split(',').apply(lambda x: [e.strip() for e in x]).tolist() 
# use sets to check the intersection
df_combo['Tag-set'] = df_combo['Tag-set'].apply(set)
# filter the list
df_fd = df_combo[df_combo['Tag-set'].apply(lambda x: len(x & tags) > 0)]

这个想法是使用splitand清理所有字符串strip,然后只保留交叉点至少包含一个元素的字符串。

于 2020-11-13T03:04:54.783 回答