@@ -100,7 +100,8 @@ def __init__(self, labels, name=None):
100
100
if isinstance (name , str ) and not name_is_python_str :
101
101
name = str (name )
102
102
if name is not None and not isinstance (name , (int , str )):
103
- raise TypeError ("Axis name should be None, int or str but is: %s (%s)" % (name , type (name ).__name__ ))
103
+ nametype = type (name ).__name__
104
+ raise TypeError (f"Axis name should be None, int or str but is: { name } ({ nametype } )" )
104
105
self .name = name
105
106
self ._labels = None
106
107
self .__mapping = None
@@ -349,12 +350,12 @@ def split(self, sep='_', names=None, regex=None, return_labels=False):
349
350
if self .name is None :
350
351
names = None
351
352
elif sep not in self .name :
352
- raise ValueError ('{ } not found in self name ({})' . format ( sep , self .name ) )
353
+ raise ValueError (f' { sep } not found in self name ({ self .name } )' )
353
354
else :
354
355
names = self .name .split (sep )
355
356
elif isinstance (names , str ):
356
357
if sep not in names :
357
- raise ValueError ('{ } not found in names ({})'. format ( sep , names ) )
358
+ raise ValueError (f' { sep } not found in names ({ names } )' )
358
359
else :
359
360
names = names .split (sep )
360
361
else :
@@ -470,17 +471,19 @@ def _group(self, *args, **kwargs):
470
471
"""
471
472
name = kwargs .pop ('name' , None )
472
473
if kwargs :
473
- raise ValueError ("invalid keyword argument(s): %s" % list (kwargs .keys ()))
474
+ invalid_kwargs = list (kwargs .keys ())
475
+ raise ValueError (f"invalid keyword argument(s): { invalid_kwargs } " )
474
476
key = args [0 ] if len (args ) == 1 else args
475
477
return self [key ] >> name if name else self [key ]
476
478
477
479
def group (self , * args , ** kwargs ):
478
480
group_name = kwargs .pop ('name' , None )
479
481
key = args [0 ] if len (args ) == 1 else args
480
- syntax = '{}[{}]' .format (self .name if self .name else 'axis' , key )
482
+ name = self .name if self .name else 'axis'
483
+ syntax = f'{ name } [{ key } ]'
481
484
if group_name is not None :
482
- syntax += ' >> {}' . format ( repr (group_name ))
483
- raise NotImplementedError ('Axis.group is deprecated. Use {} instead.' . format ( syntax ) )
485
+ syntax += f ' >> { repr (group_name )} '
486
+ raise NotImplementedError (f 'Axis.group is deprecated. Use { syntax } instead.' )
484
487
485
488
def all (self , name = None ):
486
489
r"""
@@ -493,8 +496,7 @@ def all(self, name=None):
493
496
"""
494
497
axis_name = self .name if self .name else 'axis'
495
498
group_name = name if name else 'all'
496
- raise NotImplementedError ('Axis.all is deprecated. Use {}[:] >> {} instead.'
497
- .format (axis_name , repr (group_name )))
499
+ raise NotImplementedError (f'Axis.all is deprecated. Use { axis_name } [:] >> { repr (group_name )} instead.' )
498
500
499
501
# TODO: make this method private
500
502
def subaxis (self , key ):
@@ -939,7 +941,7 @@ def index(self, key):
939
941
else :
940
942
# the first mapping[key] above will cover most cases.
941
943
# This code path is only used if the key was g
10000
iven in "non normalized form"
942
- assert np .isscalar (key ), "%s (%s) is not scalar" % ( key , type ( key ))
944
+ assert np .isscalar (key ), f" { key } ( { type ( key ) } ) is not scalar"
943
945
# key is scalar (integer, float, string, ...)
944
946
if self ._is_key_type_compatible (key ):
945
947
return mapping [key ]
@@ -963,7 +965,7 @@ def __str__(self):
963
965
964
966
def __repr__ (self ):
965
967
labels = len (self ) if self .iswildcard else list (self .labels )
966
- return 'Axis(%r, %r)' % ( labels , self .name )
968
+ return f 'Axis({ labels !r } , { self .name !r } )'
967
969
968
970
def labels_summary (self ):
969
971
r"""
@@ -983,7 +985,7 @@ def _binop(opname):
983
985
r"""
984
986
Method factory to create binary operators special methods.
985
987
"""
986
- fullname = '__%s__' % opname
988
+ fullname = f '__{ opname } __'
987
989
988
990
def opmethod (self , other ):
989
991
# give a chance to AxisCollection.__rXXX__ ops to trigger
@@ -1089,13 +1091,13 @@ def replace(self, old, new=None):
1089
1091
new = list (old .values ())
1090
1092
old = list (old .keys ())
1091
1093
elif np .isscalar (old ):
1092
- assert new is not None and np .isscalar (new ), "%s is not a scalar but a %s" % ( new , type (new ).__name__ )
1094
+ assert new is not None and np .isscalar (new ), f" { new } is not a scalar but a { type (new ).__name__ } "
1093
1095
old = [old ]
1094
1096
new = [new ]
1095
1097
else :
1096
1098
seq = (tuple , list , np .ndarray )
1097
- assert isinstance (old , seq ), "%s is not a sequence but a %s" % ( old , type (old ).__name__ )
1098
- assert isinstance (new , seq ), "%s is not a sequence but a %s" % ( new , type (new ).__name__ )
1099
+ assert isinstance (old , seq ), f" { old } is not a sequence but a { type (old ).__name__ } "
1100
+ assert isinstance (new , seq ), f" { new } is not a sequence but a { type (new ).__name__ } "
1099
1101
assert len (old ) == len (new )
1100
1102
# using object dtype because new labels length can be larger than the fixed str length in the self.labels array
1101
1103
labels = self .labels .astype (object )
@@ -1470,9 +1472,9 @@ def __init__(self, axes=None):
1470
1472
dupe_axes = list (duplicates (axes ))
1471
1473
if dupe_axes :
1472
1474
axis = dupe_axes [0 ]
1473
- raise ValueError ("Cannot have multiple occurrences of the same axis object in a collection ('%s' -- %s "
1474
- " with id %d ). Several axes with the same name are allowed though (but not recommended). "
1475
- % ( axis . name , axis . labels_summary (), id ( axis )) )
1475
+ raise ValueError (f "Cannot have multiple occurrences of the same axis object in a collection ('{ axis . name } ' "
1476
+ f" -- { axis . labels_summary () } with id { id ( axis ):d } ). Several axes with the same name are "
1477
+ f"allowed though (but not recommended)." )
1476
1478
self ._list = axes
1477
1479
self ._map = {axis .name : axis for axis in axes if axis .name is not None }
1478
1480
@@ -1592,7 +1594,7 @@ def __getitem__(self, key):
1592
1594
# transform ValueError to KeyError
1593
1595
except ValueError :
1594
1596
if key .name is None :
1595
- raise KeyError ("axis '%s ' not found in %s" % ( key , self ) )
1597
+ raise KeyError (f "axis '{ key } ' not found in { self } " )
1596
1598
else :
1597
1599
# we should NOT check that the object is the same, so that we can use AxisReference objects to
1598
1600
# target real axes
@@ -1616,13 +1618,13 @@ def __getitem__(self, key):
1616
1618
elif isinstance (key , slice ):
1617
1619
return AxisCollection (self ._list [key ])
1618
1620
elif key is None :
1619
- raise KeyError ("axis '%s ' not found in %s" % ( key , self ) )
1621
+ raise KeyError (f "axis '{ key } ' not found in { self } " )
1620
1622
else :
1621
1623
assert isinstance (key , str ), type (key )
1622
1624
if key in self ._map :
1623
1625
return self ._map [key ]
1624
1626
else :
1625
- raise KeyError ("axis '%s ' not found in %s" % ( key , self ) )
1627
+ raise KeyError (f "axis '{ key } ' not found in { self } " )
1626
1628
1627
1629
def _ipython_key_completions_ (self ):
1628
1630
return list (self ._map .keys ())
@@ -1664,9 +1666,9 @@ def get_by_pos(self, key, i):
1664
1666
if res .iscompatible (key ):
1665
1667
return res
1666
1668
else :
1667
- raise ValueError ("axis %s is not compatible with %s" % ( res , key ) )
1669
+ raise ValueError (f "axis { res } is not compatible with { key } " )
1668
1670
# XXX: KeyError instead?
1669
- raise ValueError ("axis %s not found in %s" % ( key , self ) )
1671
+ raise ValueError (f "axis { key } not found in { self } " )
1670
1672
else :
1671
1673
return self [key ]
1672
1674
@@ -1827,15 +1829,17 @@ def __len__(self):
1827
1829
ndim = property (__len__ )
1828
1830
1829
1831
def __str__ (self ):
1830
- return "{%s}" % ', ' .join (self .display_names )
1832
+ names = ', ' .join (self .display_names )
1833
+ return f"{{{ names } }}"
1831
1834
1832
1835
def __repr__ (self ):
1833
1836
if len (self ):
1834
1837
repr_per_axis = [repr (axis ) for axis in self ._list ]
1835
- axes_repr = "\n {}\n " .format (',\n ' .join (repr_per_axis ))
1838
+ axes_repr = ',\n ' .join (repr_per_axis )
1839
+ axes_repr = f"\n { axes_repr } \n "
1836
1840
else :
1837
1841
axes_repr = ""
1838
- return "AxisCollection([{}])" . format ( axes_repr )
1842
+ return f "AxisCollection([{ axes_repr } ])"
1839
1843
1840
1844
# TODO: kill name argument (does not seem to be used anywhere
1841
1845
def get (self , key , default = None , name = None ):
@@ -2006,7 +2010,7 @@ def check_compatible(self, axes):
2006
2010
for i , axis in enumerate (axes ):
2007
2011
local_axis = self .get_by_pos (axis , i )
2008
2012
if not local_axis .iscompatible (axis ):
2009
- raise ValueError ("incompatible axes:\n {!r}\n vs\n {!r}" . format ( axis , local_axis ) )
2013
+ raise ValueError (f "incompatible axes:\n { axis !r} \n vs\n { local_axis !r} " )
2010
2014
2011
2015
# XXX: deprecate method (functionality is duplicated in union)?
2012
2016
# I am not so sure anymore we need to actually deprecate the method: having both methods with the same
@@ -2046,7 +2050,7 @@ def extend(self, axes, validate=True, replace_wildcards=False):
2046
2050
"""
2047
2051
# axes should be a sequence
2048
2052
if not isinstance (axes , (tuple , list , AxisCollection )):
2049
- raise TypeError ("AxisCollection can only be extended by a sequence of Axis, not %s" % type (axes ).__name__ )
2053
+ raise TypeError (f "AxisCollection can only be extended by a sequence of Axis, not { type (axes ).__name__ } " )
2050
2054
# check that common axes are the same
2051
2055
# if validate:
2052
2056
# self.check_compatible(axes)
@@ -2070,7 +2074,7 @@ def get_axis(col, i, axis):
2070
2074
else :
2071
2075
# check that common axes are the same
2072
2076
if validate and not old_axis .iscompatible (axis ):
2073
- raise ValueError ("incompatible axes:\n %r \n vs\n %r" % ( axis , old_axis ) )
2077
+ raise ValueError (f "incompatible axes:\n { axis !r } \n vs\n { old_axis !r } " )
2074
2078
if replace_wildcards and old_axis .iswildcard :
2075
2079
self [old_axis ] = axis
2076
2080
@@ -2115,7 +2119,7 @@ def index(self, axis, compatible=False):
2115
2119
if - len (self ) <= axis < len (self ):
2116
2120
return axis
2117
2121
else :
2118
- raise ValueError ("axis %d is not in collection" % axis )
2122
+ raise ValueError (f "axis { axis } is not in collection" )
2119
2123
elif isinstance (axis , Axis ):
2120
2124
try :
2121
2125
# 1) first look for that particular axis object
@@ -2146,7 +2150,7 @@ def index(self, axis, compatible=False):
2146
2150
else :
2147
2151
name = axis
2148
2152
if name is None :
2149
- raise ValueError ("%r is not in collection" % axis )
2153
+ raise ValueError (f" { axis !r } is not in collection" )
2150
2154
return self .names .index (name )
2151
2155
2152
2156
# XXX: we might want to return a new AxisCollection (same question for other inplace operations:
@@ -2327,7 +2331,7 @@ def replace(self, axes_to_replace=None, new_axis=None, inplace=False, **kwargs):
2327
2331
if isinstance (axes_to_replace , (list , AxisCollection )) and \
2328
2332
all ([isinstance (axis , Axis ) for axis in axes_to_replace ]):
2329
2333
if len (axes_to_replace ) != len (self ):
2330
- raise ValueError ('{ } axes given as argument, expected {}' . format ( len (axes_to_replace ), len ( self )) )
2334
+ raise ValueError (f' { len ( axes_to_replace ) } axes given as argument, expected { len (self )} ' )
2331
2335
axes = axes_to_replace
2332
2336
else :
2333
2337
axes = self if inplace else self [:]
@@ -2372,11 +2376,11 @@ def _guess_axis(self, axis_key):
2372
2376
except KeyError :
2373
2377
continue
2374
2378
if not valid_axes :
2375
- raise ValueError ("%s is not a valid label for any axis" % axis_key )
2379
+ raise ValueError (f" { axis_key } is not a valid label for any axis" )
2376
2380
elif len (valid_axes ) > 1 :
2377
- valid_axes = ', ' .join (a .name if a .name is not None else '{{{}}}' . format ( self .axes .index (a ))
2381
+ valid_axes = ', ' .join (a .name if a .name is not None else f '{{{ self .axes .index (a )} }}'
2378
2382
for a in valid_axes )
2379
- raise ValueError ('%s is ambiguous (valid in %s)' % ( axis_key , valid_axes ) )
2383
+ raise ValueError (f' { axis_key } is ambiguous (valid in { valid_axes } )' )
2380
2384
return valid_axes [0 ][axis_key ]
2381
2385
2382
2386
def set_labels (self , axis = None , labels = None , inplace = False , ** kwargs ):
@@ -2616,7 +2620,7 @@ def _translate_axis_key_chunk(self, axis_key):
2616
2620
try :
2617
2621
axis_pos_key = real_axis .index (axis_key )
2618
2622
except KeyError :
2619
- raise ValueError ("%r is not a valid label for any axis" % axis_key )
2623
+ raise ValueError (f" { axis_key !r } is not a valid label for any axis" )
2620
2624
return real_axis .i [axis_pos_key ]
2621
2625
except KeyError :
2622
2626
# axis associated with axis_key may not belong to self.
@@ -2636,13 +2640,13 @@ def _translate_axis_key_chunk(self, axis_key):
2636
2640
except KeyError :
2637
2641
continue
2638
2642
if not valid_axes :
2639
- raise ValueError ("%r is not a valid label for any axis" % axis_key )
2643
+ raise ValueError (f" { axis_key !r } is not a valid label for any axis" )
2640
2644
elif len (valid_axes ) > 1 :
2641
2645
# TODO: make an AxisCollection.display_name(axis) method out of this
2642
2646
# valid_axes = ', '.join(self.display_name(axis) for a in valid_axes)
2643
- valid_axes = ', ' .join (a .name if a .name is not None else '{{{}}}' . format ( self .index (a ))
2647
+ valid_axes = ', ' .join (a .name if a .name is not None else f '{{{ self .index (a )} }}'
2644
2648
for a in valid_axes )
2645
- raise ValueError ('%s is ambiguous (valid in %s)' % ( axis_key , valid_axes ) )
2649
+ raise ValueError (f' { axis_key } is ambiguous (valid in { valid_axes } )' )
2646
2650
return valid_axes [0 ].i [axis_pos_key ]
2647
2651
2648
2652
def _translate_axis_key (self , axis_key ):
@@ -2755,8 +2759,7 @@ def _key_to_igroups(self, key):
2755
2759
if isinstance (axis_key , Array ) and np .issubdtype (axis_key .dtype , np .bool_ ):
2756
2760
extra_key_axes = axis_key .axes - self
2757
2761
if extra_key_axes :
2758
- raise ValueError ("boolean subset key contains more axes ({}) than array ({})"
2759
- .format (axis_key .axes , self ))
2762
+ raise ValueError (f"boolean subset key contains more axes ({ axis_key .axes } ) than array ({ self } )" )
2760
2763
# nonzero (currently) returns a tuple of IGroups containing 1D Arrays (one IGroup per axis)
2761
2764
nonboolkey .extend (axis_key .nonzero ())
2762
2765
else :
@@ -2997,7 +3000,7 @@ def display_names(self):
2997
3000
['a', 'b*', '{2}', '{3}*']
2998
3001
"""
2999
3002
def display_name (i , axis ):
3000
- name = axis .name if axis .name is not None else '{%d}' % i
3003
+ name = axis .name if axis .name is not None else f'{{ { i } }}'
3001
3004
return (name + '*' ) if axis .iswildcard else name
3002
3005
3003
3006
return [display_name (i , axis ) for i , axis in enumerate (self ._list )]
@@ -3114,7 +3117,7 @@ def info(self):
3114
3117
sex [2]: 'M' 'F'
3115
3118
time [4]: 2007 2008 2009 2010
3116
3119
"""
3117
- lines = [" %s [%d]: %s" % ( name , len (axis ), axis .labels_summary ())
3120
+ lines = [f" { name } [ { len (axis )} ]: { axis .labels_summary ()} "
3118
3121
for name , axis in zip (self .display_names , self ._list )]
3119
3122
shape = " x " .join (str (s ) for s in self .shape )
3120
3123
return ReprString ('\n ' .join ([shape ] + lines ))
@@ -3576,7 +3579,7 @@ def index(self, key):
3576
3579
raise NotImplementedError ("an AxisReference (X.) cannot translate labels" )
3577
3580
3578
3581
def __repr__ (self ):
3579
- return 'AxisReference(%r)' % self .name
3582
+ return f 'AxisReference({ self .name !r } )'
3580
3583
3581
3584
def evaluate (self , context ):
3582
3585
r"""
0 commit comments