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 pylab as pl

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
            pl.figure()
            rows,cols = sc.getrowscols(len(self.results))
            for i,label,result in self.results.enumitems(): # odict magic!
                pl.subplot(rows, cols, i+1)
                pl.scatter(np.arange(self.n), result, c=result, cmap='parula')
                pl.title(label)
            sc.figlayout() # Trim whitespace from the figure

sim = Sim()
sim.run()
sim.plot()
../_images/tutorials_tut_dicts_12_0.png

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.20270654,  0.6708633 ,  0.84962719, -0.12712647, -1.77423146,
       -0.52461166,  0.28106319,  0.76587516,  0.34074275, -0.57504623,
       -0.82692705,  1.32020452, -0.3448903 ,  0.95150247,  0.20042778,
        0.0772026 , -1.61560224, -1.40879705,  0.60905786,  0.75504973])
#1: 'y = N^2':
array([1.80091073e-01, 7.35476449e-01, 1.43588594e-01, 1.09528176e+00,
       6.25335455e-01, 1.48385459e+00, 3.62462558e-01, 8.21068204e-04,
       2.56534935e+00, 5.27861581e-02, 2.30237247e+00, 8.00535799e-01,
       8.74060420e-02, 3.80817675e+00, 1.03039699e-01, 5.17642732e-02,
       1.13934646e+00, 5.49254460e+00, 2.30922721e-02, 7.98702467e-01])
#2: 'y = N^3':
array([ 3.77217293, -0.65058311, -0.60333399, -0.03949993,  2.33499009,
       -0.48408857,  2.77872357, -0.1448034 , -3.72477984, -1.53618083,
       13.13019317, -3.74254323, 26.15813623,  4.07735403,  0.19663714,
       -0.21037702,  1.00144023, -6.74359225,  0.51804618, -0.41783374])
#3: 'y = N^4':
array([9.72289288e-04, 6.72065799e-01, 1.90717158e-02, 1.92605769e-01,
       5.12367285e+01, 1.20622566e+00, 2.18483079e+00, 3.41265841e-03,
       1.24194131e-01, 1.87047991e+00, 2.96245354e-03, 1.44790783e-01,
       5.27956569e-04, 1.80150586e+00, 2.36433954e-01, 7.33200902e-06,
       3.07711421e-01, 5.67071105e-03, 2.80215872e-02, 2.47522328e-03])
#4: 'y = N^5':
array([-6.23652161e-02, -5.38034412e-03, -1.80834186e-10, -1.25534175e+02,
        4.92932629e-09, -2.53567903e-03, -8.67544375e-03,  9.82133765e-02,
       -1.22593657e+00, -8.85608039e+00, -5.58368016e-01, -3.30764696e-02,
        1.58505161e-01, -7.99243645e-01, -4.86016333e-04,  2.98922624e-03,
       -3.08201373e-01, -1.18410609e-01, -9.06454796e-08, -1.19901467e-04])
#5: 'y = N^6':
array([2.05595348e+01, 4.12346980e-03, 3.20666491e+00, 6.31398584e-01,
       1.00585838e-03, 1.54583641e-01, 8.57506031e+00, 1.16757332e-02,
       3.83760864e-01, 4.67882132e+01, 8.81695636e+01, 3.86607260e-15,
       2.77092623e-04, 1.33694326e+01, 1.08156013e-03, 3.55128940e-03,
       1.57385132e+00, 4.31784428e-02, 4.76366093e-01, 5.11931259e+01])
The first set of results is
[-1.20270654  0.6708633   0.84962719 -0.12712647 -1.77423146 -0.52461166
  0.28106319  0.76587516  0.34074275 -0.57504623 -0.82692705  1.32020452
 -0.3448903   0.95150247  0.20042778  0.0772026  -1.61560224 -1.40879705
  0.60905786  0.75504973]
The first set of results has median
0.139 (95% CI: -1.699, 1.145)

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.089967  0.731390  0.373137  0.330746  0.204397  0.792912  0.496172  \
1   0.820067  0.131440  0.035501  0.760790  0.019310  0.398000  0.878056
2   0.372566  0.980536  0.573206  0.800147  0.863270  0.734609  0.954842
3   0.408772  0.898948  0.081456  0.480961  0.950988  0.150750  0.223392
4   0.305938  0.346341  0.056190  0.620162  0.005650  0.698217  0.786933
..       ...       ...       ...       ...       ...       ...       ...
65  0.497135  0.628300  0.545847  0.154014  0.115608  0.991059  0.559331
66  0.232300  0.118147  0.495335  0.074219  0.562963  0.124194  0.739403
67  0.548823  0.782341  0.630992  0.029517  0.422551  0.606471  0.324370
68  0.985586  0.319179  0.788595  0.597766  0.151752  0.536277  0.850030
69  0.273725  0.883878  0.872465  0.716478  0.849936  0.251180  0.626405

           7         8         9
