Python3 best way to define and use multiple 2D data

Viewed 33

I have a large set of data: for about 10 asset classes, the interest rate for each year for around a hundred years. I had been using a dictionary structure so that I could access the rate for the year like this:

rate = asset_class_1.get(year)

But defining it is cumbersome, and I would prefer to access the asset_class as part of a broader data structure -- so a 2D dictionary. Is there any better way?

1 Answers

Use a Pandas DataFrame.

import pandas as pd

# Example data
asset_class_1 = {y: r for y, r in zip(range(1901, 2000), range(1, 100))}
asset_class_2 = {y: r+100 for y, r in zip(range(1901, 2000), range(1, 100))}

asset_classes = pd.DataFrame({'class_1': asset_class_1, 'class_2': asset_class_2})
>>> asset_classes
      class_1  class_2
1901        1      101
1902        2      102
1903        3      103
1904        4      104
1905        5      105
...       ...      ...
1995       95      195
1996       96      196
1997       97      197
1998       98      198
1999       99      199

[99 rows x 2 columns]
>>> asset_classes['class_1'][1959]
59

You can also select whole columns or whole rows:

>>> asset_classes['class_1']
1901     1
1902     2
1903     3
1904     4
1905     5
        ..
1995    95
1996    96
1997    97
1998    98
1999    99
Name: class_1, Length: 99, dtype: int64
>>> asset_classes.loc[[1959]]
      class_1  class_2
1959       59      159

Check out the Getting started tutorials for a quick intro to the data structures.

Related