You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python筛选DataFrame:保留label列字符串存在于sentence列的行

在Python中筛选DataFrame:保留label是sentence子串的行

需求说明

从含空值的DataFrame中筛选出满足同一行内labels列字符串是sentence列字符串子串的行,自动排除空值无效行。

输入DataFrame

sentencelabels
A met BA
C is deadX
D
D went to London and BerlinLondon and Berlin
E is sleeping

实现代码

import pandas as pd

# 构造输入DataFrame
data = {
    'sentence': ['A met B', 'C is dead', '', 'D went to London and Berlin', 'E is sleeping'],
    'labels': ['A', 'X', 'D', 'London and Berlin', '']
}
df = pd.DataFrame(data)

# 筛选逻辑:先排除空值行,再判断子串关系
filtered_df = df[(df['sentence'].notna() & df['sentence'] != '') & (df['labels'].notna() & df['labels'] != '')]
filtered_df = filtered_df[filtered_df.apply(lambda row: row['labels'] in row['sentence'], axis=1)]

# 匹配输出示例的列名
filtered_df.rename(columns={'labels': 'label'}, inplace=True)

print(filtered_df)

输出结果

sentencelabel
A met BA
D went to London and BerlinLondon and Berlin

代码说明

  1. 空值过滤:通过条件判断排除sentence或labels为空的行,避免空字符串干扰子串判断。
  2. 子串校验:用apply按行检查labels是否包含在sentence中,axis=1指定按行处理。
  3. 列名调整:将原列名labels改为label,匹配输出示例格式,可按需省略此步骤。

内容的提问来源于stack exchange,提问作者user7665853

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 05:00:12