pd_utils¶
Pandas DataFrame utilities for column selection, I/O, and transformation.
This module provides helper functions for working with pandas DataFrames, including column selection by name/type/regex, CSV/pickle I/O, conversion to numpy arrays/dicts, group-based limiting, column transforms, and datetime-epoch conversion.
get_df_columns(df, discards=None)
¶
Return column names from df, excluding any in discards.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
discards
|
Optional set of column names to exclude. |
None
|
Returns:
| Type | Description |
|---|---|
|
A list of column names not in discards. |
Example
import pandas as pd
df = pd.DataFrame({'a': [3, 1], 'b': [1.5, 2.5]})
pd_utils.get_df_columns(df) # ['a', 'b']
pd_utils.get_df_columns(df, discards={'b'}) # ['a']
Source code in py_misc_utils/pd_utils.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
get_typed_columns(df, type_fn, discards=None)
¶
Return column names whose dtype satisfies type_fn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
type_fn
|
A callable taking a numpy dtype and returning True if the column should be included. |
required | |
discards
|
Optional set of column names to exclude. |
None
|
Returns:
| Type | Description |
|---|---|
|
A list of column names matching the type predicate. |
Example
import pandas as pd
df = pd.DataFrame({'a': [3, 1], 'c': ['x', 'y']})
pd_utils.get_typed_columns(df, pd.api.types.is_numeric_dtype)
# ['a']
Source code in py_misc_utils/pd_utils.py
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 | |
is_numeric_dtype(dtype)
¶
Check if a dtype is numeric (integer or floating point).
Extension dtypes - which np.issubdtype() cannot interpret - are handled via pd.api.types.is_numeric_dtype(), while plain NumPy dtypes are delegated to npu.is_numeric() to keep the np_utils contract pure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
A pandas or NumPy dtype. |
required |
Returns:
| Type | Description |
|---|---|
|
True if dtype is a numeric type. |
Example
import numpy as np
import pandas as pd
pd_utils.is_numeric_dtype(np.dtype('int64')) # True
pd_utils.is_numeric_dtype(pd.Int64Dtype()) # True
pd_utils.is_numeric_dtype(pd.StringDtype()) # False
pd_utils.is_numeric_dtype(np.dtype(bool)) # False
Source code in py_misc_utils/pd_utils.py
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 | |
re_select_columns(df, re_cols)
¶
Return column names matching any of the given regex patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
re_cols
|
A collection of regex patterns to match against column names. |
required |
Returns:
| Type | Description |
|---|---|
|
A list of column names that match at least one pattern. |
Example
import pandas as pd
df = pd.DataFrame({'ab': [1], 'cd': [2]})
pd_utils.re_select_columns(df, ['a', 'c.+']) # ['ab', 'cd']
Source code in py_misc_utils/pd_utils.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
read_csv(path, rows_sample=100, dtype=None, args=None)
¶
Read a CSV file into a pandas DataFrame with optional dtype inference.
If dtype is not provided, samples the first rows_sample rows to infer numeric column types automatically.
A dict dtype is passed through to pd.read_csv() as-is, while a single dtype is applied to the numeric columns detected in the sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Filesystem path or URL to the CSV file. |
required | |
rows_sample
|
Number of rows to sample for dtype inference (default: 100). |
100
|
|
dtype
|
Optional dtype specification (dict mapping column to dtype, or a single dtype to apply to all numeric columns). |
None
|
|
args
|
Optional dict of extra keyword arguments for pd.read_csv(). |
None
|
Returns:
| Type | Description |
|---|---|
|
A pandas DataFrame. |
Example
import os
import tempfile
import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [1.5, 2.5]})
path = os.path.join(tempfile.mkdtemp(), 'data.csv')
pd_utils.save_dataframe(df, path)
pd_utils.read_csv(path, dtype={'a': np.int64})
Source code in py_misc_utils/pd_utils.py
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 | |
save_dataframe(df, path, **kwargs)
¶
Save a DataFrame to a pickle or CSV file based on extension.
Only '.pkl' and '.csv' extensions are supported. For CSV files, the index is dropped when it has no name (unless index is given in kwargs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
path
|
Output filesystem path. |
required | |
**kwargs
|
Format-specific options passed to to_pickle or to_csv. |
{}
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the path extension is neither .pkl nor .csv. |
Example
import os
import tempfile
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [1.5, 2.5]})
pd_utils.save_dataframe(df, os.path.join(tempfile.mkdtemp(), 'out.pkl'))
pd_utils.save_dataframe(df, os.path.join(tempfile.mkdtemp(), 'out.csv'))
Source code in py_misc_utils/pd_utils.py
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 | |
load_dataframe(path, **kwargs)
¶
Load a DataFrame from a pickle or CSV file based on extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Filesystem path or URL to the data file. |
required | |
**kwargs
|
Format-specific options. For CSV, supports rows_sample and dtype (as per read_csv()), plus any pd.read_csv() option. |
{}
|
Returns:
| Type | Description |
|---|---|
|
A pandas DataFrame. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the path extension is neither .pkl nor .csv. |
Example
import os
import tempfile
import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [1.5, 2.5]})
path = os.path.join(tempfile.mkdtemp(), 'data.csv')
pd_utils.save_dataframe(df, path)
pd_utils.load_dataframe(path, dtype={'a': np.int64})
Source code in py_misc_utils/pd_utils.py
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 | |
to_npdict(df, reset_index=False, dtype=None, no_convert=())
¶
Convert a DataFrame to a dict of numpy arrays keyed by column name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
reset_index
|
If True, a named index is added to the output as an extra column. |
False
|
|
dtype
|
Optional dtype specification applied via npu.astype. |
None
|
|
no_convert
|
Tuple of column names to skip dtype conversion. |
()
|
Returns:
| Type | Description |
|---|---|
|
A dict mapping column names to numpy arrays. |
Example
import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [3, 1], 'b': [1.5, 2.5]})
pd_utils.to_npdict(df) # {'a': array([3, 1]), 'b': array([1.5, 2.5])}
pd_utils.to_npdict(df, dtype={'a': np.float32})
Source code in py_misc_utils/pd_utils.py
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 | |
load_dataframe_as_npdict(path, reset_index=False, dtype=None, no_convert=())
¶
Load a DataFrame from file and convert it to a dict of numpy arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Filesystem path or URL to the data file, as per load_dataframe(). |
required | |
reset_index
|
If True, a named index is added to the output as an extra column. |
False
|
|
dtype
|
Optional dtype specification applied via npu.astype. |
None
|
|
no_convert
|
Tuple of column names to skip dtype conversion. |
()
|
Returns:
| Type | Description |
|---|---|
|
A dict mapping column names to numpy arrays. |
Example
import os
import tempfile
import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [1.5, 2.5]})
path = os.path.join(tempfile.mkdtemp(), 'data.csv')
pd_utils.save_dataframe(df, path)
pd_utils.load_dataframe_as_npdict(path, dtype={'b': np.float32})
Source code in py_misc_utils/pd_utils.py
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 | |
column_or_index(df, name, numpy=True)
¶
Return the column data for name, or the index if name matches index.name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
name
|
The column or index name. |
required | |
numpy
|
If True, return data as a numpy array. |
True
|
Returns:
| Type | Description |
|---|---|
|
The column/index data, or None when no column or index named name |
|
|
exists. |
Example
import pandas as pd
df = pd.DataFrame({'a': [3, 1]})
df.index.name = 'ts'
pd_utils.column_or_index(df, 'a') # The 'a' column values.
pd_utils.column_or_index(df, 'ts') # The index values.
Source code in py_misc_utils/pd_utils.py
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 | |
columns_transform(df, cols, tfn)
¶
Apply a transformation function to specified columns or index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
cols
|
A collection of column names to transform: names matching a named index are applied to the index. |
required | |
tfn
|
A callable taking (name, data, index) and returning transformed data; data is the column (or index) values and index tells whether they belong to the index. |
required |
Returns:
| Type | Description |
|---|---|
|
The modified DataFrame. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When a name matches neither a column nor the index. |
Example
import pandas as pd
df = pd.DataFrame({'a': [3, 1]})
pd_utils.columns_transform(df, ['a'], lambda c, v, index: v * 10)
Source code in py_misc_utils/pd_utils.py
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 | |
get_columns_index(df)
¶
Split a DataFrame into its column index mapping and column list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required |
Returns:
| Type | Description |
|---|---|
|
A tuple with the dict mapping each column name to its ordinal |
|
|
position and the list of column names. |
Example
import pandas as pd
pd_utils.get_columns_index(pd.DataFrame({'a': [0], 'b': [1]}))
# ({'a': 0, 'b': 1}, ['a', 'b'])
Source code in py_misc_utils/pd_utils.py
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | |
concat_dataframes(files, **kwargs)
¶
Load and concatenate the DataFrames of a list of files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
files
|
Iterable of filesystem paths or URLs, each loaded with load_dataframe(). |
required | |
**kwargs
|
Format-specific options forwarded to load_dataframe(). |
{}
|
Returns:
| Type | Description |
|---|---|
|
The concatenated pandas DataFrame, or None when no file is given. |
Example
import os
import tempfile
import pandas as pd
df = pd.DataFrame({'a': [1, 2]})
td = tempfile.mkdtemp()
p1, p2 = os.path.join(td, 'a.csv'), os.path.join(td, 'b.csv')
pd_utils.save_dataframe(df, p1)
pd_utils.save_dataframe(df * 2, p2)
pd_utils.concat_dataframes([p1, p2])
Source code in py_misc_utils/pd_utils.py
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 | |
get_dataframe_groups(df, cols, cols_transforms=None)
¶
Group the DataFrame rows by the tuple of values of some columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
cols
|
Column names whose tuple of values forms the group key. |
required | |
cols_transforms
|
Optional dict mapping a column name to a callable applied to its values before building the group key. |
None
|
Returns:
| Type | Description |
|---|---|
|
A dict mapping each group key tuple to the array.array of strictly |
|
|
ascending row numbers of the rows belonging to the group. The row |
|
|
numbers are strictly ascending within each group, do NOT change that! |
Example
import pandas as pd
df = pd.DataFrame({'k': ['u', 'u', 'v'], 'v': [1, 2, 3]})
pd_utils.get_dataframe_groups(df, ['k'])
# {('u',): array([0, 1]), ('v',): array([2])}
pd_utils.get_dataframe_groups(df, ['k'], cols_transforms={'k': str.upper})
Source code in py_misc_utils/pd_utils.py
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 | |
limit_per_group(df, cols, limit)
¶
Limit the number of rows selected from each group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
cols
|
Column names whose tuple of values forms the group key, as per get_dataframe_groups(). |
required | |
limit
|
Maximum number of rows to keep for each group; a negative value keeps the rows at the end of each group. |
required |
Returns:
| Type | Description |
|---|---|
|
The DataFrame containing the selected rows. |
Example
import pandas as pd
df = pd.DataFrame({'k': ['u', 'u', 'v'], 'v': [1, 2, 3]})
pd_utils.limit_per_group(df, ['k'], 1) # The first row of each group.
pd_utils.limit_per_group(df, ['k'], -1) # The last row of each group.
Source code in py_misc_utils/pd_utils.py
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 | |
dataframe_column_rewrite(df, name, fn)
¶
Replace the values of a column or of the index in place.
The DataFrame is modified in place; a new copy is still returned for chaining purposes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
name
|
Name of the column or index to rewrite. |
required | |
fn
|
Callable taking the numpy array of the values and returning the new values. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When no column or index named name exists. |
Example
import pandas as pd
df = pd.DataFrame({'a': [3, 1]})
pd_utils.dataframe_column_rewrite(df, 'a', lambda v: v * -1)
Source code in py_misc_utils/pd_utils.py
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 | |
correlate(df, col, top_n=None)
¶
Compute the columns most correlated with a given column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
col
|
Name of the column to correlate the other columns with. |
required | |
top_n
|
Maximum number of columns to return; defaults to all of them. |
None
|
Returns:
| Type | Description |
|---|---|
|
A tuple of (column name, correlation) pairs sorted by descending |
|
|
absolute correlation value. |
Example
import pandas as pd
df = pd.DataFrame({'x': [1, 2, 3], 'y': [2, 4, 6], 'z': [1, 0, 1]})
pd_utils.correlate(df, 'x') # (('x', 1.0), ('y', 1.0), ('z', -0.44...))
pd_utils.correlate(df, 'x', top_n=2) # The two most correlated columns.
Source code in py_misc_utils/pd_utils.py
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | |
type_convert_dataframe(df, types)
¶
Convert the types of DataFrame columns in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
types
|
Dict mapping column names to the type to convert them to. |
required |
Returns:
| Type | Description |
|---|---|
|
The modified DataFrame. |
Example
import pandas as pd
df = pd.DataFrame({'a': [1, 2]})
pd_utils.type_convert_dataframe(df, {'a': 'float32'})
Source code in py_misc_utils/pd_utils.py
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | |
dataframe_rows_select(df, indices)
¶
Select DataFrame rows by their ordinal position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
indices
|
Sequence of row positions to select. |
required |
Returns:
| Type | Description |
|---|---|
|
The DataFrame containing the selected rows. |
Example
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3]})
pd_utils.dataframe_rows_select(df, [0, 2])
Source code in py_misc_utils/pd_utils.py
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 | |
sorted_index(df, col)
¶
Sort a DataFrame and set a column as its index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
A pandas DataFrame. |
required | |
col
|
Name of the column to sort by and to use as index. |
required |
Returns:
| Type | Description |
|---|---|
|
The DataFrame sorted by col: when col is already the index name the |
|
|
rows are simply sorted, otherwise the sorted rows are re-indexed |
|
|
with the col values. |
Example
import pandas as pd
df = pd.DataFrame({'a': [3, 1, 2]})
sdf = pd_utils.sorted_index(df, 'a')
sdf.index # The sorted 'a' values: [1, 2, 3].
Source code in py_misc_utils/pd_utils.py
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 | |
datetime_to_epoch(data)
¶
Convert datetime values into epoch seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Sequence of datetime values convertible by pd.to_datetime(). |
required |
Returns:
| Type | Description |
|---|---|
|
A pandas Series of epoch seconds with fractional part. |
Example
pd_utils.datetime_to_epoch(['1970-01-01', '1970-01-02'])
# [0.0, 86400.0]
Source code in py_misc_utils/pd_utils.py
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 | |