如何用Python筛选DataFrame:保留label列字符串存在于sentence列的行
在Python中筛选DataFrame:保留label是sentence子串的行
需求说明
从含空值的DataFrame中筛选出满足同一行内labels列字符串是sentence列字符串子串的行,自动排除空值无效行。
输入DataFrame
| sentence | labels |
|---|---|
| A met B | A |
| C is dead | X |
| D | |
| D went to London and Berlin | London 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)
输出结果
| sentence | label |
|---|---|
| A met B | A |
| D went to London and Berlin | London and Berlin |
代码说明
- 空值过滤:通过条件判断排除
sentence或labels为空的行,避免空字符串干扰子串判断。 - 子串校验:用
apply按行检查labels是否包含在sentence中,axis=1指定按行处理。 - 列名调整:将原列名
labels改为label,匹配输出示例格式,可按需省略此步骤。
内容的提问来源于stack exchange,提问作者user7665853
相关产品推荐
相关产品推荐

