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()
../_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.93826365, -0.03866506, -0.34504865,  0.09277775, -0.39356432,
        0.70055744, -0.96993021, -1.37268801,  1.87372142,  1.92254221,
       -1.2212271 ,  1.70037104,  0.22203085,  1.14862493,  0.21724226,
       -0.19271769,  0.43248342, -0.55581957, -0.60848602,  1.02091905])
#1: 'y = N^2':
array([1.59348459e+00, 1.34914547e-01, 6.55917952e-02, 6.63520311e+00,
       7.42314649e-01, 4.47988028e-01, 2.66723166e+00, 3.36711811e-01,
       2.85767270e+00, 5.75410938e-02, 3.89439992e-01, 3.48085187e-02,
       2.12190530e-02, 3.70150402e-01, 3.29985062e-01, 1.76807881e-02,
       4.10046507e-03, 5.38124026e-01, 1.26842302e+00, 7.87588396e-01])
#2: 'y = N^3':
array([ 1.44996853e+01, -1.54599707e-09, -1.11759295e-03, -3.38564369e-02,
        1.07901205e+01, -8.22878267e-03, -5.83566825e-03, -2.87867024e+00,
        1.35249425e-01, -1.36526874e-04,  1.79796958e-01, -6.15546115e-10,
        6.53891783e-02, -2.58603304e+00,  6.20942720e-02,  7.07641343e-06,
       -6.82883509e-03, -3.46267450e-01, -4.41137935e+00,  1.61947594e+00])
#3: 'y = N^4':
array([1.37778724e-01, 8.24576280e+00, 1.92283547e-01, 1.23581350e-02,
       1.40198040e-02, 2.79947574e-01, 4.10547680e-02, 8.89521178e-03,
       4.27797858e-03, 1.09373192e-02, 3.08557131e+00, 3.03168592e+00,
       4.06902914e+01, 1.15856652e+00, 3.01028035e-01, 2.14689087e-01,
       1.90295433e+02, 2.25842408e+01, 4.46700429e-04, 3.96545602e-01])
#4: 'y = N^5':
array([-3.77561979e-06, -1.68808561e+01,  3.17825808e-03, -3.13047212e-02,
       -6.22415808e+00,  1.38747262e-05, -1.47788014e+01, -3.18075172e-01,
        5.01398865e-07,  4.94690839e-02,  1.95019093e-01,  3.67485210e+00,
       -7.45270326e-04,  2.50458093e-02, -1.92110040e-05, -7.38624825e-01,
        1.06760197e-03,  3.82181119e-02,  8.72110297e+00, -4.06409859e-02])
#5: 'y = N^6':
array([7.17853315e-01, 4.51135956e+00, 6.38679906e-01, 3.48520008e-03,
       6.92204768e+00, 2.52751169e+01, 6.25109010e+00, 6.69449004e+00,
       2.48465650e-05, 4.10227313e-02, 2.43857127e-02, 4.92019180e-01,
       1.61665934e+02, 9.77065637e-06, 2.10600339e-06, 3.67496690e-03,
       2.84710634e-04, 9.24768322e-01, 1.38896692e+00, 1.26142011e+00])
The first set of results is
[ 1.93826365 -0.03866506 -0.34504865  0.09277775 -0.39356432  0.70055744
 -0.96993021 -1.37268801  1.87372142  1.92254221 -1.2212271   1.70037104
  0.22203085  1.14862493  0.21724226 -0.19271769  0.43248342 -0.55581957
 -0.60848602  1.02091905]
The first set of results has median
0.155 (95% CI: -1.301, 1.931)

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.344711  0.025948  0.039037  0.198749  0.293299  0.998667  0.178582
1   0.184400  0.467361  0.965332  0.860354  0.938906  0.397039  0.542148
2   0.584030  0.080243  0.057049  0.633673  0.922454  0.453988  0.568772
3   0.804503  0.055101  0.748696  0.134160  0.176520  0.912554  0.689494
4   0.941144  0.349468  0.596023  0.554890  0.610681  0.092607  0.299862
..       ...       ...       ...       ...       ...       ...       ...
65  0.442133  0.273734  0.512207  0.779552  0.948970  0.995370  0.769447
66  0.289587  0.966686  0.863013  0.372953  0.700086  0.925574  0.260379
67  0.507107  0.902911  0.702278  0.888355  0.054236  0.619780  0.419559
68  0.779561  0.856486  0.141996  0.344277  0.444707  0.371439  0.978246
69  0.882835  0.615402  0.473032  0.714634  0.290312  0.003249  0.326788

           7         8         9
0   0.596108  0.718533  0.806508
1   0.717750  0.803145  0.300739
2   0.599953  0.908333  0.443065
3   0.415991  0.808797  0.063251
4   0.887026  0.353526  0.296492
..       ...       ...       ...
65  0.618468  0.953310  0.420598
66  0.522988  0.883923  0.182372
67  0.152385  0.621007  0.539545
68  0.565560  0.792542  0.034531
69  0.028347  0.733535  0.821602

