Clumper
¶
This object adds methods to a list of dictionaries that make it nicer to explore.
Parameters
Name | Type | Description | Default |
---|---|---|---|
blob |
the list of data to turn into a Clumper | required | |
groups |
specify any groups you'd like to attach to the Clumper | () |
|
listify |
if the input is a dictionary, turn it into a list with one dictionary inside beforehand. | True |
Usage:
from clumper import Clumper
list_dicts = [{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}]
c = Clumper(list_dicts)
assert len(c) == 4
only_has_dictionaries:
(property, readonly)¶
Boolean, confirms if each item in the clumper is a dictionary.
shape:
(property, readonly)¶
Returns the shape (items, n_keys) of the Clumper
agg(self, **kwargs)
¶
Show source code in clumper/clump.py
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 |
|
Does an aggregation on a collection of dictionaries. If there are no groups active then this method will create a single dictionary containing a summary. If there are groups active then the dataset will first split up, then apply the summaries after which everything is combined again into a single collection.
When defining a summary to apply you'll need to pass three things:
- the name of the new key
- the key you'd like to summarise (first item in the tuple)
- the summary you'd like to calculate on that key (second item in the tuple)
It can also accept a string and it will try to fetch an appropriate function
for you. If you pass a string it must be either: mean
, count
, unique
,
n_unique
, sum
, min
, max
, median
, values
, var
, std
, first
or last
.
Warning
This method is aware of groups. There may be different results if a group is active.
Parameters
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
keyword arguments that represent the aggregation that is about to happen, see usage below. | {} |
Usage:
from clumper import Clumper
list_dicts = [
{'a': 1, 'b': 2},
{'a': 2, 'b': 3},
{'a': 3}
]
(Clumper(list_dicts)
.agg(mean_a=('a', 'mean'),
min_b=('b', 'min'),
max_b=('b', 'max'))
.collect())
another_list_dicts = [
{'a': 1, 'c': 'a'},
{'a': 2, 'c': 'b'},
{'a': 3, 'c': 'a'}
]
(Clumper(another_list_dicts)
.group_by('c')
.agg(mean_a=('a', 'mean'),
uniq_a=('a', 'unique'))
.collect())
Advanced Usage:
You can also supply this verb your own functions if you'd like.
from clumper import Clumper
data = [
{"a": 7, "grp": "a"},
{"a": 2, "grp": "b"},
{"a": 7, "grp": "a"},
{"a": 9, "grp": "b"},
{"a": 5, "grp": "a"}
]
tfm_clump = (Clumper(data)
.group_by("grp")
.transform(s=("a", sum),
u=("a", lambda x: set(x))))
expected = [
{'a': 7, 'grp': 'a', 's': 19, 'u': {5, 7}},
{'a': 7, 'grp': 'a', 's': 19, 'u': {5, 7}},
{'a': 5, 'grp': 'a', 's': 19, 'u': {5, 7}},
{'a': 2, 'grp': 'b', 's': 11, 'u': {2, 9}},
{'a': 9, 'grp': 'b', 's': 11, 'u': {2, 9}}
]
assert tfm_clump.equals(expected)
collect(self)
¶
Show source code in clumper/clump.py
1464 1465 1466 1467 1468 1469 1470 |
|
Returns a list instead of a Clumper
object.
concat(self, *other)
¶
Show source code in clumper/clump.py
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 |
|
Concatenate two or more Clumper
objects together.
from clumper import Clumper
c1 = Clumper([{"a": 1}])
c2 = Clumper([{"a": 2}])
c3 = Clumper([{"a": 3}])
assert len(c1.concat(c2)) == 2
assert len(c1.concat(c2, c3)) == 3
assert len(c1.concat(c2).concat(c3)) == 3
copy(self)
¶
Show source code in clumper/clump.py
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 |
|
Makes a copy of the collection.
Usage:
from clumper import Clumper
list_dicts = [{'a': i} for i in range(100)]
c1 = Clumper(list_dicts)
c2 = c1.copy()
assert id(c1) != id(c2)
count(self, col)
¶
Show source code in clumper/clump.py
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 |
|
Counts how often a key appears in the collection.
Usage:
from clumper import Clumper
list_of_dicts = [
{'a': 7},
{'a': 2, 'b': 7},
{'a': 3, 'b': 6},
{'a': 2, 'b': 7}
]
assert Clumper(list_of_dicts).count("a") == 4
assert Clumper(list_of_dicts).count("b") == 3
drop(self, *keys)
¶
Show source code in clumper/clump.py
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 |
|
Removes a subset of keys from each item in the collection.
Parameters
Name | Type | Description | Default |
---|---|---|---|
*keys |
the keys to remove | () |
Usage:
from clumper import Clumper
list_dicts = [
{'a': 1, 'b': 2},
{'a': 2, 'b': 3, 'c':4},
{'a': 1, 'b': 6}]
clump = Clumper(list_dicts).drop('c')
assert all(["c" not in d.keys() for d in clump])
drop_duplicates(self)
¶
Show source code in clumper/clump.py
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 |
|
Iterates over all elements to remove duplicates.
Usage:
from clumper import Clumper
data = [{"a": 1}, {"a": 2}, {"a": 2}]
clump = Clumper(data).drop_duplicates()
expected = [{"a": 1}, {"a": 2}]
assert clump.equals(expected)
equals(self, data)
¶
Show source code in clumper/clump.py
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 |
|
Compares the collection of items with a list. Returns True
if they have the same contents.
Note that we do not care about the order of the elements.
This method is used internally for testing but it can also be very useful for bug reporting.
Parameters
Name | Type | Description | Default |
---|---|---|---|
data |
a list of that to compare against | required |
Usage:
from clumper import Clumper
data = [{"a": 1}]
clump = Clumper(data)
assert clump.equals(data)
assert not clump.equals([{"b":1}])
explode(self, *to_explode, **kwargs)
¶
Show source code in clumper/clump.py
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 |
|
Turns a list in an item into multiple items. The opposite of .implode()
.
Parameters
Name | Type | Description | Default |
---|---|---|---|
*to_explode |
keys to explode, will keep the same name | () |
|
**kwargs |
(new name, keys to explode)-pairs | {} |
Usage:
from clumper import Clumper
data = [{'a': 1, 'items': [1, 2]}]
clumper = Clumper(data).explode("items")
expected = [{'a': 1, 'items': 1}, {'a': 1, 'items': 2}]
assert clumper.equals(expected)
clumper = Clumper(data).explode(item="items")
expected = [{'a': 1, 'item': 1}, {'a': 1, 'item': 2}]
assert clumper.equals(expected)
flatten_keys(self, keyname='key')
¶
Show source code in clumper/clump.py
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 |
|
Flattens the keys in the data. Useful when Clumper
is created with a single large dictionary.
Parameters
Name | Type | Description | Default |
---|---|---|---|
keyname |
the name of the new key | 'key' |
Usage:
from clumper import Clumper
data = {
'feature_1': {'propery_1': 1, 'property_2': 2},
'feature_2': {'propery_1': 3, 'property_2': 4},
'feature_3': {'propery_1': 5, 'property_2': 6},
}
expected = [
{'propery_1': 1, 'property_2': 2, 'key': 'feature_1'},
{'propery_1': 3, 'property_2': 4, 'key': 'feature_2'},
{'propery_1': 5, 'property_2': 6, 'key': 'feature_3'}
]
assert Clumper(data, listify=False).flatten_keys().collect() == expected
group_by(self, *cols)
¶
Show source code in clumper/clump.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 |
|
Sets a group on this clumper object or overrides a previous setting.
A group will affect how some verbs behave. You can undo this behavior
with .ungroup()
.
from clumper import Clumper
clump = Clumper([{"a": 1}]).group_by("a")
assert clump.groups == ("a", )
head(self, n=5)
¶
Show source code in clumper/clump.py
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 |
|
Selects the top n
items from the collection.
Parameters
Name | Type | Description | Default |
---|---|---|---|
n |
the number of items to grab | 5 |
Usage:
from clumper import Clumper
list_dicts = [{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}]
result = Clumper(list_dicts).head(2)
expected = [{'a': 1}, {'a': 2}]
assert result.equals(expected)
implode(self, **kwargs)
¶
Show source code in clumper/clump.py
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 |
|
Nests a sequence of items. The opposite of .explode()
.
Parameters
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
(new name, keys to implode)-pairs | {} |
Usage:
from clumper import Clumper
data = [{'a': 1, 'items': [1, 2]}]
clumper = Clumper(data).explode(item="items")
expected = [{'a': 1, 'item': 1}, {'a': 1, 'item': 2}]
assert clumper.equals(expected)
clumper_back = clumper.implode(items="item")
expected = [{'a': 1, 'item': 1}, {'a': 1, 'item': 2}]
assert clumper_back.equals(data)
inner_join(self, other, mapping, lsuffix='', rsuffix='_joined')
¶
Show source code in clumper/clump.py
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 |
|
Performs an inner join on two collections.
Parameters
Name | Type | Description | Default |
---|---|---|---|
other |
another collection to join with | required | |
mapping |
a dictionary of left-keys:right-keys that explain how to join | required | |
lsuffix |
a suffix to add to the left keys in case of an overlap | '' |
|
rsuffix |
a suffix to add to the right keys in case of an overlap | '_joined' |
Usage:
from clumper import Clumper
left = Clumper([
{"a": 1, "b":4},
{"a": 2, "b":6},
{"a": 3, "b":8},
])
right = Clumper([
{"c": 9, "b":4},
{"c": 8, "b":5},
{"c": 7, "b":6},
])
result = left.inner_join(right, mapping={"b": "b"})
expected = [
{"a": 1, "b": 4, "c": 9},
{"a": 2, "b": 6, "c": 7},
]
assert result.equals(expected)
keep(self, *funcs)
¶
Show source code in clumper/clump.py
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 |
|
Allows you to select which items to keep and which items to remove.
Parameters
Name | Type | Description | Default |
---|---|---|---|
*funcs |
functions that indicate which items to keep | () |
Usage:
from clumper import Clumper
list_dicts = [{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}]
clump = Clumper(list_dicts).keep(lambda d: d['a'] >= 3)
expected = [{'a': 3}, {'a': 4}]
assert clump.equals(expected)
keys(self, overlap=False)
¶
Show source code in clumper/clump.py
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 |
|
Returns all the keys of all the items in the collection.
Parameters
Name | Type | Description | Default |
---|---|---|---|
overlap |
if True only return the keys that overlap in each set |
False |
Usage:
from clumper import Clumper
data = [{'a': 1, 'b': 2}, {'a': 2, 'c': 3}]
assert set(Clumper(data).keys(overlap=True)) == {'a'}
assert set(Clumper(data).keys(overlap=False)) == {'a', 'b', 'c'}
left_join(self, other, mapping, lsuffix='', rsuffix='_joined')
¶
Show source code in clumper/clump.py
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 |
|
Performs a left join on two collections.
Each item from the left set will appear in the final collection. Only some items from the right set may appear if a merge is possible. There may be multiple copies of the left set if it can be joined multiple times.
Parameters
Name | Type | Description | Default |
---|---|---|---|
other |
another collection to join with | required | |
mapping |
a dictionary of left-keys:right-keys that explain how to join | required | |
lsuffix |
a suffix to add to the left keys in case of an overlap | '' |
|
rsuffix |
a suffix to add to the right keys in case of an overlap | '_joined' |
Usage:
from clumper import Clumper
left = Clumper([
{"a": 1, "b": 4},
{"a": 2, "b": 6},
{"a": 3, "b": 8},
])
right = Clumper([
{"c": 9, "b": 4},
{"c": 8, "b": 5},
{"c": 7, "b": 6},
])
result = left.left_join(right, mapping={"b": "b"})
expected = [
{"a": 1, "b": 4, "c": 9},
{"a": 2, "b": 6, "c": 7},
{"a": 3, "b": 8},
]
assert result.equals(expected)
map(self, func)
¶
Show source code in clumper/clump.py
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 |
|
Directly map one item to another one using a function.
If you're dealing with dictionaries, consider using
mutate
instead.
Parameters
Name | Type | Description | Default |
---|---|---|---|
func |
the function that will map each item | required |
Usage:
from clumper import Clumper
list_dicts = [{'a': 1}, {'a': 2}]
(Clumper(list_dicts)
.map(lambda d: {'a': d['a'], 'b': 1})
.collect())
max(self, col)
¶
Show source code in clumper/clump.py
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 |
|
Returns maximum value that a key has.
Usage:
from clumper import Clumper
list_of_dicts = [
{'a': 7},
{'a': 2, 'b': 7},
{'a': 3, 'b': 6},
{'a': 2, 'b': 7}
]
assert Clumper(list_of_dicts).max("a") == 7
assert Clumper(list_of_dicts).max("b") == 7
mean(self, col)
¶
Show source code in clumper/clump.py
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 |
|
Give the mean of the values that belong to a key.
Usage:
from clumper import Clumper
list_of_dicts = [
{'a': 7},
{'a': 2, 'b': 7},
{'a': 3, 'b': 6},
{'a': 2, 'b': 7}
]
assert round(Clumper(list_of_dicts).mean("a"), 1) == 3.5
assert round(Clumper(list_of_dicts).mean("b"), 1) == 6.7
min(self, col)
¶
Show source code in clumper/clump.py
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 |
|
Returns minimum value that a key has.
Usage:
from clumper import Clumper
list_of_dicts = [
{'a': 7},
{'a': 2, 'b': 7},
{'a': 3, 'b': 6},
{'a': 2, 'b': 7}
]
assert Clumper(list_of_dicts).min("a") == 2
assert Clumper(list_of_dicts).min("b") == 6
mutate(self, **kwargs)
¶
Show source code in clumper/clump.py
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 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 |
|
Adds or overrides key-value pairs in the collection of dictionaries.
Parameters
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
keyword arguments of keyname/function-pairs | {} |
Warning
This method is aware of groups. There may be different results if a group is active.
Usage:
from clumper import Clumper
list_dicts = [
{'a': 1, 'b': 2},
{'a': 2, 'b': 3, 'c':4},
{'a': 1, 'b': 6}]
result = (Clumper(list_dicts)
.mutate(c=lambda d: d['a'] + d['b'],
s=lambda d: d['a'] + d['b'] + d['c']))
expected = [
{'a': 1, 'b': 2, 'c': 3, 's': 6},
{'a': 2, 'b': 3, 'c': 5, 's': 10},
{'a': 1, 'b': 6, 'c': 7, 's': 14}
]
assert result.equals(expected)
n_unique(self, col)
¶
Show source code in clumper/clump.py
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 |
|
Returns number of unique values that a key has.
Usage:
from clumper import Clumper
list_of_dicts = [
{'a': 7},
{'a': 2, 'b': 7},
{'a': 3, 'b': 6},
{'a': 2, 'b': 7}
]
assert Clumper(list_of_dicts).n_unique("a") == 3
assert Clumper(list_of_dicts).n_unique("b") == 2
pipe(self, func, *args, **kwargs)
¶
Show source code in clumper/clump.py
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 |
|
Applies a function to the Clumper
object in a chain-able manner.
Parameters
Name | Type | Description | Default |
---|---|---|---|
func |
function to apply | required | |
*args |
arguments that will be passed to the function | () |
|
**kwargs |
keyword-arguments that will be passed to the function | {} |
Usage:
from clumper import Clumper
list_dicts = [{'a': i} for i in range(100)]
def remove_outliers(clump, min_a, max_a):
return (clump
.keep(lambda d: d['a'] >= min_a,
lambda d: d['a'] <= max_a))
result = Clumper(list_dicts).pipe(remove_outliers, min_a=10, max_a=90)
assert len(result) == 81
read_csv(path, delimiter=',', na_values=None, dtype=None, fieldnames=None, n=None, add_path=False)
(classmethod)¶
Show source code in clumper/clump.py
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 |
|
Reads in a csv file. Can also read files from url.
Parameters
Name | Type | Description | Default |
---|---|---|---|
path |
filename, url, pathlib.Path or list of pathlib.Path . Filenames can include a wildcard * . |
required | |
delimiter |
Delimiter used in the csv file. Must be a single character and , is the default. |
',' |
|
n |
Number of rows to read in. Useful when reading large files. If None , all rows are read. |
None |
|
fieldnames |
Allows you to set the fieldnames if the header is missing. By default, the first row of the csv will provide the Clumper keys if fieldnames is None . If fieldnames is provided, then the first row becomes part of the data. You should ensure that the correct number of fieldnames is supplied, as an incorrect number can lead to an irregular outcome. If the row has seven fields and the number of fields in fieldnames length is 3, then every row will have only 3 values, the remaining four will be lumped into a list, and assigned key None . If the rows have fewer fields than fieldnames, then the missing values are filled in with None . |
None |
|
na_values |
This provides an option for treating null values. If ignore , null values are returned as empty strings (""). If None , then for each row, the key,value pair with the null values will be truncated from the row. The only values treated as null are empty strings("") and "NA". |
None |
|
add_path |
Adds the name of the read path to each item in the Clumper. Is useful when using wildcards to read in multiple files at once. | False |
|
dtype |
Data type for each value in a key:value pair. If None , then values will be read in as strings. Available dtypes are (int, float, str). If a single dtype is passed, then all values will be converted to the data type and raise an error, if not applicable. For different data types for different key, value pairs, a dictionary of {key: data_type} passed to dtype argument will change the value for every key with the data type, and raise an error if not applicable. |
None |
Usage:
from clumper import Clumper
clump = Clumper.read_csv("tests/data/monopoly.csv")
assert len(clump) == 22
clump = Clumper.read_csv("tests/data/monopoly.csv", n = 10)
assert len(clump) == 10
clump = Clumper.read_csv("https://calmcode.io/datasets/monopoly.csv")
assert len(clump) == 22
# If the fieldnames argument is not None, then the first row becomes part of the data.
fieldnames = ['date', 'currency', 'country', 'price', 'dollar_rate', 'cost']
clump = Clumper.read_csv("https://calmcode.io/datasets/bigmac.csv", fieldnames=fieldnames)
first_row = ['date', 'currency_code','name','local_price', 'dollar_ex', 'dollar_price']
assert clump.head(1).equals([dict(zip(fieldnames, first_row))])
read_json(path, n=None, listify=True, add_path=False)
(classmethod)¶
Show source code in clumper/clump.py
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 |
|
Reads in a json file. Can also read files from url.
Parameters
Name | Type | Description | Default |
---|---|---|---|
path |
filename, url, pathlib.Path or list of pathlib.Path . Filenames can include a wildcard * . |
required | |
n |
Number of rows to read in. Useful when reading large files. If None , all rows are read. |
None |
|
listify |
if the input is a single json dictionary, turn it into a list with that dictionary inside of it before passing it along to the Clumper. | True |
|
add_path |
Adds the name of the read path to each item in the Clumper. Is useful when using wildcards to read in multiple files at once. | False |
Usage:
from clumper import Clumper
clump = Clumper.read_json("tests/data/pokemon.json")
assert len(clump) == 800
clump = Clumper.read_json("https://calmcode.io/datasets/got.json")
assert len(clump) == 30
clump = Clumper.read_json("https://calmcode.io/datasets/got.json", n=10)
assert len(clump) == 10
read_jsonl(path, n=None, listify=True, add_path=False)
(classmethod)¶
Show source code in clumper/clump.py
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 |
|
Reads in a jsonl file. Can also read files from url.
Parameters
Name | Type | Description | Default |
---|---|---|---|
path |
filename, url, pathlib.Path or list of pathlib.Path . Filenames can include a wildcard * . |
required | |
n |
Number of rows to read in. Useful when reading large files. If None , all rows are read. |
None |
|
listify |
if the input is a single json dictionary, turn it into a list with that dictionary inside of it before passing it along to the Clumper. | True |
|
add_path |
Adds the name of the filepath to each item in the Clumper. Is useful when using wildcards to read in multiple files at once. | False |
Usage:
from clumper import Clumper
clump = Clumper.read_jsonl("tests/data/cards.jsonl")
assert len(clump) == 4
clump = Clumper.read_jsonl("https://calmcode.io/datasets/pokemon.jsonl")
assert len(clump) == 800
clump = Clumper.read_jsonl("https://calmcode.io/datasets/pokemon.jsonl", n=10)
assert len(clump) == 10
read_yaml(path, n=None, listify=True, add_path=False)
(classmethod)¶
Show source code in clumper/clump.py
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 |
|
Reads in a yaml file.
Parameters
Name | Type | Description | Default |
---|---|---|---|
path |
filename, url, pathlib.Path or list of pathlib.Path . Filenames can include a wildcard * . |
required | |
n |
number of lines to read in, if None will read all |
None |
|
listify |
if the input is a single json dictionary, turn it into a list with that dictionary inside of it before passing it along to the Clumper. | True |
|
add_path |
Adds the name of the filepath to each item in the Clumper. Is useful when using wildcards to read in multiple files at once. | False |
Important
This method requires the PyYAML
dependency which is not installed automatically.
To install it you can run;
# This will only install the yaml dependencies.
pip install clumper[yaml]
# This will install all optional dependencies.
pip install clumper[all]
Usage:
from clumper import Clumper
clump = Clumper.read_yaml("tests/data/demo-flat-1.yaml")
assert len(clump) == 3
clump = Clumper.read_yaml("tests/data/demo-flat-*.yaml")
assert len(clump) == 6
reduce(self, **kwargs)
¶
Show source code in clumper/clump.py
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 |
|
Reduce the collection using reducing functions.
Parameters
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
key-function pairs | {} |
Usage:
from clumper import Clumper
list_ints = [1, 2, 3, 4, 5]
(Clumper(list_ints)
.reduce(sum_a = lambda x,y: x + y,
min_a = lambda x,y: min(x, y),
max_a = lambda x,y: max(x, y))
.collect())
rename(self, **kwargs)
¶
Show source code in clumper/clump.py
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 |
|
Rename items in the collection.
Usage:
from clumper import Clumper
data = [{'a': 1, 'b': 3}, {'a': 2, 'b': 4}]
clumper = Clumper(data).rename(c="b")
expected = [{'a': 1, 'c': 3}, {'a': 2, 'c': 4}]
assert clumper.equals(expected)
sample(self, n, replace, random_state=None, weights=None)
¶
Show source code in clumper/clump.py
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 |
|
Samples n data from the collection
Parameters
Name | Type | Description | Default |
---|---|---|---|
n |
int |
The number of items to sample | required |
replace |
bool |
Have duplicate items or not. Defaults to False. | required |
weights |
str |
The key used for calculate sample probability. Defaults to None which means equal probability | None |
random_state |
Optional[int] |
Random seed for reproducible results. Defaults to None. | None |
Exceptions
Type | Description |
---|---|
ValueError |
Raises error when sampling more than size of collection |
Returns
Type | Description |
---|---|
`` | Clumper: Sampled Clumper instance |
sample_frac(self, frac, replace, random_state=None, weights=None)
¶
Show source code in clumper/clump.py
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 |
|
Samples fraction of items from the collection
Parameters
Name | Type | Description | Default |
---|---|---|---|
frac |
float |
: The fraction of items to sample | required |
replace |
bool |
Have duplicate items or not. Defaults to False. | required |
weights |
str |
The key(s) used for calculate sample probability. Defaults to None which means equal probability | None |
random_state |
Optional[int] |
Random seed for reproducible results. Defaults to None. | None |
select(self, *keys)
¶
Show source code in clumper/clump.py
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 |
|
Selects a subset of the keys in each item in the collection.
Parameters
Name | Type | Description | Default |
---|---|---|---|
*keys |
the keys to keep | () |
Usage:
from clumper import Clumper
list_dicts = [
{'a': 1, 'b': 2},
{'a': 2, 'b': 3, 'c':4},
{'a': 1, 'b': 6}]
clump = Clumper(list_dicts).select('a', 'b')
assert all(["c" not in d.keys() for d in clump])
show(self, n=1, name=None)
¶
Show source code in clumper/clump.py
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 |
|
Prints the first n
items in the clumper as an example. Very useful for debugging!
This method requires rich if you want the pretty output.
from clumper import Clumper
data = [{"n": 123, "data": [1, 2, 3], "maintainer": "Vincent"}]
Clumper(data).show(n=1, name="Before").explode("data").show(n=3, name="After")
sort(self, key, reverse=False)
¶
Show source code in clumper/clump.py
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 |
|
Allows you to sort the collection of dictionaries.
Parameters
Name | Type | Description | Default |
---|---|---|---|
key |
the number of items to grab | required | |
reverse |
the number of items to grab | False |
Warning
This method is aware of groups. Expect different results if a group is active.
Usage:
from clumper import Clumper
list_dicts = [
{'a': 1, 'b': 2},
{'a': 3, 'b': 3},
{'a': 2, 'b': 1}]
(Clumper(list_dicts)
.sort(lambda d: d['a'])
.collect())
(Clumper(list_dicts)
.sort(lambda d: d['b'], reverse=True)
.collect())
sum(self, col)
¶
Show source code in clumper/clump.py
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 |
|
Give the sum of the values that belong to a key.
Usage:
from clumper import Clumper
list_of_dicts = [
{'a': 7},
{'a': 2, 'b': 7},
{'a': 3, 'b': 6},
{'a': 2, 'b': 7}
]
Clumper(list_of_dicts).sum("a")
Clumper(list_of_dicts).sum("b")
summarise_col(self, func, key)
¶
Show source code in clumper/clump.py
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 |
|
Apply your own summary function to a key in the collection.
It can also accept a string and it will try to fetch an appropriate function
for you. If you pass a string it must be either: mean
, count
, unique
,
n_unique
, sum
, min
, max
, median
, values
, var
, std
, first
or last
.
Note that this method ignores groups. It also does not return a Clumper
collection.
Usage:
from clumper import Clumper
clump = Clumper([{"a": 1}, {"a": 2}, {"a": 3}])
assert clump.summarise_col("last", "a") == 3
assert clump.summarise_col(lambda d: d[-1], "a") == 3
tail(self, n=5)
¶
Show source code in clumper/clump.py
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 |
|
Selects the bottom n
items from the collection.
Parameters
Name | Type | Description | Default |
---|---|---|---|
n |
the number of items to grab | 5 |
Usage:
from clumper import Clumper
list_dicts = [{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}]
result = Clumper(list_dicts).tail(2)
expected = [{'a': 3}, {'a': 4}]
assert result.equals(expected)
transform(self, **kwargs)
¶
Show source code in clumper/clump.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 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 |
|
Does an aggregation just like .agg()
however instead of reducing the rows we
merge the results back with the original data. This saves a lot of compute time
because effectively this prevents us from performing a join.
Parameters
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
keyword arguments that represent the aggregation that is about to happen, see usage below. | {} |
Warning
This method is aware of groups. There may be different results if a group is active.
Usage:
from clumper import Clumper
data = [
{"a": 6, "grp": "a"},
{"a": 2, "grp": "b"},
{"a": 7, "grp": "a"},
{"a": 9, "grp": "b"},
{"a": 5, "grp": "a"}
]
tfm_clump = (Clumper(data)
.group_by("grp")
.transform(s=("a", "sum"),
u=("a", "unique")))
expected = [
{'a': 6, 'grp': 'a', 's': 18, 'u': [5, 6, 7]},
{'a': 7, 'grp': 'a', 's': 18, 'u': [5, 6, 7]},
{'a': 5, 'grp': 'a', 's': 18, 'u': [5, 6, 7]},
{'a': 2, 'grp': 'b', 's': 11, 'u': [9, 2]},
{'a': 9, 'grp': 'b', 's': 11, 'u': [9, 2]}
]
assert tfm_clump.equals(expected)
ungroup(self)
¶
Show source code in clumper/clump.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 |
|
Removes all grouping from the collection.
from clumper import Clumper
clump = Clumper([{"a": 1}]).group_by("a")
assert clump.groups == ("a", )
assert clump.ungroup().groups == tuple()
unique(self, col)
¶
Show source code in clumper/clump.py
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 |
|
Returns a set of unique values that a key has.
Usage:
from clumper import Clumper
list_of_dicts = [
{'a': 7},
{'a': 2, 'b': 7},
{'a': 3, 'b': 6},
{'a': 2, 'b': 7}
]
assert Clumper(list_of_dicts).unique("a") == [2, 3, 7]
assert Clumper(list_of_dicts).unique("b") == [6, 7]
unpack(self, name)
¶
Show source code in clumper/clump.py
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 |
|
Unpacks a nested list of dictionaries.
Parameters
Name | Type | Description | Default |
---|---|---|---|
name |
the name of the column to unpack | required |
from clumper import Clumper
list_dicts = {
'a': 1,
'rows': [{'b': 2, 'c': 3}, {'b': 3}, {'b': 4}]
}
result = Clumper(list_dicts).unpack('rows').collect()
expected = [
{'a': 1, 'b': 2, 'c': 3},
{'a': 1, 'b': 3},
{'a': 1, 'b': 4}
]
assert result == expected
write_csv(self, path, mode='w')
¶
Show source code in clumper/clump.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 |
|
Write to a csv file.
Parameters
Name | Type | Description | Default |
---|---|---|---|
path: filename
mode: w
writes to a file if it does not exist, or overwrites if it already exists,
while a
: - append to file if it already exists. The default is w
.
Note that null values will be exported as empty strings; this is the convention chosen by Python.
Usage:
from clumper import Clumper
from pathlib import Path
path = '/tmp/monopoly.csv'
Clumper.read_csv("tests/data/monopoly.csv").write_csv(path)
reader = Clumper.read_csv(path)
assert Clumper.read_csv("tests/data/monopoly.csv").collect() == reader.collect()
write_json(self, path, sort_keys=False, indent=None)
¶
Show source code in clumper/clump.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 |
|
Writes to a json file.
Parameters
Name | Type | Description | Default |
---|---|---|---|
path |
filename | required | |
sort_keys |
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key. | False |
|
indent |
If indent is a non-negative integer (default: None), then JSON array elements members will be pretty-printed with that indent level. | None |
Usage:
from clumper import Clumper
clump_orig = Clumper.read_json("tests/data/pokemon.json")
clump_orig.write_json("tests/data/pokemon_copy.json")
clump_copy = Clumper.read_json("tests/data/pokemon_copy.json")
assert clump_copy.collect() == clump_orig.collect()
write_jsonl(self, path, sort_keys=False, indent=None)
¶
Show source code in clumper/clump.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 |
|
Writes to a jsonl file.
Parameters
Name | Type | Description | Default |
---|---|---|---|
path |
filename | required | |
sort_keys |
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key. | False |
|
indent |
If indent is a non-negative integer (default: None), then JSON array elements members will be pretty-printed with that indent level. | None |
write_yaml(self, path)
¶
Show source code in clumper/clump.py
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 |
|
Write the collection of data as a yaml file.
Parameters
Name | Type | Description | Default |
---|---|---|---|
path |
path to write the file to | required |
Important
This method requires the PyYAML
dependency which is not installed automatically.
To install it you can run;
# This will only install the yaml dependencies.
pip install clumper[yaml]
# This will install all optional dependencies.
pip install clumper[all]
Usage:
from clumper import Clumper
clump_orig = Clumper.read_yaml("tests/data/demo-flat-1.yaml")
clump_orig.write_json("tests/data/demo-flat-copy.json")
clump_copy = Clumper.read_json("tests/data/demo-flat-copy.json")
assert clump_copy.collect() == clump_orig.collect()