In [1]:
from dynd import nd, ndt
In [3]:
a = nd.array([('Smith', 'John', '1979-01-22'),
('Katz', 'Barbara', '1990-12-03'),
('Barker', 'Henry', '1979-06-12')],
dtype='{lastname: string(32); firstname: string(32); birthday: date}')
In [4]:
a
Out[4]:
Because we used fixed-buffer strings, we can reassign their values and convert them into NumPy.
In [5]:
a[2].firstname = 'George'
In [6]:
nd.as_numpy(a, allow_copy=True)
Out[6]:
Now let's add our two computed fields.
The first one, 'fullname', is simple, we simply concatenate the first and last name strings together. The second one, 'age', is a little trickier. There doesn't seem to be a simple one-liner for this, and the code here will crash on February 29th, but hopefully it demonstrates the idea nicely.
In [7]:
b = nd.add_computed_fields(a,
[('fullname', ndt.string,
'firstname + " " + lastname'),
('age', ndt.int32,
'date.today().year - birthday.year - 1 + (date.today().replace(year=birthday.year) >= birthday)')])
Now 'b' is a deferred evaluation object, with a fairly complicated dynd type. You don't need to know what's going on in the type printout, but here it is for show.
In [9]:
nd.type_of(b)
Out[9]:
We can evaluate back to an object with no deferred expression using the 'eval' method.
In [10]:
b.eval()
Out[10]:
In [11]:
print(nd.as_py(b[1]))
print(nd.as_py(b.age))
In [12]:
a[1] = ['Ford', 'Carol', '1967-05-12']
In [13]:
print(nd.as_py(b[1]))
print(nd.as_py(b.age))