r"""Substitute the variable parameters into the expression. This function performs the parameter substitution when applying features to a dataframe. It is a mechanism for the user to override the default values in any given expression when defining a feature, instead of having t
(v, expr)
| 295 | # |
| 296 | |
| 297 | def vsub(v, expr): |
| 298 | r"""Substitute the variable parameters into the expression. |
| 299 | |
| 300 | This function performs the parameter substitution when |
| 301 | applying features to a dataframe. It is a mechanism for |
| 302 | the user to override the default values in any given |
| 303 | expression when defining a feature, instead of having |
| 304 | to programmatically call a function with new values. |
| 305 | |
| 306 | Parameters |
| 307 | ---------- |
| 308 | v : str |
| 309 | Variable name. |
| 310 | expr : str |
| 311 | The expression for substitution. |
| 312 | |
| 313 | Returns |
| 314 | ------- |
| 315 | newexpr |
| 316 | The expression with the new, substituted values. |
| 317 | |
| 318 | """ |
| 319 | # numbers pattern |
| 320 | npat = '[-+]?[0-9]*\.?[0-9]+' |
| 321 | nreg = re.compile(npat) |
| 322 | # find all number locations in variable name |
| 323 | vnums = nreg.findall(v) |
| 324 | viter = nreg.finditer(v) |
| 325 | vlocs = [] |
| 326 | for match in viter: |
| 327 | vlocs.append(match.span()) |
| 328 | # find all number locations in expression |
| 329 | # find all non-number locations as well |
| 330 | elen = len(expr) |
| 331 | enums = nreg.findall(expr) |
| 332 | eiter = nreg.finditer(expr) |
| 333 | elocs = [] |
| 334 | enlocs = [] |
| 335 | index = 0 |
| 336 | for match in eiter: |
| 337 | eloc = match.span() |
| 338 | elocs.append(eloc) |
| 339 | enlocs.append((index, eloc[0])) |
| 340 | index = eloc[1] |
| 341 | # build new expression |
| 342 | newexpr = str() |
| 343 | for i, enloc in enumerate(enlocs): |
| 344 | if i < len(vlocs): |
| 345 | newexpr += expr[enloc[0]:enloc[1]] + v[vlocs[i][0]:vlocs[i][1]] |
| 346 | else: |
| 347 | newexpr += expr[enloc[0]:enloc[1]] + expr[elocs[i][0]:elocs[i][1]] |
| 348 | if elocs: |
| 349 | estart = elocs[len(elocs)-1][1] |
| 350 | else: |
| 351 | estart = 0 |
| 352 | newexpr += expr[estart:elen] |
| 353 | return newexpr |
| 354 |