Dataframe verbs and tools
The dfverbs
module is intended to be imported as an alias and used inside pipe
for dplyr like data manipulation grammar. Using the sample on the redframes README:
import pandas as pd
from utilz import pipe, randdf
import utilz.dfverbs as _
# Define demo df
df = pd.DataFrame({
'bear': ['Brown bear', 'Polar bear', 'Asian black bear', 'American black bear', 'Sun bear', 'Sloth bear', 'Spectacled bear', 'Giant panda'],
'genus': ['Ursus', 'Ursus', 'Ursus', 'Ursus', 'Helarctos', 'Melursus', 'Tremarctos', 'Ailuropoda'],
'weight (male, lbs)': ['300-860', '880-1320', '220-440', '125-500', '60-150', '175-310', '220-340', '190-275'],
'weight (female, lbs)': ['205-455', '330-550', '110-275', '90-300', '45-90', '120-210', '140-180', '155-220']
})
out = pipe(
df,
_.rename({"weight (male, lbs)": "male", "weight (female, lbs)": "female"}),
_.pivot_longer(columns=["male", "female"], into=("sex", "weight")),
_.split("weight", ("min", "max"), sep="-"),
_.pivot_longer(columns=["min", "max"], into=("stat", "weight")),
_.astype({"weight": float}),
_.groupby("genus", "sex"),
_.summarize(weight="weight.mean()"),
_.pivot_wider(column="sex", using="weight"),
_.mutate(dimorphism="male / female"), # no rounding possible
_.mutate(dimorphism=lambda male, female: np.round(male / female, 2)) # instead use a func
)
Note
The dftools
module on the other handed is not intended to be imported at all. Instead it defines new .methods
on pandas DataFrame
and DataFrameGroupBy
objects automatically, e.g. df.select('-Col1')
is a new method that allows for R-style column selection.
Verbs
dplyr like verbs for working with pandas dataframes.
apply(*args, **kwargs)
Call a dataframe or groupby object's .apply
method
For groupbed dataframes, resets and drops index by default. Change this with reset_index='drop'|'reset'|'none'
Source code in utilz/dfverbs/verbs.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
|
assign(**kwargs)
Call a dataframe object's .assign
method
Source code in utilz/dfverbs/verbs.py
213 214 215 216 217 218 219 220 221 |
|
astype(cols, df)
Cast one ore more columns to a type. Like .rename()
you can either input a single tuple to cast 1
column or a dict to cast multiple
Source code in utilz/dfverbs/verbs.py
512 513 514 515 516 517 518 |
|
call(*args, **kwargs)
Call an arbitrary method or function on an object, e.g. pipe(df,
_.call('mean'))
would call df.mean()
Source code in utilz/dfverbs/verbs.py
533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
|
concat(*args, **kwargs)
Call pd.concat
Source code in utilz/dfverbs/verbs.py
112 113 114 115 |
|
drop(*args)
Call a dataframe's .drop(axis=1)
method. Column names should be passed as
multiple args like .select()
, e.g. _.drop('height', 'weight')
Source code in utilz/dfverbs/verbs.py
414 415 416 417 418 419 420 421 422 |
|
fillna(*args, **kwargs)
Call a dataframe's fillna method
Source code in utilz/dfverbs/verbs.py
574 575 576 577 578 579 580 581 |
|
groupby(*args)
Call a dataframe's .groupby
method
Source code in utilz/dfverbs/verbs.py
87 88 89 90 91 92 93 94 |
|
head(*args, **kwargs)
Call dataframe's .head()
method
Source code in utilz/dfverbs/verbs.py
394 395 396 397 398 399 400 401 |
|
join(*args, **kwargs)
Call pd.concat
Source code in utilz/dfverbs/verbs.py
124 125 126 127 |
|
merge(*args, **kwargs)
Call pd.concat
Source code in utilz/dfverbs/verbs.py
118 119 120 121 |
|
mutate(dfg, **kwargs)
Creates a new column(s) in a DataFrame based on a function of existing columns in the DataFrame. Always returns a dataframe the same size as the original. For groupby inputs, the result is always ungrouped.
Just like .summarize()
, input should be kwargs organized like new_column = str|
function
. Such as: _.mutate(weight_centered ='weight - weight.mean()')
or _.mutate(weight_centered = lambda weight: weight - weight.mean())
or _.mutate(weight_centered = lambda df: df['weight].apply(lambda x: x -
x.mean())
. To return output smaller than the input dataframe use .summarize()
instead.
Source code in utilz/dfverbs/verbs.py
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 |
|
pivot_longer(*args, **kwargs)
Convert a list of columns into 2 columns. Can pass a list of columsn to melt-down or
id_vars
to select everything else: e.g. _.pivot_longer(['male', 'female'],
into=('gender', 'response'))
or _.pivot_longer(id_vars='SID', into=('gender','response'))
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns |
list or None
|
columns to melt; Defaults to None |
required |
id_vars |
list or None
|
columns to use as id variables; Default to None |
required |
into |
tuple
|
cols to create Defaults to ("variable", "value"). |
required |
make_index |
bool
|
does a reset_index prior to melting and adds the |
required |
Source code in utilz/dfverbs/verbs.py
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 |
|
pivot_wider(*args, **kwargs)
Convert a pair of columns to multiple columns, e.g. _.pivot_wider('condition', using='response')
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column |
str
|
string name of column to "explode" |
required |
using |
str
|
string name of column who's values should be placed into the new columns |
required |
drop_index |
bool; optional
|
if a 'prev_index' col exists (usually created by |
required |
Source code in utilz/dfverbs/verbs.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
|
query(q, **kwargs)
Call a dataframe object's .query
method. Resets and drops index by
default. Change this with reset_index='drop'|'reset'|'none'
Source code in utilz/dfverbs/verbs.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 |
|
read_csv(*args, **kwargs)
Call pd.read_csv
Source code in utilz/dfverbs/verbs.py
106 107 108 109 |
|
rename(cols, df)
Rename one ore more columns. Can either input a single tuple to rename 1 column or a dict to rename multiple
Source code in utilz/dfverbs/verbs.py
97 98 99 100 101 102 103 |
|
replace(*args, **kwargs)
Call a dataframe's replace method
Source code in utilz/dfverbs/verbs.py
584 585 586 587 588 589 590 591 |
|
reset_index(*args, **kwargs)
Call a dataframe's reset_index method
Source code in utilz/dfverbs/verbs.py
594 595 596 597 598 599 600 601 |
|
select(*args)
Select one or more columns by name. Drop one or more columns by prepending '-' to the name. Always returns a dataframe even if there is just 1 column. Does not support renaming
Source code in utilz/dfverbs/verbs.py
425 426 427 428 429 430 431 432 433 434 435 |
|
sort(*args, **kwargs)
Sort df by one or more columns passed as args. Ignores index by default by you
can change that with ignore_index=False
.
Source code in utilz/dfverbs/verbs.py
521 522 523 524 525 526 527 528 529 530 |
|
split(*args, sep=' ')
Split values in single df column into multiple columns by separator, e.g. First-Last -> [First], [Last]. To split list elements use [] as the sep, e.g. [1,2,3] -> [1], [2], [3]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column |
str
|
column to split |
required |
into |
list
|
new columns names to create |
required |
sep |
str, list
|
separator to split on. Use [] for list |
' '
|
Source code in utilz/dfverbs/verbs.py
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 |
|
splitquery(query, **kwargs)
Call a dataframe or groupby object's .query
method and return 2 dataframes one
where containing results where the query is true and its inverse.
Resets and drops index by default. Change this with reset_index='drop'|'reset'|'none'
Source code in utilz/dfverbs/verbs.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 |
|
squeeze(*args, **kwargs)
Call a dataframe's .squeeze
method
Source code in utilz/dfverbs/verbs.py
57 58 59 60 61 62 63 64 |
|
summarize(dfg, **kwargs)
Create new columns based on existing columns in a dataframe but return a
smaller dataframe than the original. Works with the output of groupby
as well:
Just like .mutate()/.transmute()
, input should be kwargs organized like
new_column = str| function
. Such as: _.summarize(weight_mean ='weight.mean()')
or _.summarize(weight_mean = lambda weight: weight.mean())
or _.summarize(weight_mean = lambda df: df['weight].mean())
. To return output the
same size as the input dataframe use .mutate()
or .transmute()
instead as
either will broadcast values to the right size.
Source code in utilz/dfverbs/verbs.py
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 |
|
tail(*args, **kwargs)
Call dataframe's .tail()
method
Source code in utilz/dfverbs/verbs.py
404 405 406 407 408 409 410 411 |
|
to_csv(path, df, index=False)
Call a dataframe's .to_csv(index=False)
method
Source code in utilz/dfverbs/verbs.py
130 131 132 133 134 135 136 |
|
to_list(*args, **kwargs)
Call a dataframe's .to_list
method
Source code in utilz/dfverbs/verbs.py
77 78 79 80 81 82 83 84 |
|
to_numpy(*args, **kwargs)
Call a dataframe's .to_numpy
method
Source code in utilz/dfverbs/verbs.py
67 68 69 70 71 72 73 74 |
|
transmute(dfg, **kwargs)
Just like .mutate()
, but only returns the newly created columns.
Source code in utilz/dfverbs/verbs.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
|
Stats
dataframe stats methods
abs(*args, **kwargs)
Call df.abs
Source code in utilz/dfverbs/stats.py
151 152 153 154 155 156 157 158 |
|
all(*args, **kwargs)
Call df.all
Source code in utilz/dfverbs/stats.py
171 172 173 174 175 176 177 178 |
|
any(*args, **kwargs)
Call df.any
Source code in utilz/dfverbs/stats.py
181 182 183 184 185 186 187 188 |
|
bootci(col, **kwargs)
Calculate 95% bootstrapped confidence intervals on the mean of a column. Unlike
summarize, bootci expects a string column name and will return a summary frame with
columns for the mean, 2.5% and 97.% confidence limits. Use as_devation=True
to
convert the CIs to deviations from the mean. Accepts all the same args as
seaborn.algorithms.bootstrap
, e.g. units
.
Source code in utilz/dfverbs/stats.py
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 |
|
corr(*args, **kwargs)
Call df.corr
Source code in utilz/dfverbs/stats.py
191 192 193 194 195 196 197 198 |
|
count(*args, **kwargs)
Call df.count
Source code in utilz/dfverbs/stats.py
211 212 213 214 215 216 217 218 |
|
cov(*args, **kwargs)
Call df.cov
Source code in utilz/dfverbs/stats.py
201 202 203 204 205 206 207 208 |
|
max(*args, **kwargs)
Call df.max
Source code in utilz/dfverbs/stats.py
71 72 73 74 75 76 77 78 |
|
mean(*args, **kwargs)
Call df.mean
Source code in utilz/dfverbs/stats.py
41 42 43 44 45 46 47 48 |
|
median(*args, **kwargs)
Call df.median
Source code in utilz/dfverbs/stats.py
51 52 53 54 55 56 57 58 |
|
min(*args, **kwargs)
Call df.min
Source code in utilz/dfverbs/stats.py
61 62 63 64 65 66 67 68 |
|
mode(*args, **kwargs)
Call df.mode
Source code in utilz/dfverbs/stats.py
81 82 83 84 85 86 87 88 |
|
nunique(*args, **kwargs)
Call df.nunique
Source code in utilz/dfverbs/stats.py
242 243 244 245 246 247 248 249 250 |
|
prod(*args, **kwargs)
Call df.prod
Source code in utilz/dfverbs/stats.py
131 132 133 134 135 136 137 138 |
|
rank(*args, **kwargs)
Call df.rank
Source code in utilz/dfverbs/stats.py
264 265 266 267 268 269 270 271 |
|
round(*args, **kwargs)
Call df.round
Source code in utilz/dfverbs/stats.py
141 142 143 144 145 146 147 148 |
|
sem(*args, **kwargs)
Call df.sem
Source code in utilz/dfverbs/stats.py
121 122 123 124 125 126 127 128 |
|
size(*args, **kwargs)
Call df.size
Source code in utilz/dfverbs/stats.py
274 275 276 277 278 279 280 281 |
|
sqrt(*args, **kwargs)
Call df.sqrt
Source code in utilz/dfverbs/stats.py
161 162 163 164 165 166 167 168 |
|
std(*args, **kwargs)
Call df.std
Source code in utilz/dfverbs/stats.py
101 102 103 104 105 106 107 108 |
|
sum(*args, **kwargs)
Call df.sum
Source code in utilz/dfverbs/stats.py
111 112 113 114 115 116 117 118 |
|
unique(*args, **kwargs)
Call df.unique
Source code in utilz/dfverbs/stats.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
|
value_counts(*args, **kwargs)
Call df.value_counts
Source code in utilz/dfverbs/stats.py
253 254 255 256 257 258 259 260 261 |
|
var(*args, **kwargs)
Call df.var
Source code in utilz/dfverbs/stats.py
91 92 93 94 95 96 97 98 |
|
Plots
plotting verbs to wrap calls to seaborn
barplot(**kwargs)
Call to seaborn barplot
Source code in utilz/dfverbs/plot.py
269 270 271 272 273 274 275 276 |
|
boxenplot(**kwargs)
Call to seaborn boxenplot
Source code in utilz/dfverbs/plot.py
119 120 121 122 123 124 125 126 |
|
boxplot(**kwargs)
Call to seaborn boxplot
Source code in utilz/dfverbs/plot.py
139 140 141 142 143 144 145 146 |
|
catplot(**kwargs)
Call to seaborn catplot
Source code in utilz/dfverbs/plot.py
259 260 261 262 263 264 265 266 |
|
clustermap(**kwargs)
Call to seaborn clustermap
Source code in utilz/dfverbs/plot.py
59 60 61 62 63 64 65 66 |
|
countplot(**kwargs)
Call to seaborn countplot
Source code in utilz/dfverbs/plot.py
99 100 101 102 103 104 105 106 |
|
displot(**kwargs)
Call to seaborn displot
Source code in utilz/dfverbs/plot.py
209 210 211 212 213 214 215 216 |
|
ecdfplot(**kwargs)
Call to seaborn ecdfplot
Source code in utilz/dfverbs/plot.py
179 180 181 182 183 184 185 186 |
|
heatmap(**kwargs)
Call to seaborn heatmap
Source code in utilz/dfverbs/plot.py
239 240 241 242 243 244 245 246 |
|
histplot(**kwargs)
Call to seaborn histplot
Source code in utilz/dfverbs/plot.py
199 200 201 202 203 204 205 206 |
|
jointplot(**kwargs)
Call to seaborn jointplot
Source code in utilz/dfverbs/plot.py
39 40 41 42 43 44 45 46 |
|
kdeplot(**kwargs)
Call to seaborn kdeplot
Source code in utilz/dfverbs/plot.py
189 190 191 192 193 194 195 196 |
|
lineplot(**kwargs)
Call to seaborn lineplot
Source code in utilz/dfverbs/plot.py
249 250 251 252 253 254 255 256 |
|
lmplot(**kwargs)
Call to seaborn lmplot
Source code in utilz/dfverbs/plot.py
89 90 91 92 93 94 95 96 |
|
pairplot(**kwargs)
Call to seaborn pairplot
Source code in utilz/dfverbs/plot.py
49 50 51 52 53 54 55 56 |
|
plot(*args, **kwargs)
Call a dataframe's .plot method
Source code in utilz/dfverbs/plot.py
290 291 292 293 294 295 296 297 |
|
pointplot(**kwargs)
Call to seaborn pointplot
Source code in utilz/dfverbs/plot.py
109 110 111 112 113 114 115 116 |
|
regplot(**kwargs)
Call to seaborn regplot
Source code in utilz/dfverbs/plot.py
79 80 81 82 83 84 85 86 |
|
relplot(**kwargs)
Call to seaborn relplot
Source code in utilz/dfverbs/plot.py
229 230 231 232 233 234 235 236 |
|
residplot(**kwargs)
Call to seaborn residplot
Source code in utilz/dfverbs/plot.py
69 70 71 72 73 74 75 76 |
|
rugplot(**kwargs)
Call to seaborn rugplot
Source code in utilz/dfverbs/plot.py
169 170 171 172 173 174 175 176 |
|
scatterplot(**kwargs)
Call to seaborn scatterplot
Source code in utilz/dfverbs/plot.py
219 220 221 222 223 224 225 226 |
|
stripbarplot(**kwargs)
Call to combined stripplot and barplot. See utilz.plot.stripbarplot
Source code in utilz/dfverbs/plot.py
279 280 281 282 283 284 285 286 287 |
|
stripplot(**kwargs)
Call to seaborn stripplot
Source code in utilz/dfverbs/plot.py
159 160 161 162 163 164 165 166 |
|
swarmplot(**kwargs)
Call to seaborn swarmplot
Source code in utilz/dfverbs/plot.py
149 150 151 152 153 154 155 156 |
|
violinplot(**kwargs)
Call to seaborn violinplot
Source code in utilz/dfverbs/plot.py
129 130 131 132 133 134 135 136 |
|
utilz.dftools
Common data operations and transformations often on pandas dataframes. This creates new dataframe methods that can be called like this:
df.norm_by_group(grpcol='Class', valcol='Score')
assert_balanced_groups(df, grpcols, size=None)
Check if each group of grpcols
has the same dimensions
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
pd.DataFrame
|
input dataframe |
required |
group_cols |
str/List
|
column names to group on in dataframe |
required |
shape |
tuple/None
|
optional group sizes to ensure |
required |
Source code in utilz/dftools.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
|
assert_same_nunique(df, grpcols, valcol, size=None)
Check if each group has the same number of unique values in valcol
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
pd.DataFrame
|
input dataframe |
required |
valcol |
str
|
column to check unique values in |
required |
grpcols |
str/list
|
column names to group on in dataframe, Default None |
required |
shape |
tuple/None
|
optional sizes to ensure |
required |
Source code in utilz/dftools.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
|
norm_by_group(df, grpcol, valcols, center=True, scale=True, addcol=True)
Normalize values in one or more columns separately per group
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
pd.DataFrame
|
input dataframe |
required |
grpcols |
str
|
grouping col |
required |
valcols |
Union[str, List]
|
value cols |
required |
center |
bool
|
mean center. Defaults to True. |
True
|
scale |
bool
|
divide by standard deviation. Defaults to True. |
True
|
Source code in utilz/dftools.py
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 |
|
pivot_longer(df, columns=None, id_vars=None, into=('variable', 'value'), make_index=False)
Take multiple columns or multiple id_vars and melt them into 2 columns. If columns is provided, id_vars is inferred and visa-versa. If make_index=True, will use the current index as a new id_var to ensure a unique index.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
pd.DataFrame
|
input DataFrame |
required |
columns |
list or None
|
columns to melt; Defaults to None |
None
|
id_vars |
list or None
|
columns to use as id variables; Default to None |
None
|
into |
tuple
|
cols to create Defaults to ("variable", "value"). |
('variable', 'value')
|
make_index |
bool
|
does a reset_index prior to melting and adds the |
False
|
Source code in utilz/dftools.py
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 |
|
pivot_wider(df, column, using, drop_index=True)
Cast a column of long-form tidy data to a set of wide columns based on the values in a another column ('using')
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
pd.DataFrame
|
input dataframe |
required |
column |
str
|
string name of column to "explode" |
required |
using |
str
|
string name of column who's values should be placed into the new |
required |
drop_index |
bool; optional
|
if a 'prev_index' col exists (usually created by |
True
|
Source code in utilz/dftools.py
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 |
|
select(df, *args, **kwargs)
Select one ore more columns by name. Drop one or more columns by prepending '-' to the name. Rename columns using keyword arguments.
Examples:
>>> # Grab 2 columns
>>> df.select('sepal_width', 'petal_width')
>>> # Get all columns except one
>>> df.select('-sepal_width')
>>> # Grab a column and rename it
>>> df.select(sepal_width='width')
Source code in utilz/dftools.py
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 |
|