Polars with Regex :
import polars as pl
df = pl.DataFrame({
'ID': [1, 1, 1, 2, 2, 2, 2, 2],
'QuestionCode': ['Q01', 'Q01-1', 'Q02', 'Q01', 'Q02', 'Q02-1', 'Q02-1-1', 'Q02-2']
})
df= df.with_columns(
pl.col('QuestionCode').str.replace(r'-[^-]+$','').alias('BaseCode')
)
print(df)
'''
┌─────┬──────────────┬──────────┐
│ ID ┆ QuestionCode ┆ BaseCode │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞═════╪══════════════╪══════════╡
│ 1 ┆ Q01 ┆ Q01 │
│ 1 ┆ Q01-1 ┆ Q01 │
│ 1 ┆ Q02 ┆ Q02 │
│ 2 ┆ Q01 ┆ Q01 │
│ 2 ┆ Q02 ┆ Q02 │
│ 2 ┆ Q02-1 ┆ Q02 │
│ 2 ┆ Q02-1-1 ┆ Q02-1 │
│ 2 ┆ Q02-2 ┆ Q02 │
└─────┴──────────────┴──────────┘
'''
df = df.join(df.filter(pl.col('BaseCode') != pl.col('QuestionCode')).unique(),
left_on = ['ID','QuestionCode'], right_on = ['ID','BaseCode'],
how = 'anti'
)
'''
shape: (5, 3)
┌─────┬──────────────┬──────────┐
│ ID ┆ QuestionCode ┆ BaseCode │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞═════╪══════════════╪══════════╡
│ 1 ┆ Q01-1 ┆ Q01 │
│ 1 ┆ Q02 ┆ Q02 │
│ 2 ┆ Q01 ┆ Q01 │
│ 2 ┆ Q02-1-1 ┆ Q02-1 │
│ 2 ┆ Q02-2 ┆ Q02 │
└─────┴──────────────┴──────────┘
'''
df = df.drop('BaseCode')
print(df)
'''
shape: (5, 2)
┌─────┬──────────────┐
│ ID ┆ QuestionCode │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪══════════════╡
│ 1 ┆ Q01-1 │
│ 1 ┆ Q02 │
│ 2 ┆ Q01 │
│ 2 ┆ Q02-1-1 │
│ 2 ┆ Q02-2 │
└─────┴──────────────┘
'''