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([-0.14087185, -2.84197983, -0.66356875,  0.51569623,  1.07951622,
       -0.06236386, -2.38971739, -0.79873058,  1.0833323 , -0.22919563,
       -0.01877774, -0.55224976, -0.40824618, -1.14766484,  0.2959549 ,
        1.16145281,  0.22477447,  1.11621998, -1.91676886,  1.7631795 ])
#1: 'y = N^2':
array([1.05264002e+00, 1.63482320e+00, 1.05147717e+00, 1.08843731e-01,
       7.14381992e-01, 2.66432045e-02, 2.38397003e+00, 1.01235141e-01,
       7.81234239e-01, 2.28764382e-03, 1.32914414e+00, 1.81712130e+00,
       3.30665755e+00, 1.38878178e-02, 2.11196989e+00, 1.15563239e-01,
       2.09827871e-01, 3.60945285e-01, 1.86616162e-02, 1.31425237e+00])
#2: 'y = N^3':
array([-8.48865579e-01, -1.87680784e-01, -3.25025573e-03,  4.88300460e-02,
       -9.47302736e+00, -2.66292208e-02, -2.32401353e+00,  1.11955822e+00,
       -3.72293222e-01, -2.27171589e-01,  9.43320234e-01, -2.50364686e-01,
        4.31170913e-01,  1.25370268e-01, -2.84827412e+00, -1.04939116e+00,
       -2.43210594e-03,  6.10794351e+00,  1.11468789e-02,  1.36554029e-01])
#3: 'y = N^4':
array([1.30272480e-01, 1.54601010e+01, 5.43451111e-04, 1.39414227e-02,
       4.18711884e-03, 7.29843506e-01, 1.02346074e-02, 3.26540266e-01,
       9.14012027e+00, 3.61059110e-05, 2.01138286e-01, 7.80477417e-02,
       2.37911475e+00, 5.86487320e-03, 6.32153260e-01, 9.47922399e-04,
       1.85441627e-04, 4.38864385e+00, 5.38409212e-02, 3.26690557e-01])
#4: 'y = N^5':
array([-3.32970735e-01,  1.12515205e-03, -8.92636084e+00,  5.19871479e+00,
        9.63871806e+01,  7.95511913e-08, -3.92631284e+00, -3.45961341e+00,
        7.51770122e+00, -1.50427196e+01,  5.53613752e+00, -1.27134866e-02,
       -1.81162976e+00,  1.99544979e+01,  1.13107782e-04,  1.84484773e-02,
       -7.49948444e-02,  8.04831606e-04, -1.68554978e-06, -1.73424335e+00])
#5: 'y = N^6':
array([4.36712178e-02, 1.98380136e+00, 1.07437795e-06, 2.46286648e-04,
       2.75040382e+01, 9.21071557e-01, 5.72880845e-02, 2.19564946e-03,
       3.32439307e-04, 3.01147292e+01, 6.32297193e-03, 2.06597663e+00,
       3.56736346e+01, 1.60062431e-02, 5.73342816e-09, 8.47719677e-03,
       4.06815239e-13, 1.15344094e-04, 4.05572163e-09, 1.67529729e+00])
The first set of results is
[-0.14087185 -2.84197983 -0.66356875  0.51569623  1.07951622 -0.06236386
 -2.38971739 -0.79873058  1.0833323  -0.22919563 -0.01877774 -0.55224976
 -0.40824618 -1.14766484  0.2959549   1.16145281  0.22477447  1.11621998
 -1.91676886  1.7631795 ]
The first set of results has median
-0.102 (95% CI: -2.627, 1.477)

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.375838  0.279592  0.942071  0.547487  0.801006  0.771270  0.127141
1   0.039803  0.200291  0.667292  0.635373  0.806551  0.558088  0.111804
2   0.137792  0.969121  0.395529  0.163870  0.108285  0.075748  0.528693
3   0.999490  0.444634  0.168308  0.915077  0.019123  0.589361  0.401373
4   0.883596  0.141624  0.088568  0.413109  0.911872  0.699993  0.091902
..       ...       ...       ...       ...       ...       ...       ...
65  0.300262  0.833069  0.407325  0.597830  0.798191  0.848997  0.509068
66  0.921262  0.219147  0.251306  0.861041  0.016403  0.698941  0.562642
67  0.162028  0.262490  0.519901  0.870650  0.463240  0.771799  0.888855
68  0.903574  0.326079  0.866604  0.059704  0.322959  0.626994  0.166560
69  0.355877  0.460207  0.689451  0.505066  0.288238  0.218173  0.999559

           7         8         9
0   0.501520  0.363138  0.124355
1   0.408147  0.801834  0.063800
2   0.888508  0.174359  0.214076
3   0.196281  0.333635  0.076006
4   0.710584  0.910101  0.795604
..       ...       ...       ...
65  0.228355  0.930433  0.383538
66  0.173027  0.752665  0.523305
67  0.487892  0.115658  0.595322
68  0.660569  0.699872  0.800244
69  0.191358  0.604602  0.654241

