I have the following dataframe:
import polars as pl
import numpy as np
df = pl.DataFrame({
"nrs": [1, 2, 3, None, 5],
"names_A0": ["foo", "ham", "spam", "egg", None],
"random_A0": np.random.rand(5),
"A_A2": [True, True, False, False, False],
})
digit = 0
For each column X whose name ends with the string suf =f'_A{digit}', I want to add an identical column to df, whose name is the same as X, but without suf.
In the example, I need to add columns names and random to the original dataframe df, whose content is identical to that of columns names_A0 and random_A0 respectively.
You can you Polars Selectors along with some basic strings operations to accomplish this. Depending on what you how you expect this problem to evolve, you can jump straight to regular expressions, or use polars.selectors.ends_with/string.removesuffix
String Suffix Operations
This approach uses
translating to
Regular Expressions
Alternatively you can use regular expressions to detect a range of suffix patterns
We will need to ensure our pattern ends with a
'$'to anchor the pattern to the end of the string.