0   0.486403  0.107108  0.035868
1   0.039701  0.504335  0.776265
2   0.926798  0.952127  0.829641
3   0.155574  0.432131  0.521276
4   0.162878  0.693410  0.883485
..       ...       ...       ...
65  0.885789  0.567173  0.533537
66  0.484254  0.079059  0.588733
67  0.511596  0.059857  0.564679
68  0.630047  0.555167  0.000353
69  0.939057  0.815315  0.468399

[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.0900  0.7314  0.3731  0.3307  0.2044  0.7929  0.4962  0.4864  0.1071  0.0359
1   0.8201  0.1314  0.0355  0.7608  0.0193  0.3980  0.8781  0.0397  0.5043  0.7763
2   0.3726  0.9805  0.5732  0.8001  0.8633  0.7346  0.9548  0.9268  0.9521  0.8296
3   0.4088  0.8989  0.0815  0.4810  0.9510  0.1508  0.2234  0.1556  0.4321  0.5213
4   0.3059  0.3463  0.0562  0.6202  0.0056  0.6982  0.7869  0.1629  0.6934  0.8835
5   0.7800  0.7264  0.5713  0.0698  0.0290  0.9092  0.4773  0.9336  0.2387  0.3393
6   0.1272  0.1187  0.6284  0.5686  0.3035  0.1169  0.2694  0.3738  0.2686  0.2107
7   0.7178  0.0970  0.5111  0.9656  0.2919  0.0259  0.3347  0.7515  0.7129  0.1521
8   0.6096  0.8424  0.2990  0.8131  0.4291  0.2178  0.5419  0.9287  0.8196  0.4827
9   0.2872  0.4351  0.7486  0.0246  0.3003  0.8443  0.0543  0.0651  0.9163  0.7354
10  0.2960  0.5521  0.0773  0.1565  0.3832  0.3888  0.8242  0.8614  0.2584  0.8249
11  0.3307  0.5712  0.0746  0.0850  0.0064  0.4735  0.1917  0.1788  0.0696  0.4869
12  0.3738  0.1758  0.7095  0.2578  0.2092  0.9271  0.5196  0.3281  0.9119  0.6428
13  0.6946  0.7600  0.9549  0.8681  0.2905  0.8196  0.4279  0.1445  0.0781  0.1720
14  0.6049  0.3941  0.3524  0.0831  0.5497  0.0876  0.9973  0.9422  0.8493  0.6433
15  0.4751  0.7573  0.0668  0.9105  0.9398  0.2904  0.3401  0.6760  0.8483  0.1519
16  0.7984  0.7357  0.0419  0.5883  0.1329  0.4726  0.7048  0.8614  0.9310  0.1620
17  0.2497  0.9436  0.0230  0.9839  0.3282  0.8468  0.1571  0.2232  0.2047  0.4944
18  0.1959  0.0808  0.6433  0.9415  0.0559  0.0461  0.3385  0.0014  0.0702  0.7983
19  0.0473  0.0400  0.7063  0.5729  0.5133  0.5655  0.3617  0.8090  0.2689  0.0150
20  0.4609  0.9537  0.8550  0.0112  0.2481  0.2355  0.4375  0.7246  0.8590  0.4638
21  0.7357  0.1879  0.9195  0.3277  0.9178  0.2305  0.4930  0.0936  0.7785  0.3311
22  0.3597  0.2928  0.6798  0.6849  0.5600  0.9862  0.8517  0.9420  0.6698  0.9811
23  0.0979  0.5273  0.2429  0.8286  0.2841  0.0438  0.4412  0.2229  0.9071  0.3214
24  0.4933  0.6883  0.9223  0.6410  0.4178  0.5495  0.9954  0.1787  0.8215  0.4298
25  0.1314  0.0175  0.3692  0.2361  0.4739  0.8845  0.6582  0.5889  0.1735  0.7842
26  0.6004  0.6156  0.7222  0.2819  0.7095  0.8672  0.3251  0.0922  0.8170  0.6424
27  0.5431  0.2345  0.5310  0.0529  0.1830  0.8162  0.7202  0.7698  0.8086  0.5136
28  0.7178  0.4129  0.7049  0.5657  0.2784  0.4770  0.9606  0.6209  0.5939  0.6381
29  0.5646  0.0963  0.5502  0.9614  0.5727  0.5475  0.9675  0.9408  0.9963  0.1625
30  0.6127  0.1828  0.2814  0.3517  0.7928  0.5781  0.2711  0.9845  0.7965  0.3506
31  0.8186  0.5803  0.2377  0.1539  0.0696  0.7178  0.8779  0.7178  0.7448  0.2225
32  0.5067  0.7045  0.6232  0.1822  0.9127  0.1154  0.4076  0.9546  0.6442  0.1396
33  0.5744  0.4040  0.4064  0.9789  0.0199  0.0997  0.8355  0.8085  0.8981  0.4980
34  0.2972  0.6068  0.4252  0.2235  0.6844  0.2942  0.5954  0.7106  0.2392  0.1345
35  0.0206  0.3643  0.8860  0.3490  0.6371  0.1874  0.2024  0.9641  0.6470  0.1099
36  0.3145  0.9418  0.8807  0.2835  0.1486  0.3719  0.2169  0.2675  0.9430  0.0756
37  0.0998  0.2481  0.3034  0.4437  0.8009  0.9053  0.4865  0.6051  0.6703  0.2386
38  0.7937  0.6887  0.1399  0.0516  0.7182  0.0646  0.3776  0.0343  0.6856  0.4097
39  0.4394  0.4755  0.3840  0.9778  0.0918  0.5905  0.8423  0.8320  0.5671  0.7948
40  0.9805  0.5684  0.9149  0.8209  0.0481  0.1261  0.7515  0.7518  0.1794  0.7865
41  0.7638  0.7484  0.3667  0.1981  0.0211  0.7306  0.2868  0.5894  0.8903  0.6411
42  0.0710  0.5245  0.8009  0.2895  0.6567  0.5546  0.0602  0.9958  0.2095  0.1265
43  0.6522  0.1501  0.1095  0.9437  0.5082  0.8581  0.0106  0.5076  0.5902  0.4437
44  0.2726  0.4882  0.1923  0.7457  0.9415  0.6548  0.9381  0.6321  0.2186  0.0871
45  0.6308  0.4623  0.6415  0.0880  0.7598  0.0878  0.8569  0.0382  0.0788  0.9532
46  0.3055  0.9450  0.2039  0.6477  0.4192  0.9729  0.5672  0.1161  0.2754  0.6496
47  0.4280  0.4082  0.6374  0.6618  0.3536  0.6597  0.0881  0.0896  0.1377  0.5786
48  0.3097  0.8440  0.4879  0.2158  0.1644  0.2382  0.9649  0.3485  0.5241  0.8830
49  0.0017  0.7597  0.8636  0.1312  0.1420  0.9671  0.6457  0.3993  0.9342  0.1732
50  0.8539  0.1225  0.6133  0.5747  0.4733  0.9723  0.8993  0.1462  0.6390  0.6166
51  0.9108  0.2448  0.5144  0.4232  0.2220  0.9460  0.3722  0.8529  0.6897  0.4051
52  0.5795  0.4709  0.8673  0.4759  0.6043  0.0292  0.0250  0.8010  0.2977  0.4211
53  0.1858  0.6947  0.9663  0.6720  0.6258  0.7381  0.9695  0.5407  0.8471  0.6751
54  0.2244  0.3084  0.6936  0.0425  0.5822  0.2035  0.1840  0.2975  0.7603  0.8081
55  0.7143  0.5809  0.0659  0.9810  0.0426  0.5020  0.6787  0.3358  0.0947  0.5727
56  0.8140  0.6861  0.5882  0.5631  0.6897  0.3853  0.5869  0.1544  0.2567  0.0861
57  0.4642  0.7579  0.2682  0.3036  0.9559  0.7090  0.9446  0.3283  0.5985  0.1452
58  0.6401  0.1191  0.1676  0.2180  0.2123  0.4626  0.9010  0.6678  0.9954  0.7997
59  0.3703  0.3900  0.3146  0.4478  0.0092  0.4210  0.1470  0.6464  0.3428  0.2376
60  0.5941  0.5486  0.8724  0.1247  0.9001  0.6315  0.5546  0.4591  0.4144  0.5590
61  0.8573  0.5713  0.7640  0.7061  0.0020  0.6617  0.7452  0.6307  0.9168  0.7077
62  0.4165  0.6784  0.7188  0.1516  0.1595  0.4518  0.3022  0.1490  0.6074  0.4476
63  0.4549  0.2462  0.9160  0.8260  0.7411  0.0780  0.7042  0.3047  0.2044  0.1898
64  0.3638  0.2017  0.6231  0.6977  0.0287  0.8434  0.6236  0.7153  0.0411  0.6113
65  0.4971  0.6283  0.5458  0.1540  0.1156  0.9911  0.5593  0.8858  0.5672  0.5335
66  0.2323  0.1181  0.4953  0.0742  0.5630  0.1242  0.7394  0.4843  0.0791  0.5887
67  0.5488  0.7823  0.6310  0.0295  0.4226  0.6065  0.3244  0.5116  0.0599  0.5647
68  0.9856  0.3192  0.7886  0.5978  0.1518  0.5363  0.8500  0.6300  0.5552  0.0004
69  0.2737  0.8839  0.8725  0.7165  0.8499  0.2512  0.6264  0.9391  0.8153  0.4684

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   9.0e-02  0.7  ...  1.1e-01  3.6e-02
1   8.2e-01  0.1  ...  5.0e-01  7.8e-01
2   3.7e-01  1.0  ...  9.5e-01  8.3e-01
3   4.1e-01  0.9  ...  4.3e-01  5.2e-01
4   3.1e-01  0.3  ...  6.9e-01  8.8e-01
..      ...  ...  ...      ...      ...
65  5.0e-01  0.6  ...  5.7e-01  5.3e-01
66  2.3e-01  0.1  ...  7.9e-02  5.9e-01
67  5.5e-01  0.8  ...  6.0e-02  5.6e-01
68  9.9e-01  0.3  ...  5.6e-01  3.5e-04
69  2.7e-01  0.9  ...  8.2e-01  4.7e-01

[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