我有一个dataframe列,其中所有值都在列表格式下(每个列值一个列表,包含一个或多个项目)。
我想删除在这些列表中找到特定字符串的行(列值可以是5项列表,如果其中一项与特定字符串匹配,则必须删除该行)
for row in df:
for count, item in enumerate(df["prescript"]):
for element in item:
if "complementary" in element:
df.drop(row)
df("prescript"是我要迭代的列
"互补">:如果在列值中找到该词,则必须删除该行
我如何改进上面的代码使其工作?
谢谢所有的
不切实际的解决方案,可能会引发一些新的学习:
df = pd.DataFrame(
columns=" index drug prescript ".split(),
data= [
[ 0, 1, ['a', 's', 'd', 'f'], ],
[ 1, 2, ['e', 'a', 'e', 'f'], ],
[ 2, 3, ['e', 'a'], ],
[ 3, 4, ['a', 'complementary'], ],]).set_index("index", drop=True)
df.loc[
df['prescript'].explode().replace({'complementary': np.nan}).groupby(level=0).agg(lambda x: ~pd.isnull(x).any())
]
首先使用Series.apply
屏蔽包含单词的行
word = "complementary"
word_is_in = df["prescript"].apply(lambda list_item: word in list_item)
然后使用布尔索引通过反转布尔序列word_is_in
df = df[~word_is_in]