1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
from collections import OrderedDict, Iterable
import numpy as np
import pdb
import sys
###Inspire de : https://docs.scipy.org/doc/numpy/user/basics.subclassing.html
class NamedArray(np.ndarray):
def __new__(cls, input_array, names=None):
obj = np.asarray(input_array).view(cls)
obj.colnames = OrderedDict( (name,i) for i,name in enumerate(names) )
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.colnames = getattr(obj, 'colnames', None )
def __repr__(self):
s=super().__repr__()
return s[:-1]+", names="+str(self.names)+")"
def __str__(self):
return ' '.join(self.names)+'\n'+super().__str__()
def Get(self,colname):
if self.ndim == 1 :
return self[ self.colnames[colname] ]
else:
return np.array(self[ :, self.colnames[colname] ])
def __getitem__(self,idx):
if isinstance(idx,str):
return self.Get(idx)
else :
if isinstance(idx,slice):
return NamedArray( super().__getitem__(idx), self.names[idx] )
else :
return super().__getitem__(idx)
def Set(self,colname,val):
#### Pour le 1D, a voir pour le 2D
self[ self.colnames[colname] ] = val
def __setitem__(self,idx,val):
if isinstance(idx,str):
self.Set(idx,val)
else :
super().__setitem__(idx,val)
@property
def names(self):
return list(self.colnames.keys())
arr = np.arange(5)
obj = NamedArray(arr, names=['c0','c1','c2','c3','c4'])
print(type(obj))
print(obj.names)
print(obj) ### call __str__
print(repr(obj)) ### call __repr__
print(obj[1]) ### call __getitem__
print(obj['c1']) ### call __getitem__
print(0.5*obj)
print(obj+obj)
obj[1]=13.0 ### call __setitem__
obj['c0']=17.0 ### call __setitem__
obj[3:5]=[21.0,22.0] ### call __setitem__
print(obj)
print("---")
v = obj[1:3]
print(type(v))
print(v.colnames)
print(v.names)
print(v.Get('c2'))
print(v['c2'])
print(" ----- Test 2D ---- ")
obj = NamedArray([arr,arr+10], names=['c0','c1','c2','c3','c4'])
print(type(obj))
print(obj.names)
print(obj) ### call __str__
print(repr(obj)) ### call __repr__
print(obj[1]) ### call __getitem__
print(obj[:,1]) ### call __getitem__ ### Pb ...
print(obj['c1']) ### call __getitem__
#print(obj[1,'c1'] ### call __getitem__ ### Pas encore possible)
print(0.5*obj)
print(obj+obj)
obj[0,1]=13.0 ### call __setitem__
print(obj)
#obj['c0']=17.0 ### call __setitem__
#obj[3:5]=[21.0,22.0] ### call __setitem__
#print(obj)
print("---")
v = obj[1:3] ### besoin d'avoir un NamedArray1D !
print(type(v))
print(v.colnames)
print(v.names)
print(v)
print(v.Get('c2'))
print(v['c2']) |
Partager