[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.3758  0.2796  0.9421  0.5475  0.8010  0.7713  0.1271  0.5015  0.3631  0.1244
1   0.0398  0.2003  0.6673  0.6354  0.8066  0.5581  0.1118  0.4081  0.8018  0.0638
2   0.1378  0.9691  0.3955  0.1639  0.1083  0.0757  0.5287  0.8885  0.1744  0.2141
3   0.9995  0.4446  0.1683  0.9151  0.0191  0.5894  0.4014  0.1963  0.3336  0.0760
4   0.8836  0.1416  0.0886  0.4131  0.9119  0.7000  0.0919  0.7106  0.9101  0.7956
5   0.8794  0.3503  0.6437  0.4933  0.5589  0.4005  0.5352  0.9973  0.9598  0.3410
6   0.2592  0.9097  0.2250  0.3948  0.5700  0.8895  0.4529  0.0536  0.2952  0.6996
7   0.1074  0.8868  0.5254  0.7043  0.4871  0.4688  0.7116  0.9797  0.5279  0.0304
8   0.2123  0.5675  0.5121  0.5939  0.3322  0.7544  0.9348  0.7108  0.3431  0.6817
9   0.0734  0.3041  0.7187  0.0613  0.5700  0.1649  0.3647  0.1674  0.2555  0.9569
10  0.0982  0.0417  0.7499  0.8534  0.3178  0.6650  0.3966  0.6967  0.6008  0.6719
11  0.6843  0.1080  0.3204  0.8738  0.1428  0.2824  0.0676  0.3366  0.7026  0.7924
12  0.1416  0.8976  0.5129  0.2550  0.3628  0.0062  0.2198  0.0201  0.8339  0.1732
13  0.0505  0.8035  0.4384  0.6174  0.0601  0.3144  0.4109  0.2862  0.3244  0.3509
14  0.6964  0.7027  0.2857  0.4355  0.6234  0.5662  0.1103  0.4121  0.0658  0.9644
15  0.3135  0.4310  0.4696  0.3894  0.8408  0.0974  0.0884  0.2252  0.7927  0.8306
16  0.8552  0.2213  0.1139  0.3457  0.9300  0.6534  0.5463  0.2883  0.5520  0.0853
17  0.2464  0.7318  0.9773  0.2074  0.5647  0.0855  0.9228  0.2291  0.4718  0.6828
18  0.0890  0.4612  0.8172  0.9624  0.8313  0.4778  0.0738  0.1756  0.5775  0.4025
19  0.1982  0.5178  0.0141  0.2063  0.8883  0.5531  0.6077  0.1372  0.9015  0.3968
20  0.4419  0.2253  0.5576  0.8593  0.8969  0.2696  0.0679  0.8060  0.2488  0.3272
21  0.0261  0.4061  0.4109  0.6743  0.8921  0.9584  0.8081  0.0526  0.2075  0.1694
22  0.5592  0.9757  0.7455  0.3226  0.9445  0.0692  0.7118  0.7627  0.0318  0.7844
23  0.2447  0.2750  0.7225  0.7861  0.4162  0.2372  0.4574  0.2144  0.7701  0.6154
24  0.8929  0.1765  0.1551  0.8393  0.4129  0.3432  0.9359  0.7402  0.3300  0.5853
25  0.9371  0.1089  0.3548  0.7130  0.3224  0.8836  0.3345  0.8017  0.6043  0.5913
26  0.1789  0.7938  0.2814  0.8749  0.7921  0.7547  0.4208  0.8702  0.1227  0.3257
27  0.6142  0.4274  0.5532  0.0923  0.0033  0.8325  0.4564  0.0461  0.1737  0.1467
28  0.2646  0.6658  0.3857  0.4659  0.7712  0.1526  0.9079  0.7273  0.4408  0.7544
29  0.7899  0.3911  0.1944  0.8315  0.6418  0.2150  0.3788  0.5083  0.3669  0.9139
30  0.9886  0.6975  0.5754  0.8563  0.6601  0.5370  0.3795  0.4354  0.3349  0.8784
31  0.7896  0.8503  0.5339  0.3047  0.7171  0.8281  0.4468  0.5735  0.2955  0.1327
32  0.0209  0.5766  0.5541  0.2992  0.7643  0.7076  0.4730  0.4157  0.4145  0.3931
33  0.4068  0.6736  0.1771  0.0168  0.5391  0.4237  0.3883  0.6252  0.7207  0.0073
34  0.0077  0.4261  0.8200  0.1799  0.5244  0.8689  0.8610  0.1728  0.0568  0.9380
35  0.3781  0.3034  0.0881  0.0526  0.0047  0.9864  0.8516  0.8572  0.0216  0.5225
36  0.2487  0.3653  0.8821  0.4573  0.2762  0.5801  0.9167  0.6109  0.8079  0.4690
37  0.9912  0.4229  0.1230  0.5720  0.1812  0.1220  0.4539  0.4546  0.8753  0.1144
38  0.5671  0.1833  0.2796  0.7096  0.5111  0.1200  0.4905  0.0514  0.6905  0.4770
39  0.0317  0.6177  0.5382  0.2735  0.0836  0.8420  0.3169  0.3869  0.9738  0.6374
40  0.2992  0.4885  0.4705  0.7146  0.3095  0.0287  0.4796  0.3394  0.6426  0.8778
41  0.3741  0.5398  0.8545  0.7536  0.5170  0.1634  0.2252  0.0758  0.0314  0.2989
42  0.4564  0.0446  0.1735  0.0474  0.1237  0.0006  0.4788  0.1894  0.8198  0.5206
43  0.6151  0.3946  0.6075  0.9903  0.7608  0.5314  0.4765  0.7435  0.6950  0.2659
44  0.6195  0.7329  0.8704  0.6076  0.9691  0.7990  0.0501  0.6212  0.5796  0.3029
45  0.6991  0.8347  0.9811  0.5501  0.9154  0.2710  0.5150  0.5140  0.9338  0.0449
46  0.6005  0.6808  0.9215  0.8728  0.5077  0.3074  0.2634  0.2637  0.9032  0.2159
47  0.3356  0.5254  0.2836  0.4531  0.7015  0.4517  0.7460  0.2947  0.0612  0.7034
48  0.0316  0.9396  0.0012  0.5809  0.5537  0.6897  0.0439  0.1595  0.2255  0.7152
49  0.5710  0.3406  0.8093  0.9985  0.8816  0.9146  0.1123  0.3826  0.7896  0.3224
50  0.5212  0.7989  0.0815  0.2340  0.7756  0.3698  0.4369  0.0281  0.1864  0.3424
51  0.3096  0.1354  0.9116  0.8811  0.4567  0.3112  0.7626  0.7616  0.7101  0.3782
52  0.4659  0.0300  0.2542  0.5192  0.6270  0.1251  0.5899  0.4407  0.3074  0.9674
53  0.8742  0.7706  0.6360  0.6932  0.1790  0.1254  0.3149  0.5448  0.4029  0.6072
54  0.2525  0.0758  0.7178  0.1711  0.9173  0.9999  0.0281  0.7940  0.5271  0.3880
55  0.2715  0.0378  0.3382  0.9649  0.5558  0.3050  0.2540  0.6295  0.2937  0.8086
56  0.5660  0.4720  0.2220  0.3877  0.5529  0.6723  0.6593  0.2138  0.8087  0.1046
57  0.5057  0.0779  0.9415  0.6907  0.1441  0.8550  0.6747  0.8971  0.7813  0.3291
58  0.1378  0.3829  0.4923  0.9147  0.6757  0.2606  0.8644  0.0761  0.2788  0.3377
59  0.5518  0.2720  0.4265  0.2085  0.4515  0.4061  0.7012  0.8427  0.7898  0.6983
60  0.5425  0.3567  0.7503  0.6057  0.6153  0.5047  0.3257  0.4130  0.5254  0.4354
61  0.4958  0.4316  0.6605  0.5181  0.7545  0.0437  0.5215  0.4019  0.2189  0.7536
62  0.3869  0.4106  0.6755  0.4324  0.3838  0.1123  0.5220  0.6281  0.6012  0.1561
63  0.3538  0.6955  0.6094  0.7400  0.3959  0.1365  0.6167  0.3362  0.4726  0.0298
64  0.9097  0.5363  0.7893  0.2859  0.2444  0.9174  0.1916  0.6953  0.5731  0.1238
65  0.3003  0.8331  0.4073  0.5978  0.7982  0.8490  0.5091  0.2284  0.9304  0.3835
66  0.9213  0.2191  0.2513  0.8610  0.0164  0.6989  0.5626  0.1730  0.7527  0.5233
67  0.1620  0.2625  0.5199  0.8706  0.4632  0.7718  0.8889  0.4879  0.1157  0.5953
68  0.9036  0.3261  0.8666  0.0597  0.3230  0.6270  0.1666  0.6606  0.6999  0.8002
69  0.3559  0.4602  0.6895  0.5051  0.2882  0.2182  0.9996  0.1914  0.6046  0.6542

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   3.8e-01  0.3  ...  0.4  1.2e-01
1   4.0e-02  0.2  ...  0.8  6.4e-02
2   1.4e-01  1.0  ...  0.2  2.1e-01
3   1.0e+00  0.4  ...  0.3  7.6e-02
4   8.8e-01  0.1  ...  0.9  8.0e-01
..      ...  ...  ...  ...      ...
65  3.0e-01  0.8  ...  0.9  3.8e-01
66  9.2e-01  0.2  ...  0.8  5.2e-01
67  1.6e-01  0.3  ...  0.1  6.0e-01
68  9.0e-01  0.3  ...  0.7  8.0e-01
69  3.6e-01  0.5  ...  0.6  6.5e-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