Miscellaneous¶
Serializable ¶
Source code in src\survey_kit\serializable.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 | |
load
classmethod
¶
load(
path: str = "",
delete: bool = False,
delete_only: bool = False,
init_kwargs: dict | None = None,
**df_kwargs,
) -> Serializable | None
Load a serializable object from disk
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path of object. Can exclude the suffix. |
''
|
delete
|
bool
|
Delete after load? The default is False. |
False
|
delete_only
|
bool
|
Don't load, just delete. The default is False. |
False
|
init_kwargs
|
dict
|
Arguments to pass to init function |
None
|
df_kwargs
|
dict
|
Arguments to pass to narwhals scan_parquet for dataframe loading |
{}
|
Returns:
| Type | Description |
|---|---|
Serializable
|
|
Source code in src\survey_kit\serializable.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
load_any
classmethod
¶
Pass the root path of a serializable object and this will figure out what it is (from the suffix) and call that object's loader function.
For cases where multiple objects work, and I don't want to
have to do if/else logic by suffix
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path of object. Can exclude the suffix. |
''
|
delete
|
bool
|
Delete after load? The default is False. |
False
|
delete_only
|
bool
|
Don't load, just delete. The default is False. |
False
|
Returns:
| Type | Description |
|---|---|
Serializable object of any type
|
|
Source code in src\survey_kit\serializable.py
save ¶
Save a serializable object to
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path of object. Can exclude the suffix. |
required |
quietly
|
bool
|
No message to console/log |
True
|
Source code in src\survey_kit\serializable.py
DataFrameList ¶
Bases: Serializable
A light wrapper around Lazy/DataFrames that can be used like a list, mostly, (append, extend, +) and also can be used like the underlying LazyFrame or DataFrame where a narwhals operation is applied to all items in the list.
Examples:
This would apply the filter to df1 and df2 and return a DataFrameList with the filtered data.
Source code in src\survey_kit\utilities\dataframe_list.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
compress_df ¶
compress_df(
df: IntoFrameT,
cols: list[str] | str | None = None,
check_string: bool = False,
check_string_only: bool = False,
cast_all_null_to_boolean: bool = True,
check_date_time: bool = True,
no_boolean: bool = False,
) -> IntoFrameT
Optimize DataFrame by downcasting numeric types to smallest possible representation.
Analyzes numeric columns and casts them to the smallest data type that can accommodate all values, reducing memory usage and file sizes. Has some optional parameters to handle figuring out the optimal compress for stata
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT
|
Input data |
required |
cols
|
list[str]
|
Specific columns to compress (default: all) |
None
|
check_string
|
bool
|
Attempt to convert string columns to numeric |
False
|
check_string_only
|
bool
|
Only check string conversions |
False
|
cast_all_null_to_boolean
|
bool
|
Cast all-null columns to boolean |
True
|
check_date_time
|
bool
|
Optimize datetime columns |
True
|
no_boolean
|
bool
|
Skip boolean type casting (and leave as int8) |
False
|
Returns:
| Type | Description |
|---|---|
IntoFrameT
|
Compressed DataFrame with optimized data types |
Examples:
Basic compression:
String to numeric conversion:
Notes
Automatically detects the smallest integer type that can hold all values in each column, considering ranges like Int8 (-128 to 127), Int16, etc.
Source code in src\survey_kit\utilities\compress.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | |
Config ¶
Global configuration for survey-kit.
Config manages package-wide settings including paths, CPU limits, memory settings, and environment variables. Settings can be configured via environment variables or by directly setting attributes on the config instance.
The config instance is typically accessed via:
Attributes:
| Name | Type | Description |
|---|---|---|
code_root |
str
|
Root directory for code files. Set via environment variable
|
data_root |
str
|
Root directory for data files. Set via environment variable
|
cpus |
int
|
Number of CPUs to use for parallel operations. Automatically sets
thread limits for Polars, OpenBLAS, MKL, etc. when changed.
Set via |
path_temp_files |
str
|
Directory for temporary files. Set via |
ram |
int
|
Total available RAM in bytes. Set via |
mem_in_gb |
int
|
Available memory in gigabytes (read-only). |
mem_in_mb |
int
|
Available memory in megabytes (read-only). |
mem_in_kb |
int
|
Available memory in kilobytes (read-only). |
Examples:
Basic configuration:
>>> from survey_kit import config
>>> config.data_root = "/projects/data/myproject"
>>> config.cpus = 16
>>> print(config.path_temp_files)
'/projects/data/myproject/temp_files'
Using environment variables:
Memory information:
>>> print(f"Available RAM: {config.mem_in_gb} GB")
>>> print(f"Available RAM: {config.mem_in_mb} MB")
Temporary files:
>>> temp_path = config.path_temp_with_random(as_parquet=True)
>>> print(temp_path)
'/projects/data/myproject/temp_files/abc123xyz.parquet'
Notes
Setting cpus automatically updates thread limits for multiple libraries:
- POLARS_MAX_THREADS
- OMP_NUM_THREADS
- NUMEXPR_NUM_THREADS
- MKL_NUM_THREADS
- OPENBLAS_NUM_THREADS
Source code in src\survey_kit\orchestration\config.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
path_temp_with_random ¶
Generate a random temporary file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_parquet
|
bool
|
Add .parquet extension. Default is False. |
False
|
underscore_prefix
|
bool
|
Prefix filename with underscore. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Full path to a uniquely-named temporary file. |
Examples:
Source code in src\survey_kit\orchestration\config.py
random ¶
RandomData ¶
Generate random data, in a slightly easier way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_rows
|
int
|
Number of rows in the data to be generated |
required |
seed
|
int
|
For replicability, set the seed. Default is 0 (which does not set the seed) |
0
|
Examples:
Create a dataframe with random variables:
>>> nRows = 10000
>>> df = (RandomData(n_rows=nRows, seed=89465551)
... .index("index")
... .integer("year", lower=2015, upper=2020)
... .float("var1", 0, 100000)
... .integer("var2", 1, 100000)
... .integer("var3", 1, 50)
... .float("var4", 0, 1)
... .date("date", date(2020, 1, 1), date(2025, 12, 31))
... .datetime("datetime", date(2020, 1, 1), date(2025, 12, 31))
... .np_distribution("v_normal", "normal", dict(loc=1, scale=2))
... .np_distribution("v_lognormal", "lognormal", dict(mean=1, sigma=2))
... .to_df()
... )
Source code in src\survey_kit\utilities\random.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | |
boolean ¶
Create an boolean column
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
column name |
required |
Returns:
| Type | Description |
|---|---|
RandomData object (so you can chain 's)
|
|
Source code in src\survey_kit\utilities\random.py
date ¶
Create a date column in [start,end]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
column name |
required |
start
|
date
|
lower bound |
required |
end
|
date
|
upper bound |
required |
Returns:
| Type | Description |
|---|---|
RandomData object (so you can chain 's)
|
|
Source code in src\survey_kit\utilities\random.py
datetime ¶
Create a datetime column in [start,end]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
column name |
required |
start
|
datetime | date
|
lower bound |
required |
end
|
datetime | date
|
upper bound |
required |
Returns:
| Type | Description |
|---|---|
RandomData object (so you can chain 's)
|
|
Source code in src\survey_kit\utilities\random.py
float ¶
Create a float64 column in (lower,upper)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
column name |
required |
lower
|
float
|
lower bound |
required |
upper
|
float
|
upper bound |
required |
Returns:
| Type | Description |
|---|---|
RandomData object (so you can chain 's)
|
|
Source code in src\survey_kit\utilities\random.py
index ¶
Create an index column (i.e. 0-n_rows-1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
column name |
required |
Returns:
| Type | Description |
|---|---|
RandomData object (so you can chain 's)
|
|
Source code in src\survey_kit\utilities\random.py
integer ¶
Create an integer column in [lower,upper]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
column name |
required |
lower
|
int
|
lower bound (inclusive) |
required |
upper
|
int
|
upper bound (inclusive) |
required |
Returns:
| Type | Description |
|---|---|
RandomData object (so you can chain 's)
|
|
Source code in src\survey_kit\utilities\random.py
np_distribution ¶
Create a column from a numpy distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Column name. |
required |
distribution
|
str
|
Name of numpy random distribution (e.g., "normal", "lognormal", "exponential"). Must be a valid method of np.random.Generator. |
required |
**kwargs
|
Keyword arguments passed to the distribution function (e.g., loc, scale for normal). |
{}
|
Returns:
| Type | Description |
|---|---|
RandomData
|
Self for method chaining. |
Raises:
| Type | Description |
|---|---|
Exception
|
If distribution is not a valid numpy random distribution. |
Examples:
>>> df = (RandomData(n_rows=1000, seed=123)
... .np_distribution("normal_var", "normal", loc=0, scale=1)
... .np_distribution("lognormal_var", "lognormal", mean=1, sigma=2)
... .np_distribution("exponential_var", "exponential", scale=1.5)
... .to_df())
Source code in src\survey_kit\utilities\random.py
to_df ¶
Convert accumulated random data to a Polars DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compress
|
bool
|
Apply compression to reduce memory usage by downcasting numeric types. Default is True. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing all generated columns. |
Examples:
>>> df = (RandomData(n_rows=1000, seed=123)
... .integer("id", 1, 1000)
... .float("value", 0, 100)
... .to_df())
>>> print(df)
>>> # Without compression
>>> df_uncompressed = (RandomData(n_rows=1000, seed=123)
... .integer("id", 1, 1000)
... .to_df(compress=False))
Source code in src\survey_kit\utilities\random.py
RandomNumberGenerator ¶
Create a new numpy random number generator with random seed.
Returns:
| Type | Description |
|---|---|
Generator
|
Numpy random number generator initialized with a random seed from Python's random module. |
Examples:
>>> from survey_kit.utilities.random import RandomNumberGenerator
>>> rng = RandomNumberGenerator()
>>> random_values = rng.normal(loc=0, scale=1, size=100)
Source code in src\survey_kit\utilities\random.py
generate_seed ¶
Generate a random seed value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
power_of_2_limit
|
int
|
Upper bound is 2^power_of_2_limit. Default is 32. |
32
|
Returns:
| Type | Description |
|---|---|
int
|
Random integer between 1 and 2^power_of_2_limit - 1. |
Examples:
>>> from survey_kit.utilities.random import generate_seed, set_seed
>>> seed = generate_seed()
>>> set_seed(seed) # Use for reproducibility
Source code in src\survey_kit\utilities\random.py
get_random_state ¶
Get the current state of the random number generator.
Returns:
| Type | Description |
|---|---|
tuple
|
Internal state of Python's random module. |
Examples:
>>> from survey_kit.utilities.random import get_random_state, set_random_state
>>> state = get_random_state()
>>> # ... do some random operations ...
>>> set_random_state(state) # Restore to previous state
Source code in src\survey_kit\utilities\random.py
set_random_state ¶
Set the random number generator to a specific state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
tuple
|
State tuple from get_random_state(). |
required |
Examples:
>>> state = get_random_state()
>>> # ... do some random operations ...
>>> set_random_state(state) # Restore to previous state
Source code in src\survey_kit\utilities\random.py
set_seed ¶
Set the random seed for reproducibility.
Sets the seed for Python's random module, which is used by the random number generator in this module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. If 0 or less, does not set seed. Default is 0. |
0
|
Examples:
>>> from survey_kit.utilities.random import set_seed, generate_seed
>>> set_seed(12345)
>>> seed1 = generate_seed()
>>> set_seed(12345)
>>> seed2 = generate_seed()
>>> assert seed1 == seed2 # Same seed produces same sequence
Source code in src\survey_kit\utilities\random.py
FormulaBuilder ¶
Build and manipulate R-style formulas for statistical models.
FormulaBuilder provides a programmatic way to construct complex model formulas using R/Patsy-style syntax. It supports formula manipulation, variable expansion, interactions, transformations, and pattern matching against dataframes.
The class works with Formulaic to parse and expand formulas, and integrates with the dataframe utilities to resolve wildcards and column patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Reference dataframe for resolving column names and wildcards. Default is None. |
None
|
formula
|
str
|
Initial formula string. If empty, constructs from lhs and constant. Default is "". |
''
|
lhs
|
str
|
Left-hand side of formula (response variable). Default is "". |
''
|
constant
|
bool
|
Include intercept term (1) or suppress it (0). Default is True. |
True
|
Attributes:
| Name | Type | Description |
|---|---|---|
formula |
str
|
Current formula string. |
df |
IntoFrameT | None
|
Reference dataframe. |
columns |
list[str]
|
All variables required by the formula. |
columns_rhs |
list[str]
|
Variables in right-hand side of formula. |
columns_lhs |
list[str]
|
Variables in left-hand side of formula. |
Examples:
Basic formula construction:
>>> from survey_kit.utilities.formula import FormulaBuilder
>>>
>>> fb = FormulaBuilder(df=df, lhs="income", constant=True)
>>> fb += "age + education"
>>> print(fb.formula)
'income~1+age+education'
Add variables using wildcards:
>>> fb = FormulaBuilder(df=df, lhs="income")
>>> fb.continuous(columns="demographic_*")
>>> fb.factor(columns="region")
>>> print(fb.formula)
Polynomial terms:
>>> fb = FormulaBuilder(df=df, lhs="income")
>>> fb.polynomial(columns="age", degree=3)
>>> print(fb.formula)
'income~1+poly(age,degree=3,raw=True)'
Interactions:
>>> fb = FormulaBuilder(df=df, lhs="income")
>>> fb.simple_interaction(columns=["age", "education"], order=2)
>>> print(fb.formula)
'income~1+(age+education)**2'
Standardization:
>>> fb = FormulaBuilder(df=df, lhs="income")
>>> fb.scale(columns=["age", "experience"])
>>> print(fb.formula)
'income~1+scale(age)+scale(experience)'
Working with existing formula strings:
>>> formula = "income~age+education+age:education"
>>> fb = FormulaBuilder(df=df, formula=formula)
>>> fb.expand() # Expand shorthand
>>> print(fb.rhs()) # Get right-hand side
'age+education+age:education'
>>> print(fb.columns)
['income', 'age', 'education']
Notes
Formula syntax follows R/Patsy conventions:
- ~ separates left and right sides
- + adds terms
- : creates interactions
- * creates main effects and interactions: a*b = a+b+a:b
- **n creates all n-way interactions
- I() for arithmetic operations
- C() for categorical variables
- Functions like scale(), center(), poly() for transformations
Wildcards in column specifications:
- "income_*" matches all columns starting with "income_"
- ["age", "education_*"] matches age and all education columns
The FormulaBuilder can be used in two modes: 1. Object mode: Create instance and chain methods 2. Static mode: Call methods with self=None for one-off operations
See Also
formulaic.Formula : Underlying formula parser
Source code in src\survey_kit\utilities\formula_builder.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 | |
add_to_formula ¶
Append a string to the formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
add_part
|
str
|
String to append. Default is "". |
''
|
plus_first
|
bool
|
Add "+" before the string. Default is True. |
True
|
Source code in src\survey_kit\utilities\formula_builder.py
any_wrapper ¶
any_wrapper(
df: IntoFrameT | None = None,
columns: str | list | None = None,
clause: str = "",
case_insensitive: bool = False,
prefix: str = "",
suffix: str = "",
) -> str | FormulaBuilder
General wrapper for adding columns with prefix/suffix.
Used internally by other methods to add variables with transformations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for resolving column patterns. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns. Default is None. |
None
|
clause
|
str
|
Pre-constructed clause (bypasses column lookup). Default is "". |
''
|
case_insensitive
|
bool
|
Case-insensitive column matching. Default is False. |
False
|
prefix
|
str
|
String to prepend to each column. Default is "". |
''
|
suffix
|
str
|
String to append to each column. Default is "". |
''
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string if self is None, otherwise returns self for chaining. |
Source code in src\survey_kit\utilities\formula_builder.py
center ¶
center(
df: IntoFrameT | None = None,
columns: str | list | None = None,
clause: str = "",
case_insensitive: bool = False,
) -> str | FormulaBuilder
Center variables (subtract mean).
Convenience method for scale(standardize=False).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for column lookup. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns. Default is None. |
None
|
clause
|
str
|
Pre-constructed clause. Default is "". |
''
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |
Source code in src\survey_kit\utilities\formula_builder.py
columns_from_formula ¶
Extract variable names from a formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str
|
Formula string. If empty, uses self.formula. Default is "". |
''
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Variable names required by the formula. |
Source code in src\survey_kit\utilities\formula_builder.py
continuous ¶
continuous(
df: IntoFrameT | None = None,
columns: str | list | None = None,
clause: str = "",
case_insensitive: bool = False,
) -> str | FormulaBuilder
Add continuous variables to the formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for column lookup. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns (e.g., "income_*"). Default is None. |
None
|
clause
|
str
|
Pre-constructed clause. Default is "". |
''
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |
Examples:
>>> fb = FormulaBuilder(df=df, lhs="y")
>>> fb.continuous(columns=["age", "income"])
>>> print(fb.formula)
'y~1+age+income'
Source code in src\survey_kit\utilities\formula_builder.py
exclude_interactions ¶
exclude_interactions(
formula: str = "",
b_exclude_powers: bool = True,
df: IntoFrameT | None = None,
) -> tuple[str, bool]
Remove interaction terms from formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str
|
Formula string. If empty, uses self.formula. Default is "". |
''
|
b_exclude_powers
|
bool
|
Also exclude polynomial terms. Default is True. |
True
|
df
|
IntoFrameT | None
|
Reference dataframe. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, bool]
|
(modified formula, whether any terms were dropped) |
Source code in src\survey_kit\utilities\formula_builder.py
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 | |
exclude_variables ¶
exclude_variables(
exclude_list: list = None,
formula: str = "",
df: IntoFrameT | None = None,
case_insensitive: bool = False,
)
Remove specific variables from formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude_list
|
list
|
Variables to exclude. Default is None. |
None
|
formula
|
str
|
Formula string. If empty, uses self.formula. Default is "". |
''
|
df
|
IntoFrameT | None
|
Reference dataframe. Default is None. |
None
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Modified formula string or self for chaining. |
Source code in src\survey_kit\utilities\formula_builder.py
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 | |
expand ¶
Expand formula shorthand (e.g., a*b becomes a+b+a:b).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str
|
Formula string. If empty, uses self.formula. Default is "". |
''
|
Returns:
| Type | Description |
|---|---|
str
|
Expanded formula string. |
Source code in src\survey_kit\utilities\formula_builder.py
factor ¶
factor(
df: IntoFrameT | None = None,
columns: str | list | None = None,
clause: str = "",
reference=None,
case_insensitive: bool = False,
)
Add categorical variables with treatment coding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for column lookup. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns. Default is None. |
None
|
clause
|
str
|
Pre-constructed clause. Default is "". |
''
|
reference
|
str | int | None
|
Reference level for treatment coding. Default is None (use first level). |
None
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |
Examples:
>>> fb.factor(columns="education", reference="high_school")
>>> print(fb.formula)
"y~1+C(education, contr.treatment('high_school'))"
Source code in src\survey_kit\utilities\formula_builder.py
formula_with_varnames_in_brackets ¶
formula_with_varnames_in_brackets(
clause: str = "",
df: LazyFrame | DataFrame | None = None,
case_insensitive: bool = False,
append: bool = False,
) -> str | FormulaBuilder
Expand {pattern} placeholders with matching column names.
Replaces {var} with all columns matching var pattern in the dataframe. Useful for programmatically building formulas with wildcards.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clause
|
str
|
Formula clause with {pattern} placeholders. Default is "". |
''
|
df
|
LazyFrame | DataFrame | None
|
Dataframe for column lookup. Default is None. |
None
|
case_insensitive
|
bool
|
Case-insensitive pattern matching. Default is False. |
False
|
append
|
bool
|
Append to existing formula instead of replacing. Only used when called on instance. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Expanded formula string or self for chaining. |
Examples:
>>> fb = FormulaBuilder(df=df)
>>> fb.formula_with_varnames_in_brackets("{income_*} + age")
>>> print(fb.formula)
'y~1+income_wages+income_self_employment+age'
Source code in src\survey_kit\utilities\formula_builder.py
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 | |
function ¶
function(
df: IntoFrameT | None = None,
columns: str | list | None = None,
clause: str = "",
operator_before: str = "",
operator_after: str = "",
function_item: str = "",
case_insensitive: bool = False,
**kwargs,
) -> str | FormulaBuilder
Wrap columns in a function call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for column lookup. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns. Default is None. |
None
|
clause
|
str
|
Pre-constructed clause. Default is "". |
''
|
operator_before
|
str
|
String before function call. Default is "". |
''
|
operator_after
|
str
|
String after function call. Default is "". |
''
|
function_item
|
str
|
Function name (e.g., "log", "sqrt"). Default is "". |
''
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
**kwargs
|
Additional function arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |
Examples:
Source code in src\survey_kit\utilities\formula_builder.py
has_constant ¶
Check if formula includes an intercept.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str
|
Formula string. If empty, uses self.formula. Default is "". |
''
|
true_if_missing
|
bool
|
Return True if constant term is implicit (not specified). Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
True if formula includes intercept. |
Source code in src\survey_kit\utilities\formula_builder.py
interact_clauses ¶
interact_clauses(
clause1: str = "",
clause2: str = "",
no_base: bool = False,
) -> str | FormulaBuilder
Create interactions between two formula clauses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clause1
|
str
|
First formula clause. Default is "". |
''
|
clause2
|
str
|
Second formula clause. Default is "". |
''
|
no_base
|
bool
|
Exclude main effects from clauses. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |
Examples:
>>> fb.interact_clauses("age+education", "region")
>>> print(fb.formula)
'y~1+(age+education)*(region)'
Source code in src\survey_kit\utilities\formula_builder.py
lhs ¶
Get left-hand side of formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str
|
Formula string. If empty, uses self.formula. Default is "". |
''
|
Returns:
| Type | Description |
|---|---|
str
|
Left-hand side (response variable). |
Source code in src\survey_kit\utilities\formula_builder.py
polynomial ¶
polynomial(
df: IntoFrameT | None = None,
columns: str | list | None = None,
clause: str = "",
degree: int = 0,
case_insensitive: bool = False,
center: bool = False,
) -> str | FormulaBuilder
Add polynomial terms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for column lookup. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns. Default is None. |
None
|
clause
|
str
|
Pre-constructed clause. Default is "". |
''
|
degree
|
int
|
Polynomial degree. Default is 0 (returns continuous). |
0
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
center
|
bool
|
Use orthogonal polynomials (centered). Default is False (raw polynomials). |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |
Examples:
>>> fb.polynomial(columns="age", degree=2, center=True)
>>> print(fb.formula)
'y~1+poly(age,degree=2,raw=False)'
Source code in src\survey_kit\utilities\formula_builder.py
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 | |
remove_constant ¶
Remove intercept from formula (change ~1+ to ~0+).
Source code in src\survey_kit\utilities\formula_builder.py
rhs ¶
Get right-hand side of formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str
|
Formula string. If empty, uses self.formula. Default is "". |
''
|
Returns:
| Type | Description |
|---|---|
str
|
Right-hand side (predictors). |
Source code in src\survey_kit\utilities\formula_builder.py
scale ¶
scale(
df: IntoFrameT | None = None,
columns: str | list | None = None,
clause: str = "",
standardize: bool = True,
case_insensitive: bool = False,
) -> str | FormulaBuilder
Standardize or center variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for column lookup. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns. Default is None. |
None
|
clause
|
str
|
Pre-constructed clause. Default is "". |
''
|
standardize
|
bool
|
If True, standardize (mean=0, sd=1). If False, only center (mean=0). Default is True. |
True
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |
Examples:
>>> fb.scale(columns="age") # Standardize
>>> fb.scale(columns="income", standardize=False) # Center only
Source code in src\survey_kit\utilities\formula_builder.py
simple_interaction ¶
simple_interaction(
df: IntoFrameT | None = None,
columns: str | list | None = None,
order: int = 2,
case_insensitive: bool = False,
sub_function: Callable | None = None,
no_base: bool = False,
) -> str | FormulaBuilder
Create interactions between variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for column lookup. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns. Default is None. |
None
|
order
|
int
|
Interaction order. 2 = pairwise, 3 = three-way, etc. Default is 2. |
2
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
sub_function
|
Callable | None
|
Function to apply to columns before interacting. Default is None. |
None
|
no_base
|
bool
|
Exclude main effects (only interactions). Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |
Examples:
>>> fb.simple_interaction(columns=["age", "education"], order=2)
>>> print(fb.formula)
'y~1+(age+education)**2'
>>> fb.simple_interaction(columns=["a", "b", "c"], order=2, no_base=True)
>>> print(fb.formula)
'y~1+(a+b+c)**2-(a+b+c)' # Interactions only
Source code in src\survey_kit\utilities\formula_builder.py
standardize ¶
standardize(
df: IntoFrameT | None = None,
columns: str | list | None = None,
clause: str = "",
case_insensitive: bool = False,
) -> str | FormulaBuilder
Standardize variables (mean=0, sd=1).
Convenience method for scale(standardize=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
IntoFrameT | None
|
Dataframe for column lookup. Default is None. |
None
|
columns
|
str | list | None
|
Column names or patterns. Default is None. |
None
|
clause
|
str
|
Pre-constructed clause. Default is "". |
''
|
case_insensitive
|
bool
|
Case-insensitive matching. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
str | FormulaBuilder
|
Formula string or self for chaining. |