[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.3447  0.0259  0.0390  0.1987  0.2933  0.9987  0.1786  0.5961  0.7185  0.8065
1   0.1844  0.4674  0.9653  0.8604  0.9389  0.3970  0.5421  0.7178  0.8031  0.3007
2   0.5840  0.0802  0.0570  0.6337  0.9225  0.4540  0.5688  0.6000  0.9083  0.4431
3   0.8045  0.0551  0.7487  0.1342  0.1765  0.9126  0.6895  0.4160  0.8088  0.0633
4   0.9411  0.3495  0.5960  0.5549  0.6107  0.0926  0.2999  0.8870  0.3535  0.2965
5   0.5623  0.9116  0.5453  0.5366  0.5329  0.4139  0.9062  0.2844  0.9039  0.1569
6   0.1310  0.2206  0.4786  0.7268  0.2295  0.0699  0.1989  0.6147  0.4936  0.8712
7   0.6408  0.4123  0.6197  0.5885  0.3791  0.4600  0.8099  0.1475  0.0940  0.9788
8   0.0932  0.7985  0.2137  0.9866  0.9984  0.0996  0.3907  0.1850  0.0138  0.7480
9   0.0633  0.9023  0.6943  0.6029  0.7611  0.2827  0.0298  0.8656  0.6740  0.4151
10  0.2878  0.1100  0.9141  0.7857  0.7953  0.2276  0.2100  0.3783  0.9508  0.8758
11  0.3570  0.8368  0.4137  0.0541  0.6327  0.7110  0.6717  0.6753  0.2170  0.9869
12  0.3589  0.1975  0.5163  0.9087  0.8508  0.5097  0.2370  0.1341  0.5198  0.8095
13  0.9097  0.0238  0.0059  0.7227  0.4666  0.3459  0.8809  0.7345  0.0125  0.2330
14  0.5939  0.4465  0.6320  0.0464  0.7577  0.9164  0.9507  0.1983  0.5593  0.9877
15  0.3106  0.7712  0.1528  0.3345  0.5947  0.2494  0.6407  0.7188  0.0665  0.9387
16  0.3032  0.3956  0.8152  0.3253  0.9117  0.9234  0.8966  0.6142  0.4486  0.6666
17  0.2034  0.3431  0.0657  0.9486  0.3965  0.7111  0.5003  0.6901  0.9907  0.6154
18  0.4413  0.9223  0.4151  0.9997  0.3202  0.1511  0.9435  0.5479  0.1517  0.3069
19  0.9498  0.3672  0.2020  0.5653  0.5062  0.1720  0.8547  0.7258  0.4115  0.4437
20  0.5489  0.6647  0.3989  0.7945  0.7795  0.1842  0.5467  0.8812  0.4446  0.5553
21  0.8299  0.7578  0.2317  0.6475  0.9877  0.7242  0.1378  0.9443  0.4424  0.3563
22  0.6761  0.2358  0.6500  0.9604  0.1877  0.6471  0.7559  0.3017  0.8793  0.9740
23  0.7096  0.0475  0.2616  0.0046  0.6468  0.7780  0.0297  0.1445  0.0286  0.3870
24  0.3820  0.9233  0.4569  0.4371  0.5452  0.4652  0.6690  0.0750  0.7400  0.9864
25  0.1989  0.9522  0.0773  0.0801  0.2506  0.7748  0.0527  0.4791  0.2350  0.5678
26  0.6843  0.0855  0.5855  0.9489  0.0535  0.8248  0.2914  0.6170  0.9596  0.6738
27  0.2422  0.4359  0.5155  0.3777  0.1513  0.7915  0.1172  0.1182  0.7717  0.2019
28  0.2584  0.1499  0.6625  0.0300  0.3234  0.2804  0.4530  0.7660  0.9513  0.2967
29  0.4471  0.2115  0.2969  0.8948  0.9605  0.3932  0.3862  0.4234  0.4788  0.6335
30  0.5460  0.1225  0.4156  0.2100  0.4761  0.0439  0.3215  0.1782  0.5238  0.7386
31  0.6796  0.3515  0.2436  0.8954  0.3742  0.8924  0.9817  0.6523  0.8769  0.2253
32  0.9606  0.8930  0.1193  0.3446  0.6950  0.9172  0.0029  0.1891  0.4720  0.4707
33  0.4536  0.7376  0.0720  0.4278  0.1957  0.1182  0.8163  0.7205  0.7107  0.3809
34  0.7737  0.3206  0.1579  0.9385  0.7172  0.8746  0.9102  0.5950  0.5803  0.8723
35  0.8749  0.5364  0.5714  0.3395  0.3688  0.3017  0.3607  0.8517  0.7086  0.5180
36  0.7614  0.7365  0.8980  0.6695  0.0173  0.7895  0.8747  0.4037  0.3800  0.6477
37  0.9204  0.0407  0.4380  0.2219  0.8590  0.1351  0.1174  0.4980  0.5137  0.3941
38  0.9329  0.4360  0.4271  0.3316  0.6231  0.6864  0.1639  0.2639  0.7624  0.8998
39  0.2249  0.7761  0.9423  0.9461  0.0791  0.3983  0.6810  0.9281  0.9159  0.6834
40  0.2668  0.3161  0.2206  0.7767  0.7137  0.8427  0.5914  0.7160  0.0698  0.2878
41  0.1916  0.8434  0.1215  0.5971  0.1881  0.5596  0.0402  0.1261  0.0879  0.2729
42  0.9317  0.8306  0.4804  0.4212  0.4526  0.0076  0.1574  0.3674  0.8487  0.9566
43  0.3590  0.7936  0.7436  0.3425  0.6633  0.8227  0.8358  0.9855  0.4410  0.8365
44  0.5627  0.7628  0.0878  0.6920  0.7662  0.2899  0.1270  0.4669  0.4727  0.2095
45  0.3150  0.6415  0.8537  0.7931  0.8200  0.6010  0.4907  0.8761  0.0410  0.6082
46  0.1458  0.7248  0.2133  0.2081  0.6180  0.1596  0.7032  0.6522  0.9308  0.9635
47  0.3732  0.3500  0.9273  0.4461  0.4147  0.8010  0.4649  0.7569  0.9572  0.9304
48  0.2336  0.3899  0.6161  0.9925  0.2198  0.8520  0.6915  0.8859  0.1137  0.1745
49  0.9034  0.3892  0.0444  0.9515  0.8071  0.7186  0.6924  0.1621  0.9082  0.3757
50  0.4106  0.0143  0.0196  0.6987  0.6447  0.2032  0.1534  0.7176  0.3182  0.8543
51  0.0995  0.1346  0.6315  0.1687  0.9410  0.9178  0.4135  0.2899  0.2406  0.8338
52  0.8890  0.4008  0.7723  0.7759  0.6896  0.6272  0.6518  0.5743  0.8197  0.5220
53  0.7128  0.4054  0.6859  0.6506  0.9821  0.4412  0.9514  0.1447  0.4806  0.6465
54  0.2575  0.6705  0.8910  0.1553  0.9941  0.1136  0.2206  0.1798  0.8934  0.6335
55  0.9400  0.9072  0.6877  0.2958  0.6885  0.3825  0.7699  0.3551  0.2161  0.9990
56  0.0359  0.1680  0.9099  0.1909  0.6388  0.7723  0.2934  0.8413  0.9479  0.3262
57  0.1894  0.2782  0.6199  0.5606  0.8122  0.5266  0.2209  0.9402  0.5536  0.6695
58  0.3380  0.4820  0.7674  0.9873  0.9224  0.5538  0.0343  0.4140  0.7822  0.0595
59  0.5803  0.0248  0.4506  0.7590  0.7598  0.0296  0.9346  0.1184  0.7148  0.4743
60  0.5769  0.2103  0.3108  0.3811  0.0461  0.5426  0.2981  0.6641  0.4351  0.7652
61  0.8110  0.9277  0.2839  0.0907  0.8315  0.1776  0.6546  0.0046  0.8558  0.1839
62  0.6308  0.7462  0.5533  0.2420  0.3425  0.8223  0.1589  0.5787  0.2054  0.5141
63  0.4347  0.8864  0.7137  0.3963  0.3979  0.2709  0.5873  0.5278  0.7180  0.0073
64  0.8057  0.4493  0.1803  0.3154  0.3307  0.4659  0.4877  0.3824  0.2203  0.2240
65  0.4421  0.2737  0.5122  0.7796  0.9490  0.9954  0.7694  0.6185  0.9533  0.4206
66  0.2896  0.9667  0.8630  0.3730  0.7001  0.9256  0.2604  0.5230  0.8839  0.1824
67  0.5071  0.9029  0.7023  0.8884  0.0542  0.6198  0.4196  0.1524  0.6210  0.5395
68  0.7796  0.8565  0.1420  0.3443  0.4447  0.3714  0.9782  0.5656  0.7925  0.0345
69  0.8828  0.6154  0.4730  0.7146  0.2903  0.0032  0.3268  0.0283  0.7335  0.8216

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   0.3  2.6e-02  ...  0.7  8.1e-01
1   0.2  4.7e-01  ...  0.8  3.0e-01
2   0.6  8.0e-02  ...  0.9  4.4e-01
3   0.8  5.5e-02  ...  0.8  6.3e-02
4   0.9  3.5e-01  ...  0.4  3.0e-01
..  ...      ...  ...  ...      ...
65  0.4  2.7e-01  ...  1.0  4.2e-01
66  0.3  9.7e-01  ...  0.9  1.8e-01
67  0.5  9.0e-01  ...  0.6  5.4e-01
68  0.8  8.6e-01  ...  0.8  3.5e-02
69  0.9  6.2e-01  ...  0.7  8.2e-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