analog_daddy.plutils
¶
A collection of polars dataframe level helpers.
These helpers could probably be snippets in a docs page. But they have earned their place here due to their utility across different domains. Most of these are slight modifications of snippets scavenged across the internet (primarily Stackoverflow, Discord and Github) and I have attempted to credit the original sources wherever possible.
Examples are provided to illustrate their composability.
Examples:
>>> (
... df := pl.DataFrame(
... {
... "x": [1, None, 3],
... "e": [None, None, None],
... "d": [None, None, None],
... "y": [4.0, None, 6.0],
... }
... )
... )
shape: (3, 4)
┌──────┬──────┬──────┬──────┐
│ x ┆ e ┆ d ┆ y │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ null ┆ null ┆ f64 │
╞══════╪══════╪══════╪══════╡
│ 1 ┆ null ┆ null ┆ 4.0 │
│ null ┆ null ┆ null ┆ null │
│ 3 ┆ null ┆ null ┆ 6.0 │
└──────┴──────┴──────┴──────┘
>>> (
... # firstly we remove empty rows.
... df.pipe(filter_all_null)
... # then fill the delimiter column with junk to keep it.
... .with_columns(pl.lit("|").alias("d"))
... # finally drop any empty columns.
... .pipe(drop_all_null)
... )
shape: (2, 3)
┌─────┬─────┬─────┐
│ x ┆ d ┆ y │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ f64 │
╞═════╪═════╪═════╡
│ 1 ┆ | ┆ 4.0 │
│ 3 ┆ | ┆ 6.0 │
└─────┴─────┴─────┘
df_shape_diff(df_before, df_after)
¶
Compare the number of rows and columns in two DataFrames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_before
|
DataFrame
|
The DataFrame before changes. |
required |
df_after
|
DataFrame
|
The DataFrame after changes. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame with the row and column counts for each input, plus their signed differences. |
Examples:
>>> df1 = pl.from_repr(r'''shape: (2, 2)
... ┌─────┬─────┐
... │ A ┆ B │
... │ --- ┆ --- │
... │ i64 ┆ i64 │
... ╞═════╪═════╡
... │ 1 ┆ 3 │
... │ 2 ┆ 4 │
... └─────┴─────┘
... ''')
>>> df2 = pl.from_repr(r'''shape: (1, 3)
... ┌─────┬─────┬─────┐
... │ A ┆ B ┆ C │
... │ --- ┆ --- ┆ --- │
... │ i64 ┆ i64 ┆ i64 │
... ╞═════╪═════╪═════╡
... │ 1 ┆ 3 ┆ 5 │
... └─────┴─────┴─────┘
... ''')
>>> df_shape_diff(df1, df2)
shape: (2, 4)
┌─────────┬────────┬───────┬────────────────┐
│ No. of ┆ before ┆ after ┆ after - before │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞═════════╪════════╪═══════╪════════════════╡
│ Rows ┆ 2 ┆ 1 ┆ -1 │
│ Columns ┆ 2 ┆ 3 ┆ 1 │
└─────────┴────────┴───────┴────────────────┘
Source code in src/analog_daddy/plutils.py
drop_all_null(df)
¶
Drop columns where every value is null.
Notes
- Obtained from examples in drop_nulls
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame to clean up. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Clean DataFrame with all-null columns removed. |
Examples:
>>> (
... df := pl.DataFrame(
... {
... "a": [None, None, None],
... "b": [1, 2, None],
... "c": ["x", "y", ""],
... }
... )
... )
shape: (3, 3)
┌──────┬──────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ null ┆ i64 ┆ str │
╞══════╪══════╪═════╡
│ null ┆ 1 ┆ x │
│ null ┆ 2 ┆ y │
│ null ┆ null ┆ │
└──────┴──────┴─────┘
>>> drop_all_null(df)
shape: (3, 2)
┌──────┬─────┐
│ b ┆ c │
│ --- ┆ --- │
│ i64 ┆ str │
╞══════╪═════╡
│ 1 ┆ x │
│ 2 ┆ y │
│ null ┆ │
└──────┴─────┘
Source code in src/analog_daddy/plutils.py
explode_nested_params(df, keys, index_col='Point', identify_str='Parameters:')
¶
Extract inline parameter values and add them as columns to data rows.
Parameter rows are identified by identify_str in index_col
and contain comma-separated key=value pairs. Their values are
propagated to subsequent data rows until another parameter row is
encountered. The list of keys must be provided and cannot change
between rows. Use this as a building block for more nested rows with
dynamic keys.
See Also
- :func:
scan_nested_paramsfor a helper to extract the keys if they remain identical within a given dataframe.
Notes
- This is based on the excellent solution provided in the polars discord's general discussion channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with interleaved parameter/data rows. |
required |
keys
|
list[str]
|
Ordered parameter key names, e.g. from
:func: |
required |
index_col
|
str
|
Column that carries the parameter marker rows. |
"Point"
|
identify_str
|
str
|
Prefix string that identifies a parameter row. |
"Parameters:"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Data rows only, with one new column per key in |
Examples:
>>> (
... df := pl.DataFrame(
... {
... "Point": ["Parameters: ds=0, gs=1", "1", "2"],
... "Value": [None, 10, 20],
... }
... )
... )
shape: (3, 2)
┌────────────────────────┬───────┐
│ Point ┆ Value │
│ --- ┆ --- │
│ str ┆ i64 │
╞════════════════════════╪═══════╡
│ Parameters: ds=0, gs=1 ┆ null │
│ 1 ┆ 10 │
│ 2 ┆ 20 │
└────────────────────────┴───────┘
>>> explode_nested_params(df, keys=["ds", "gs"])
shape: (2, 4)
┌───────┬───────┬─────┬─────┐
│ Point ┆ Value ┆ ds ┆ gs │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ str │
╞═══════╪═══════╪═════╪═════╡
│ 1 ┆ 10 ┆ 0 ┆ 1 │
│ 2 ┆ 20 ┆ 0 ┆ 1 │
└───────┴───────┴─────┴─────┘
Source code in src/analog_daddy/plutils.py
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 | |
filter_all_null(df)
¶
Filter out rows from a dataframe where every value is null.
Notes
- Obtained from examples in drop_nulls
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame to clean up. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Clean DataFrame with all-null rows removed. |
Examples:
>>> (
... df := pl.DataFrame(
... {
... "a": [1, None, 3],
... "b": ["x", None, None],
... }
... )
... )
shape: (3, 2)
┌──────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞══════╪══════╡
│ 1 ┆ x │
│ null ┆ null │
│ 3 ┆ null │
└──────┴──────┘
>>> filter_all_null(df)
shape: (2, 2)
┌─────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪══════╡
│ 1 ┆ x │
│ 3 ┆ null │
└─────┴──────┘
Source code in src/analog_daddy/plutils.py
metrics_to_rows(df, separator='__')
¶
Reshape wide-format dataframe to a concise summary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame to reshape. |
required |
separator
|
str
|
Separator string to identify columns to unpivot. |
"__"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Reshaped DataFrame with unpivoted and pivoted columns. |
Examples:
>>> (
... df := pl.DataFrame(
... {
... "id": [1, 2],
... "min__x": [1.0, 2.0],
... "min__y": [1.0, 4.0],
... "max__x": [5.0, 6.0],
... "max__y": [5.0, 6.0],
... }
... )
... )
shape: (2, 5)
┌─────┬────────┬────────┬────────┬────────┐
│ id ┆ min__x ┆ min__y ┆ max__x ┆ max__y │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞═════╪════════╪════════╪════════╪════════╡
│ 1 ┆ 1.0 ┆ 1.0 ┆ 5.0 ┆ 5.0 │
│ 2 ┆ 2.0 ┆ 4.0 ┆ 6.0 ┆ 6.0 │
└─────┴────────┴────────┴────────┴────────┘
>>> metrics_to_rows(df)
shape: (4, 4)
┌─────┬────────┬─────┬─────┐
│ id ┆ metric ┆ min ┆ max │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ f64 ┆ f64 │
╞═════╪════════╪═════╪═════╡
│ 1 ┆ x ┆ 1.0 ┆ 5.0 │
│ 2 ┆ x ┆ 2.0 ┆ 6.0 │
│ 1 ┆ y ┆ 1.0 ┆ 5.0 │
│ 2 ┆ y ┆ 4.0 ┆ 6.0 │
└─────┴────────┴─────┴─────┘
Source code in src/analog_daddy/plutils.py
scan_nested_params(df, scan_col, identify_str='Parameters:', key_split='=', pair_split=',')
¶
Scan a DataFrame for first matching row containing nested params.
Eagerly scans the DataFrame for the first row containing
identify_str, then extracts key names from it using
key_split and pair_split. Used with
:func:explode_nested_params.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame to scan for the row. |
required |
scan_col
|
str
|
Column to scan for the identifying row. |
required |
identify_str
|
str
|
String that identifies the row to extract keys from. |
"Parameters:"
|
key_split
|
str
|
String that separates keys from values in the row. |
"="
|
pair_split
|
str
|
String that separates key-value pairs in the row. |
","
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Ordered list of parameter names found in the first matching row. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Examples:
>>> (
... df := pl.DataFrame(
... {
... "Point": [
... "Parameters: var1=-12k, var_b=1n",
... "1",
... "Parameters: var3=-12k",
... "2",
... ],
... "Value": [None, 10, 1, None],
... }
... )
... )
shape: (4, 2)
┌─────────────────────────────────┬───────┐
│ Point ┆ Value │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════════════════════════════════╪═══════╡
│ Parameters: var1=-12k, var_b=1… ┆ null │
│ 1 ┆ 10 │
│ Parameters: var3=-12k ┆ 1 │
│ 2 ┆ null │
└─────────────────────────────────┴───────┘
>>> scan_nested_params(df, scan_col="Point")
['var1', 'var_b']
Source code in src/analog_daddy/plutils.py
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 | |