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 odict
works 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([ 1.92013546, 0.50119386, -0.85598426, 1.44799103, 1.63065172,
1.95591239, -1.07810631, -1.06883157, 0.53221628, -0.50083637,
0.80984049, -1.32364548, 1.32708961, 1.11797332, 0.42746811,
-0.76855719, 0.02324697, 0.36627675, 0.2483084 , 0.720024 ])
#1: 'y = N^2':
array([7.71541258e+00, 3.43265605e-02, 2.01534313e-01, 2.37822357e+00,
4.80815869e-02, 1.29560019e-04, 2.94363019e-01, 1.48081364e-02,
8.67602024e-01, 1.99471887e+00, 6.83204688e-01, 2.68699706e-02,
1.52322699e-01, 8.36067245e-01, 8.22742115e-01, 1.43375760e+00,
1.26514604e-02, 1.21329484e-01, 5.59610405e-01, 1.09157058e-01])
#2: 'y = N^3':
array([-6.96842692e-03, 5.56842717e+00, 8.37130919e-03, -1.45267393e-01,
2.02962949e+00, 9.26498109e-01, 3.48177534e+00, 1.73404279e-01,
1.54507322e+00, -2.11315185e-03, 1.89883107e+00, 5.30533115e+00,
7.70560427e-02, -5.83573204e-02, 1.36469416e+00, -7.68143329e+00,
-1.52106983e+00, 1.76217815e+00, 9.15304224e+00, 4.87079968e-01])
#3: 'y = N^4':
array([1.02458897e+00, 5.71874696e-07, 6.42864047e-01, 4.82656562e-05,
4.19214988e-02, 1.50615461e-01, 4.42824001e-01, 9.61070197e-05,
7.48373153e-03, 2.13206414e+00, 2.63807554e-01, 2.67427234e-04,
1.82189806e+01, 1.22514402e-02, 3.02542365e-05, 9.63466121e-04,
1.53537645e+01, 2.01791507e-02, 2.77520884e-02, 1.85329321e-01])
#4: 'y = N^5':
array([ 9.32001036e-03, -7.06476538e-03, -1.67935785e-01, -7.95550343e-05,
1.36230370e-01, 1.05736624e-01, -9.72029023e-03, -1.68096209e+00,
-7.95923121e-01, -2.31321779e-04, 2.75606917e-04, -8.37504225e+00,
1.19643663e+01, -9.42136160e-02, -4.25626144e-02, 2.23305087e-02,
-8.42352748e+00, 6.11951007e-02, -3.25888640e-01, -4.17471376e+00])
#5: 'y = N^6':
array([7.76528795e+00, 8.09973686e-07, 6.75154697e+01, 3.39672588e+00,
5.60113749e-01, 1.02045298e-05, 2.07048049e-01, 4.28735727e-03,
2.64935148e-06, 4.38588881e-06, 2.88495558e-04, 2.27156397e-02,
2.28214665e-02, 5.21302140e-06, 5.80171903e+01, 2.83422447e-09,
2.99069431e-01, 1.54636027e-01, 6.51694431e-05, 5.45729464e-01])
The first set of results is
[ 1.92013546 0.50119386 -0.85598426 1.44799103 1.63065172 1.95591239
-1.07810631 -1.06883157 0.53221628 -0.50083637 0.80984049 -1.32364548
1.32708961 1.11797332 0.42746811 -0.76855719 0.02324697 0.36627675
0.2483084 0.720024 ]
The first set of results has median
0.464 (95% CI: -1.207, 1.939)
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 objdict
s rather than odict
s 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.840273 0.988312 0.989815 0.644862 0.119152 0.397980 0.867726
1 0.343771 0.382862 0.387275 0.620308 0.454754 0.057203 0.054835
2 0.138295 0.949965 0.071269 0.151573 0.881607 0.920405 0.163275
3 0.064376 0.413188 0.448056 0.942562 0.904276 0.383054 0.696205
4 0.626882 0.603008 0.732572 0.789422 0.574791 0.695067 0.199200
.. ... ... ... ... ... ... ...
65 0.234081 0.124606 0.756249 0.067300 0.869049 0.249421 0.100815
66 0.716090 0.748623 0.458981 0.734954 0.165087 0.355628 0.565391
67 0.479263 0.601527 0.773281 0.346046 0.238695 0.196620 0.320200
68 0.142034 0.038721 0.632133 0.907509 0.960648 0.006174 0.211785
69 0.377195 0.742801 0.376773 0.131118 0.128298 0.926405 0.923396
7 8 9
0 0.660042 0.076896 0.108124
1 0.015984 0.560671 0.481211
2 0.873118 0.335169 0.621144
3 0.436023 0.169159 0.996570
4 0.339683 0.675563 0.198921
.. ... ... ...
65 0.995957 0.721141 0.526191
66 0.005275 0.889976 0.910703
67 0.127961 0.163253 0.100468
68 0.421154 0.922348 0.765733
69 0.046419 0.949379 0.823459
[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.8403 0.9883 0.9898 0.6449 0.1192 0.3980 0.8677 0.6600 0.0769 0.1081
1 0.3438 0.3829 0.3873 0.6203 0.4548 0.0572 0.0548 0.0160 0.5607 0.4812
2 0.1383 0.9500 0.0713 0.1516 0.8816 0.9204 0.1633 0.8731 0.3352 0.6211
3 0.0644 0.4132 0.4481 0.9426 0.9043 0.3831 0.6962 0.4360 0.1692 0.9966
4 0.6269 0.6030 0.7326 0.7894 0.5748 0.6951 0.1992 0.3397 0.6756 0.1989
5 0.7857 0.0781 0.6434 0.4643 0.5390 0.6769 0.6515 0.8337 0.6365 0.5568
6 0.1896 0.6482 0.6872 0.5057 0.0359 0.4963 0.9960 0.9688 0.7248 0.7875
7 0.1774 0.8843 0.9919 0.8882 0.0315 0.2928 0.3833 0.6656 0.3535 0.9668
8 0.6724 0.1083 0.0840 0.5457 0.9420 0.0608 0.1384 0.6135 0.7301 0.6539
9 0.3411 0.8763 0.7215 0.2657 0.3802 0.8460 0.2662 0.5452 0.4264 0.3579
10 0.4048 0.7992 0.5775 0.1174 0.0519 0.5736 0.0814 0.7411 0.5999 0.2548
11 0.3458 0.0091 0.2254 0.7350 0.9073 0.1216 0.1253 0.1716 0.2363 0.8667
12 0.6127 0.7174 0.7388 0.0419 0.3860 0.8386 0.0389 0.0859 0.3845 0.1608
13 0.5783 0.6438 0.2389 0.3701 0.9444 0.0776 0.5978 0.7379 0.9070 0.9054
14 0.0892 0.8192 0.0981 0.5479 0.1940 0.5906 0.9167 0.0835 0.5520 0.9945
15 0.0206 0.4475 0.3135 0.5663 0.6535 0.8927 0.3661 0.5869 0.2775 0.9126
16 0.4023 0.3819 0.5201 0.5232 0.4770 0.9213 0.0931 0.1995 0.9728 0.6245
17 0.7711 0.8878 0.3065 0.5058 0.8694 0.6210 0.4656 0.9919 0.6043 0.8273
18 0.9596 0.8290 0.1311 0.7425 0.8294 0.1369 0.8022 0.1950 0.0867 0.7742
19 0.2346 0.4147 0.2114 0.9970 0.6257 0.4074 0.4962 0.4959 0.0788 0.1776
20 0.3951 0.7734 0.7470 0.3987 0.8881 0.1244 0.4550 0.4068 0.5038 0.1485
21 0.5405 0.3617 0.6631 0.4212 0.2570 0.9654 0.4052 0.3860 0.1445 0.7478
22 0.8933 0.5391 0.5581 0.4383 0.9327 0.0030 0.9364 0.6946 0.6905 0.1560
23 0.2545 0.4832 0.6036 0.5509 0.7534 0.5591 0.8456 0.9187 0.0418 0.1690
24 0.9381 0.6094 0.8444 0.7589 0.6474 0.5795 0.8060 0.1378 0.4515 0.5160
25 0.3591 0.2581 0.3369 0.9660 0.1927 0.0292 0.7798 0.1912 0.2424 0.2943
26 0.1457 0.5374 0.8925 0.8037 0.3452 0.8854 0.8228 0.3955 0.8772 0.3448
27 0.7493 0.6686 0.5683 0.2343 0.0269 0.2606 0.5024 0.3690 0.8704 0.3379
28 0.6743 0.6668 0.1600 0.9185 0.3127 0.0564 0.0217 0.4754 0.2917 0.5664
29 0.2544 0.0563 0.2971 0.7745 0.6944 0.9987 0.0212 0.9530 0.0526 0.0232
30 0.2388 0.3762 0.5267 0.2005 0.7547 0.1739 0.8135 0.4902 0.8724 0.7706
31 0.1170 0.2322 0.9579 0.6184 0.0756 0.2061 0.0497 0.8219 0.5055 0.5993
32 0.3239 0.0908 0.6819 0.7947 0.7488 0.8369 0.8448 0.8504 0.0067 0.0873
33 0.5016 0.8208 0.8783 0.1764 0.2121 0.3914 0.7147 0.8960 0.5170 0.2182
34 0.6599 0.8184 0.2873 0.6435 0.7248 0.3550 0.2143 0.5629 0.5545 0.8041
35 0.0458 0.1118 0.1706 0.3129 0.3549 0.4276 0.3503 0.6280 0.2836 0.5897
36 0.9643 0.3655 0.4994 0.2239 0.7320 0.4150 0.4505 0.6243 0.8181 0.0324
37 0.9762 0.3543 0.3686 0.0274 0.7206 0.2912 0.7356 0.7685 0.2709 0.6279
38 0.3229 0.9331 0.1609 0.9715 0.3201 0.1233 0.1469 0.2676 0.9742 0.2387
39 0.5485 0.1742 0.4167 0.2805 0.9223 0.1379 0.5916 0.4989 0.2183 0.1684
40 0.6897 0.9364 0.5352 0.4351 0.3232 0.7278 0.3940 0.2726 0.6117 0.8868
41 0.6997 0.1749 0.2918 0.1035 0.1748 0.4112 0.9112 0.8566 0.3891 0.8193
42 0.2490 0.5634 0.7762 0.4230 0.7316 0.4840 0.5292 0.7344 0.0968 0.3051
43 0.5877 0.0292 0.3587 0.5914 0.6998 0.8630 0.8399 0.9943 0.4346 0.0156
44 0.2976 0.8195 0.9077 0.9975 0.2981 0.6472 0.0604 0.2952 0.4020 0.5080
45 0.9000 0.2850 0.2876 0.9977 0.1161 0.4128 0.2166 0.2133 0.3966 0.6076
46 0.0584 0.6569 0.7258 0.9627 0.2974 0.3488 0.9329 0.7942 0.5823 0.2279
47 0.5779 0.6635 0.6128 0.3027 0.6450 0.1162 0.3911 0.3812 0.8988 0.5974
48 0.7540 0.5511 0.6213 0.1526 0.1879 0.7133 0.1124 0.4422 0.6207 0.3021
49 0.8769 0.9301 0.1807 0.5443 0.1371 0.6940 0.2226 0.0019 0.9211 0.7230
50 0.9841 0.8833 0.6174 0.3570 0.5735 0.7185 0.7283 0.6826 0.3589 0.6795
51 0.3417 0.7246 0.8848 0.7191 0.0416 0.8141 0.4276 0.1919 0.9092 0.0748
52 0.3136 0.8301 0.4057 0.7188 0.2106 0.1529 0.8976 0.7670 0.4826 0.2974
53 0.6785 0.7538 0.4437 0.8853 0.1840 0.1627 0.8933 0.3134 0.5695 0.7940
54 0.9438 0.8685 0.6142 0.2772 0.9148 0.7905 0.2756 0.4015 0.5256 0.0626
55 0.1396 0.1083 0.8529 0.5115 0.8927 0.2687 0.8747 0.1515 0.1238 0.6107
56 0.5025 0.0267 0.2522 0.4669 0.6115 0.5682 0.8124 0.6199 0.2875 0.5449
57 0.7650 0.0799 0.0893 0.9550 0.8883 0.2625 0.6041 0.0559 0.2009 0.8238
58 0.0199 0.4245 0.9347 0.8494 0.6120 0.6107 0.5114 0.9575 0.3505 0.0720
59 0.5257 0.9193 0.3305 0.4303 0.4717 0.8889 0.7959 0.1424 0.3851 0.0802
60 0.2732 0.8859 0.6737 0.2960 0.9940 0.2405 0.5488 0.0525 0.0365 0.1534
61 0.6308 0.2143 0.4733 0.6876 0.6990 0.6904 0.4873 0.1021 0.9542 0.3175
62 0.6179 0.9433 0.2144 0.5691 0.3925 0.2917 0.7369 0.8320 0.0843 0.2636
63 0.2170 0.0455 0.4014 0.3503 0.4322 0.4379 0.9902 0.3782 0.4743 0.3838
64 0.4478 0.2734 0.5782 0.4768 0.8424 0.7645 0.5101 0.4338 0.7114 0.8060
65 0.2341 0.1246 0.7562 0.0673 0.8690 0.2494 0.1008 0.9960 0.7211 0.5262
66 0.7161 0.7486 0.4590 0.7350 0.1651 0.3556 0.5654 0.0053 0.8900 0.9107
67 0.4793 0.6015 0.7733 0.3460 0.2387 0.1966 0.3202 0.1280 0.1633 0.1005
68 0.1420 0.0387 0.6321 0.9075 0.9606 0.0062 0.2118 0.4212 0.9223 0.7657
69 0.3772 0.7428 0.3768 0.1311 0.1283 0.9264 0.9234 0.0464 0.9494 0.8235
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 8.4e-01 9.9e-01 ... 7.7e-02 0.1
1 3.4e-01 3.8e-01 ... 5.6e-01 0.5
2 1.4e-01 9.5e-01 ... 3.4e-01 0.6
3 6.4e-02 4.1e-01 ... 1.7e-01 1.0
4 6.3e-01 6.0e-01 ... 6.8e-01 0.2
.. ... ... ... ... ...
65 2.3e-01 1.2e-01 ... 7.2e-01 0.5
66 7.2e-01 7.5e-01 ... 8.9e-01 0.9
67 4.8e-01 6.0e-01 ... 1.6e-01 0.1
68 1.4e-01 3.9e-02 ... 9.2e-01 0.8
69 3.8e-01 7.4e-01 ... 9.5e-01 0.8
[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