Dictionaries and dataframes#
Needing a better way of ordering dictionaries was one of the original inspirations for Sciris back in 2014. In those dark days of Python <=3.6, dictionaries were unordered, which meant that dict.keys() could give you anything. (And you still can’t do dict.keys()[0], much less dict[0]). This tutorial describes Sciris’ ordered dict, the odict, its close cousin the objdict, and its pandas-powered pseudorelative, the dataframe.
Click here to open an interactive version of this notebook.
The odict#
In basically every situation except one, an odict can be used like a dict. (Since this is a tutorial, see if you can intuit what that one situation is!) For example, creating an odictworks just like creating a regular dict:
[1]:
import sciris as sc
od = sc.odict(a=['some', 'strings'], b=[1,2,3])
print(od)
#0: 'a': ['some', 'strings']
#1: 'b': [1, 2, 3]
Okay, it doesn’t exactly look like a dict, but it is one:
[2]:
print(f'Keys: {od.keys()}')
print(f'Values: {od.values()}')
print(f'Items: {od.items()}')
Keys: ['a', 'b']
Values: [['some', 'strings'], [1, 2, 3]]
Items: [('a', ['some', 'strings']), ('b', [1, 2, 3])]
Looks pretty much the same as a regular dict, except that od.keys() returns a regular list (so, yes, you can do od.keys()[0]). But, you can do things you can’t do with a regular dict, such as:
[3]:
for i,k,v in od.enumitems():
print(f'Item {i} is called {k} and has value {v}')
Item 0 is called a and has value ['some', 'strings']
Item 1 is called b and has value [1, 2, 3]
We can, as you probably guessed, also retrieve items by index as well:
[4]:
print(od['a'])
print(od[0])
['some', 'strings']
['some', 'strings']
Remember the question about the situation where you wouldn’t use an odict? The answer is if your dict has integer keys, then although you still could use an odict, it’s probably best to use a regular dict. But even float keys are fine to use (if somewhat strange).
You might’ve noticed that the odict has more verbose output than a regular dict. This is because its primary purpose is as a high-level container for storing large(ish) objects.
For example, let’s say we want to store a number of named simulation results. Look at how we’re able to leverage the odict in the loop that creates the plots
[5]:
import numpy as np
import matplotlib.pyplot as plt
class Sim:
def __init__(self, n=20, n_factors=6):
self.results = sc.odict()
self.n = n
self.n_factors = n_factors
def run(self):
for i in range(self.n_factors):
label = f'y = N^{i+1}'
result = np.random.randn(self.n)**(i+1)
self.results[label] = result
def plot(self):
with sc.options.context(jupyter=True): # Jupyter-optimized plotting
plt.figure()
rows,cols = sc.getrowscols(len(self.results))
for i,label,result in self.results.enumitems(): # odict magic!
plt.subplot(rows, cols, i+1)
plt.scatter(np.arange(self.n), result, c=result, cmap='parula')
plt.title(label)
sc.figlayout() # Trim whitespace from the figure
sim = Sim()
sim.run()
sim.plot()
We can quickly access these results for exploratory data analysis without having to remember and type the labels explicitly:
[6]:
print('Sim results are')
print(sim.results)
print('The first set of results is')
print(sim.results[0])
print('The first set of results has median')
sc.printmedian(sim.results[0])
Sim results are
#0: 'y = N^1':
array([-0.87763341, -0.31835845, 1.46325544, 0.52531378, 0.9983846 ,
1.9793977 , 0.77661481, -1.41850138, 0.52374861, -2.29867331,
-0.2299808 , -0.58182673, -0.32177392, -2.23960449, -0.26865499,
-0.14823349, -0.59793575, 0.5210056 , 0.39925402, -0.63161542])
#1: 'y = N^2':
array([1.92508611e+00, 4.36861452e-02, 1.75177350e+00, 2.37328226e+00,
8.05400802e-02, 3.57215106e+00, 2.16194337e-01, 4.21346559e+00,
1.61661034e-01, 7.58172077e-02, 3.75514875e-01, 8.45351743e-01,
1.45774789e+00, 4.89023763e-01, 3.18219234e-04, 3.17855690e-01,
7.87031201e-03, 1.38043576e+00, 6.44272038e-01, 3.04063829e-01])
#2: 'y = N^3':
array([-1.50669524e+01, -2.58771482e+00, -4.38023791e-04, 4.19771027e-01,
2.55908418e+00, -3.33752760e-01, -1.18301396e-01, 3.27269324e-01,
3.12028144e+00, 5.90612526e-01, -1.32824217e+01, -6.24523302e-02,
4.92037259e+00, -1.01192314e+00, 2.58619064e+00, 1.90127850e-03,
-8.81442970e-01, 7.22959558e-02, 5.04939157e+00, -6.75772152e+00])
#3: 'y = N^4':
array([4.02226526e-01, 2.35567820e-06, 2.48508564e-03, 4.32289571e-03,
6.31050775e-03, 1.23772291e+01, 1.69268354e+00, 1.88146629e+00,
1.22452837e-04, 7.10651748e+00, 1.06811564e-02, 1.82289869e-01,
1.04220162e+00, 2.67886509e+01, 8.66941697e-07, 9.63602256e-03,
2.55288954e-01, 1.46479809e-01, 8.70183625e-02, 2.51231804e-01])
#4: 'y = N^5':
array([-1.09411353e-02, -1.26544549e-05, -1.88794609e+01, 6.46131315e+00,
2.20513667e-01, -3.17659108e-01, 3.48223717e-01, -2.97946705e-02,
1.19000621e+01, -3.79955519e+00, -1.36210444e+00, -1.92638239e-02,
4.99049815e+00, 1.43294112e-04, -4.57687447e-05, 5.00449874e-02,
9.57253993e-02, 3.31102932e-01, 1.92664044e-01, -8.25871637e-01])
#5: 'y = N^6':
array([9.47885834e-02, 1.11841099e+01, 3.07954690e+01, 4.03210298e+00,
3.28572565e-02, 1.24370923e-05, 1.24111010e-01, 1.40906948e-01,
2.51844505e-08, 3.31257397e-01, 8.04394780e-01, 7.34012530e-03,
2.49422356e-02, 1.73196887e-04, 5.30277983e+01, 8.16708903e-01,
5.43865959e+00, 1.21513552e+01, 8.35069302e-02, 1.44748505e-02])
The first set of results is
[-0.87763341 -0.31835845 1.46325544 0.52531378 0.9983846 1.9793977
0.77661481 -1.41850138 0.52374861 -2.29867331 -0.2299808 -0.58182673
-0.32177392 -2.23960449 -0.26865499 -0.14823349 -0.59793575 0.5210056
0.39925402 -0.63161542]
The first set of results has median
-0.249 (95% CI: -2.271, 1.734)
This is a have-your-cake-and-eat-it-too situation: the first set of results is correctly labeled (sim.results['y = N^1']), but you can easily access it without having to type all that (sim.results[0]).
The objdict#
When you’re just writing throwaway analysis code, it can be a pain to type mydict['key1']['key2'] over and over. (Right-pinky overuse is a real medical issue.) Wouldn’t it be nice if you could just type mydict.key1.key2, but otherwise have everything work exactly like a dict? This is where the objdict comes in: it’s identical to an odict (and hence like a regular dict), except you can use “object syntax” (a.b)
instead of “dict syntax” (a['b']). This is especially handy for using f-strings, since you don’t have to worry about nested quotes:
[7]:
ob = sc.objdict(key1=['some', 'strings'], key2=[1,2,3])
print(f'Checking {ob[0] = }')
print(f'Checking {ob.key1 = }')
print(f'Checking {ob["key1"] = }') # We need to use double-quotes inside since single quotes are taken!
Checking ob[0] = ['some', 'strings']
Checking ob.key1 = ['some', 'strings']
Checking ob["key1"] = ['some', 'strings']
In most cases, you probably want to use objdicts rather than odicts just to have the extra flexibility. Why would you ever use an odict over an objdict? Mostly just because there’s small but nonzero overhead in doing the extra attribute checking: odict is faster (faster than even collections.OrderedDict, though slower than a plain dict). The differences are tiny (literally nanoseconds) so won’t matter unless you’re doing millions of operations. But if you’re
reading this, chances are high that you do sometimes need to do millions of dict operations.
Dataframes#
The Sciris sc.dataframe() works exactly like pandas pd.DataFrame(), with a couple extra features, mostly to do with creation, indexing, and manipulation.
Dataframe creation#
Any valid pandas dataframe initialization works exactly the same in Sciris. However, Sciris is a bit more flexible about how you can create the dataframe, again optimized for letting you make them quickly with minimal code. For example:
[8]:
import pandas as pd
x = ['a','b','c']
y = [1, 2, 3]
z = [1, 0, 1]
df = pd.DataFrame(dict(x=x, y=y, z=z)) # Pandas
df = sc.dataframe(x=x, y=y, z=z) # Sciris
It’s not a huge difference, but the Sciris one is shorter. Sciris also makes it easier to define types on dataframe creation:
[9]:
df = sc.dataframe(x=x, y=y, z=z, dtypes=[str, float, bool])
print(df)
x y z
0 a 1.0 True
1 b 2.0 False
2 c 3.0 True
You can also define data types along with the columns:
[10]:
columns = dict(x=str, y=float, z=bool)
data = [
['a', 1, 1],
['b', 2, 0],
['c', 3, 1],
]
df = sc.dataframe(columns=columns, data=data)
df.disp()
x y z
0 a 1.0 True
1 b 2.0 False
2 c 3.0 True
The df.disp() command will do its best to show the full dataframe. By default, Sciris dataframes (just like pandas) are shown in abbreviated form:
[11]:
df = sc.dataframe(data=np.random.rand(70,10))
print(df)
0 1 2 3 4 5 6 \
0 0.959060 0.154389 0.594912 0.441297 0.462495 0.070671 0.450671
1 0.642012 0.953458 0.977862 0.265276 0.556378 0.699099 0.895814
2 0.861379 0.843331 0.370967 0.313029 0.788156 0.750997 0.331664
3 0.716154 0.564038 0.832865 0.470850 0.184281 0.508012 0.996534
4 0.643615 0.253633 0.958300 0.207989 0.003424 0.480508 0.730362
.. ... ... ... ... ... ... ...
65 0.112503 0.373253 0.656367 0.408935 0.095057 0.917785 0.892556
66 0.622859 0.739327 0.768028 0.958543 0.045198 0.016509 0.962414
67 0.760464 0.666923 0.061258 0.755947 0.512430 0.101700 0.293517
68 0.106929 0.810557 0.654563 0.191119 0.247890 0.147165 0.220854
69 0.297478 0.552760 0.930208 0.451868 0.618258 0.341047 0.728169
7 8 9
0 0.341964 0.276781 0.580498
1 0.570995 0.168934 0.151831
2 0.893334 0.196191 0.443537
3 0.862476 0.399121 0.723289
4 0.862987 0.391175 0.829896
.. ... ... ...
65 0.569537 0.442903 0.731324
66 0.818776 0.934116 0.435791
67 0.152481 0.216069 0.646468
68 0.968112 0.206750 0.265089
69 0.787726 0.692938 0.082917
[70 rows x 10 columns]
But sometimes you just want to see the whole thing. The official way to do it in pandas is with pd.options_context, but this is a lot of effort if you’re just poking around in a script or terminal (which, if you’re printing a dataframe, you probably are). By default, df.disp() shows the whole damn thing:
[12]:
df.disp()
0 1 2 3 4 5 6 7 8 9
0 0.9591 0.1544 0.5949 0.4413 0.4625 0.0707 0.4507 0.3420 0.2768 0.5805
1 0.6420 0.9535 0.9779 0.2653 0.5564 0.6991 0.8958 0.5710 0.1689 0.1518
2 0.8614 0.8433 0.3710 0.3130 0.7882 0.7510 0.3317 0.8933 0.1962 0.4435
3 0.7162 0.5640 0.8329 0.4708 0.1843 0.5080 0.9965 0.8625 0.3991 0.7233
4 0.6436 0.2536 0.9583 0.2080 0.0034 0.4805 0.7304 0.8630 0.3912 0.8299
5 0.9868 0.2921 0.0225 0.0532 0.2117 0.2608 0.6075 0.0056 0.6839 0.2392
6 0.9733 0.4503 0.5473 0.2714 0.2992 0.4699 0.2741 0.1760 0.1338 0.8547
7 0.5107 0.8611 0.9193 0.4034 0.4200 0.7881 0.2742 0.3468 0.1171 0.9522
8 0.6535 0.0940 0.5656 0.9839 0.2496 0.8816 0.9018 0.0191 0.7128 0.0110
9 0.8945 0.7393 0.6722 0.2939 0.8224 0.2456 0.8009 0.8677 0.4557 0.9197
10 0.8566 0.1187 0.1297 0.9605 0.8648 0.3432 0.9914 0.0012 0.7828 0.1482
11 0.9071 0.1319 0.4723 0.2531 0.4221 0.8654 0.5108 0.4525 0.5205 0.4396
12 0.6814 0.2757 0.3285 0.1242 0.6098 0.4735 0.3904 0.7223 0.9303 0.3516
13 0.1599 0.8475 0.2860 0.6191 0.0006 0.1386 0.6671 0.0456 0.0382 0.2971
14 0.8598 0.5689 0.0717 0.4572 0.5335 0.4286 0.5840 0.3755 0.5113 0.7951
15 0.9892 0.4360 0.0855 0.7481 0.1923 0.2418 0.9810 0.7369 0.7582 0.7938
16 0.8876 0.0273 0.9433 0.6062 0.9758 0.1800 0.9543 0.3237 0.1271 0.8086
17 0.4935 0.6781 0.0181 0.8145 0.6805 0.9845 0.1361 0.5169 0.6946 0.9923
18 0.5791 0.8209 0.2713 0.1784 0.8889 0.1563 0.3974 0.8222 0.1882 0.5074
19 0.1599 0.9361 0.9987 0.8452 0.7409 0.8139 0.5994 0.1466 0.1782 0.9208
20 0.2342 0.8149 0.0624 0.0259 0.2431 0.1088 0.0984 0.6407 0.1982 0.3424
21 0.0043 0.1604 0.6224 0.1411 0.0384 0.0261 0.1500 0.0158 0.0437 0.6182
22 0.7724 0.2174 0.6822 0.9482 0.9285 0.0741 0.5717 0.9367 0.0490 0.7352
23 0.4011 0.2520 0.0397 0.6397 0.5595 0.8573 0.6370 0.2949 0.4950 0.6168
24 0.0207 0.0482 0.5567 0.6872 0.1930 0.5947 0.3867 0.9144 0.7411 0.1623
25 0.9114 0.7923 0.1177 0.4840 0.1676 0.0733 0.7539 0.2263 0.9390 0.4479
26 0.9809 0.9294 0.8183 0.8143 0.9947 0.7608 0.2602 0.9019 0.3860 0.7108
27 0.4270 0.4535 0.6520 0.5003 0.0738 0.6410 0.4928 0.8883 0.9825 0.3663
28 0.1211 0.8870 0.7848 0.7482 0.5651 0.0049 0.4270 0.5594 0.9544 0.8246
29 0.8800 0.3341 0.0312 0.0632 0.7450 0.4721 0.1418 0.1178 0.3920 0.1385
30 0.8083 0.1547 0.3325 0.1777 0.6926 0.1994 0.8627 0.5730 0.1480 0.5505
31 0.6953 0.6209 0.6453 0.4869 0.5597 0.2662 0.0867 0.5781 0.9416 0.1204
32 0.1153 0.8584 0.3797 0.3321 0.7554 0.8710 0.0325 0.2080 0.0603 0.8172
33 0.0267 0.1247 0.1999 0.3117 0.3904 0.7169 0.8349 0.8094 0.8419 0.2741
34 0.5567 0.8670 0.4984 0.5111 0.0569 0.3287 0.2242 0.2303 0.8400 0.3482
35 0.8707 0.3078 0.2551 0.5164 0.7669 0.1184 0.0814 0.2438 0.8189 0.5074
36 0.7073 0.6661 0.0135 0.1298 0.4009 0.1116 0.1348 0.5739 0.2091 0.7790
37 0.5888 0.5660 0.0697 0.6210 0.5036 0.3226 0.4445 0.2217 0.8669 0.6582
38 0.0738 0.1884 0.1320 0.3355 0.4312 0.3854 0.8123 0.1821 0.5852 0.2985
39 0.5125 0.2258 0.3382 0.3923 0.5342 0.8737 0.5775 0.0409 0.9197 0.1381
40 0.6693 0.1977 0.2983 0.8567 0.7977 0.1956 0.5899 0.2763 0.7240 0.7686
41 0.0358 0.1638 0.2044 0.6315 0.5552 0.0506 0.0230 0.1711 0.5142 0.0788
42 0.2176 0.2053 0.0301 0.2836 0.4439 0.7799 0.9533 0.8631 0.7290 0.1994
43 0.4864 0.5346 0.1946 0.0259 0.9247 0.3340 0.8154 0.3135 0.6447 0.0349
44 0.9578 0.4219 0.3840 0.4115 0.1204 0.7749 0.1435 0.6328 0.5611 0.0435
45 0.8345 0.0457 0.8767 0.9106 0.1954 0.0823 0.2413 0.9990 0.6766 0.8547
46 0.0470 0.0874 0.9971 0.0709 0.2932 0.2936 0.9846 0.3202 0.4486 0.0920
47 0.5752 0.3233 0.1390 0.8205 0.7816 0.9639 0.4311 0.7139 0.2207 0.0541
48 0.0925 0.1281 0.1291 0.1734 0.7320 0.9063 0.5285 0.3917 0.3693 0.9884
49 0.5468 0.8034 0.1688 0.0617 0.7102 0.4958 0.7608 0.5790 0.4986 0.0365
50 0.0496 0.5125 0.6833 0.2239 0.5838 0.6509 0.1832 0.5170 0.7100 0.7857
51 0.5115 0.8750 0.6040 0.3544 0.3330 0.1544 0.8328 0.4032 0.6144 0.9491
52 0.2699 0.3398 0.7129 0.8584 0.1497 0.0889 0.3791 0.0493 0.1383 0.6733
53 0.4850 0.5024 0.2498 0.6135 0.9186 0.2477 0.2366 0.2050 0.8758 0.0929
54 0.6755 0.3131 0.5204 0.2020 0.2189 0.4378 0.7431 0.6138 0.5207 0.3365
55 0.4122 0.8656 0.8676 0.8196 0.9982 0.2520 0.8137 0.7350 0.7367 0.7683
56 0.2449 0.9119 0.7529 0.1935 0.0231 0.5950 0.2072 0.5003 0.1499 0.6813
57 0.8225 0.4833 0.1735 0.9759 0.2649 0.0241 0.9703 0.4998 0.9507 0.8789
58 0.3327 0.4333 0.2119 0.5350 0.1847 0.5966 0.7100 0.0250 0.2546 0.0478
59 0.3340 0.7097 0.2085 0.7213 0.2050 0.4310 0.9824 0.7629 0.7232 0.9570
60 0.6414 0.2771 0.6506 0.2961 0.5586 0.9201 0.1951 0.6646 0.3627 0.6129
61 0.2186 0.3378 0.5223 0.0248 0.4418 0.5313 0.1326 0.8009 0.2551 0.7337
62 0.4515 0.5575 0.4974 0.1698 0.7194 0.3936 0.7236 0.5353 0.4815 0.4988
63 0.7598 0.1481 0.7451 0.4200 0.6538 0.5688 0.4528 0.6740 0.6981 0.9173
64 0.2318 0.5380 0.3464 0.9175 0.2968 0.2295 0.3686 0.9812 0.6417 0.1714
65 0.1125 0.3733 0.6564 0.4089 0.0951 0.9178 0.8926 0.5695 0.4429 0.7313
66 0.6229 0.7393 0.7680 0.9585 0.0452 0.0165 0.9624 0.8188 0.9341 0.4358
67 0.7605 0.6669 0.0613 0.7559 0.5124 0.1017 0.2935 0.1525 0.2161 0.6465
68 0.1069 0.8106 0.6546 0.1911 0.2479 0.1472 0.2209 0.9681 0.2067 0.2651
69 0.2975 0.5528 0.9302 0.4519 0.6183 0.3410 0.7282 0.7877 0.6929 0.0829
You can also pass other options if you want to customize it further:
[13]:
df.disp(precision=1, ncols=5, nrows=10, colheader_justify='left')
0 1 ... 8 9
0 1.0 0.2 ... 0.3 5.8e-01
1 0.6 1.0 ... 0.2 1.5e-01
2 0.9 0.8 ... 0.2 4.4e-01
3 0.7 0.6 ... 0.4 7.2e-01
4 0.6 0.3 ... 0.4 8.3e-01
.. ... ... ... ... ...
65 0.1 0.4 ... 0.4 7.3e-01
66 0.6 0.7 ... 0.9 4.4e-01
67 0.8 0.7 ... 0.2 6.5e-01
68 0.1 0.8 ... 0.2 2.7e-01
69 0.3 0.6 ... 0.7 8.3e-02
[70 rows x 10 columns]
Dataframe indexing#
All the regular pandas methods (df['mycol'], df.mycol, df.loc, df.iloc, etc.) work exactly the same. But Sciris gives additional options for indexing. Specifically, getitem commands (what happens under the hood when you call df[thing]) will first try the standard pandas getitem, but then fall back to iloc if that fails. For example:
[14]:
df = sc.dataframe(
x = [1, 2, 3],
values = [45, 23, 37],
valid = [1, 0, 1]
)
sc.heading('Regular pandas indexing')
print(df['values',1])
sc.heading('Pandas-like iloc indexing')
print(df.iloc[1])
sc.heading('Automatic iloc indexing')
print(df[1]) # Would be a KeyError in regular pandas
———————————————————————
Regular pandas indexing
———————————————————————
23
—————————————————————————
Pandas-like iloc indexing
—————————————————————————
x 2
values 23
valid 0
Name: 1, dtype: int64
———————————————————————
Automatic iloc indexing
———————————————————————
x 2
values 23
valid 0
Name: 1, dtype: int64
Dataframe manipulation#
One quirk of pandas dataframes is that almost every operation creates a copy rather than modifies the original dataframe in-place (leading to the infamous SettingWithCopyWarning.) This is extremely helpful, and yet, sometimes you do want to modify a dataframe in place. For example, to append a row:
[15]:
# Create the dataframe
df = sc.dataframe(
x = ['a','b','c'],
y = [1, 2, 3],
z = [1, 0, 1],
)
# Define the new row
newrow = ['d', 4, 0]
# Append it in-place
df.appendrow(newrow)
# Show the result
print(df)
x y z
0 a 1 1
1 b 2 0
2 c 3 1
3 d 4 0
That was easy! For reference, here’s the pandas equivalent (since append was deprecated):
[16]:
# Convert to a vanilla dataframe
pdf = df.to_pandas()
# Define the new row
newrow = ['e', 5, 1]
# Append it
pdf = pd.concat([pdf, pd.DataFrame([newrow], columns=pdf.columns)])
That’s rather a pain to type, and if you mess up (e.g. type newrow instead of [newrow]), in some cases it won’t even fail, just give you the wrong result! Crikey.
Just like how sc.cat() will take anything vaguely arrayish and turn it into an actual array, sc.dataframe.cat() will do the same thing:
[17]:
df = sc.dataframe.cat(
sc.dataframe(x=['a','b'], y=[1,2]), # Actual dataframe
dict(x=['c','d'], y=[3,4]), # Dict of data
[['e',5], ['f', 6]], # Or just the data!
)
print(df)
x y
0 a 1
1 b 2
2 c d
3 3 4
4 e 5
5 f 6