Skip to content

Commit c08056a

Browse files
ganevgvproost
authored andcommitted
CLN: f-string in pandas/core/arrays/sparse/* (pandas-dev#30121)
1 parent b85e5ee commit c08056a

File tree

4 files changed

+30
-51
lines changed

4 files changed

+30
-51
lines changed

pandas/core/arrays/sparse/accessor.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -323,13 +323,7 @@ def _prep_index(data, index, columns):
323323
columns = ibase.default_index(K)
324324

325325
if len(columns) != K:
326-
raise ValueError(
327-
"Column length mismatch: {columns} vs. {K}".format(
328-
columns=len(columns), K=K
329-
)
330-
)
326+
raise ValueError(f"Column length mismatch: {len(columns)} vs. {K}")
331327
if len(index) != N:
332-
raise ValueError(
333-
"Index length mismatch: {index} vs. {N}".format(index=len(index), N=N)
334-
)
328+
raise ValueError(f"Index length mismatch: {len(index)} vs. {N}")
335329
return index, columns

pandas/core/arrays/sparse/array.py

+21-34
Original file line numberDiff line numberDiff line change
@@ -143,13 +143,13 @@ def _sparse_array_op(
143143
name = name[1:]
144144

145145
if name in ("and", "or") and dtype == "bool":
146-
opname = "sparse_{name}_uint8".format(name=name)
146+
opname = f"sparse_{name}_uint8"
147147
# to make template simple, cast here
148148
left_sp_values = left.sp_values.view(np.uint8)
149149
right_sp_values = right.sp_values.view(np.uint8)
150150
result_dtype = np.bool
151151
else:
152-
opname = "sparse_{name}_{dtype}".format(name=name, dtype=dtype)
152+
opname = f"sparse_{name}_{dtype}"
153153
left_sp_values = left.sp_values
154154
right_sp_values = right.sp_values
155155

@@ -364,16 +364,16 @@ def __init__(
364364
sparse_values = np.asarray(data, dtype=dtype)
365365
if len(sparse_values) != sparse_index.npoints:
366366
raise AssertionError(
367-
"Non array-like type {type} must "
368-
"have the same length as the index".format(type=type(sparse_values))
367+
f"Non array-like type {type(sparse_values)} must "
368+
"have the same length as the index"
369369
)
370370
self._sparse_index = sparse_index
371371
self._sparse_values = sparse_values
372372
self._dtype = SparseDtype(sparse_values.dtype, fill_value)
373373

374374
@classmethod
375375
def _simple_new(
376-
cls, sparse_array: np.ndarray, sparse_index: SparseIndex, dtype: SparseDtype,
376+
cls, sparse_array: np.ndarray, sparse_index: SparseIndex, dtype: SparseDtype
377377
) -> "SparseArray":
378378
new = cls([])
379379
new._sparse_index = sparse_index
@@ -412,7 +412,7 @@ def from_spmatrix(cls, data):
412412
length, ncol = data.shape
413413

414414
if ncol != 1:
415-
raise ValueError("'data' must have a single column, not '{}'".format(ncol))
415+
raise ValueError(f"'data' must have a single column, not '{ncol}'")
416416

417417
# our sparse index classes require that the positions be strictly
418418
# increasing. So we need to sort loc, and arr accordingly.
@@ -771,7 +771,7 @@ def __getitem__(self, key):
771771
elif hasattr(key, "__len__"):
772772
return self.take(key)
773773
else:
774-
raise ValueError("Cannot slice with '{}'".format(key))
774+
raise ValueError(f"Cannot slice with '{key}'")
775775

776776
return type(self)(data_slice, kind=self.kind)
777777

@@ -791,9 +791,7 @@ def _get_val_at(self, loc):
791791

792792
def take(self, indices, allow_fill=False, fill_value=None):
793793
if is_scalar(indices):
794-
raise ValueError(
795-
"'indices' must be an array, not a scalar '{}'.".format(indices)
796-
)
794+
raise ValueError(f"'indices' must be an array, not a scalar '{indices}'.")
797795
indices = np.asarray(indices, dtype=np.int32)
798796

799797
if indices.size == 0:
@@ -932,8 +930,8 @@ def _concat_same_type(cls, to_concat):
932930
if not (len(set(fill_values)) == 1 or isna(fill_values).all()):
933931
warnings.warn(
934932
"Concatenating sparse arrays with multiple fill "
935-
"values: '{}'. Picking the first and "
936-
"converting the rest.".format(fill_values),
933+
f"values: '{fill_values}'. Picking the first and "
934+
"converting the rest.",
937935
PerformanceWarning,
938936
stacklevel=6,
939937
)
@@ -1153,11 +1151,7 @@ def _reduce(self, name, skipna=True, **kwargs):
11531151
method = getattr(self, name, None)
11541152

11551153
if method is None:
1156-
raise TypeError(
1157-
"cannot perform {name} with type {dtype}".format(
1158-
name=name, dtype=self.dtype
1159-
)
1160-
)
1154+
raise TypeError(f"cannot perform {name} with type {self.dtype}")
11611155

11621156
if skipna:
11631157
arr = self
@@ -1253,7 +1247,7 @@ def cumsum(self, axis=0, *args, **kwargs):
12531247
nv.validate_cumsum(args, kwargs)
12541248

12551249
if axis is not None and axis >= self.ndim: # Mimic ndarray behaviour.
1256-
raise ValueError("axis(={axis}) out of bounds".format(axis=axis))
1250+
raise ValueError(f"axis(={axis}) out of bounds")
12571251

12581252
if not self._null_fill_value:
12591253
return SparseArray(self.to_dense()).cumsum()
@@ -1367,7 +1361,7 @@ def sparse_unary_method(self) -> "SparseArray":
13671361
dtype = SparseDtype(values.dtype, fill_value)
13681362
return cls._simple_new(values, self.sp_index, dtype)
13691363

1370-
name = "__{name}__".format(name=op.__name__)
1364+
name = f"__{op.__name__}__"
13711365
return compat.set_function_name(sparse_unary_method, name, cls)
13721366

13731367
@classmethod
@@ -1401,11 +1395,7 @@ def sparse_arithmetic_method(self, other):
14011395
# TODO: look into _wrap_result
14021396
if len(self) != len(other):
14031397
raise AssertionError(
1404-
(
1405-
"length mismatch: {self} vs. {other}".format(
1406-
self=len(self), other=len(other)
1407-
)
1408-
)
1398+
(f"length mismatch: {len(self)} vs. {len(other)}")
14091399
)
14101400
if not isinstance(other, SparseArray):
14111401
dtype = getattr(other, "dtype", None)
@@ -1414,7 +1404,7 @@ def sparse_arithmetic_method(self, other):
14141404
)
14151405
return _sparse_array_op(self, other, op, op_name)
14161406

1417-
name = "__{name}__".format(name=op.__name__)
1407+
name = f"__{op.__name__}__"
14181408
return compat.set_function_name(sparse_arithmetic_method, name, cls)
14191409

14201410
@classmethod
@@ -1434,9 +1424,7 @@ def cmp_method(self, other):
14341424
# TODO: make this more flexible than just ndarray...
14351425
if len(self) != len(other):
14361426
raise AssertionError(
1437-
"length mismatch: {self} vs. {other}".format(
1438-
self=len(self), other=len(other)
1439-
)
1427+
f"length mismatch: {len(self)} vs. {len(other)}"
14401428
)
14411429
other = SparseArray(other, fill_value=self.fill_value)
14421430

@@ -1454,7 +1442,7 @@ def cmp_method(self, other):
14541442
dtype=np.bool_,
14551443
)
14561444

1457-
name = "__{name}__".format(name=op.__name__)
1445+
name = f"__{op.__name__}__"
14581446
return compat.set_function_name(cmp_method, name, cls)
14591447

14601448
@classmethod
@@ -1473,11 +1461,10 @@ def _add_comparison_ops(cls):
14731461
# Formatting
14741462
# -----------
14751463
def __repr__(self) -> str:
1476-
return "{self}\nFill: {fill}\n{index}".format(
1477-
self=printing.pprint_thing(self),
1478-
fill=printing.pprint_thing(self.fill_value),
1479-
index=printing.pprint_thing(self.sp_index),
1480-
)
1464+
pp_str = printing.pprint_thing(self)
1465+
pp_fill = printing.pprint_thing(self.fill_value)
1466+
pp_index = printing.pprint_thing(self.sp_index)
1467+
return f"{pp_str}\nFill: {pp_fill}\n{pp_index}"
14811468

14821469
def _formatter(self, boxed=False):
14831470
# Defer to the formatter from the GenericArrayFormatter calling us.

pandas/core/arrays/sparse/dtype.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,7 @@ def __init__(self, dtype: Dtype = np.float64, fill_value: Any = None) -> None:
7979
fill_value = na_value_for_dtype(dtype)
8080

8181
if not is_scalar(fill_value):
82-
raise ValueError(
83-
"fill_value must be a scalar. Got {} instead".format(fill_value)
84-
)
82+
raise ValueError(f"fill_value must be a scalar. Got {fill_value} instead")
8583
self._dtype = dtype
8684
self._fill_value = fill_value
8785

@@ -163,7 +161,7 @@ def subtype(self):
163161

164162
@property
165163
def name(self):
166-
return "Sparse[{}, {}]".format(self.subtype.name, self.fill_value)
164+
return f"Sparse[{self.subtype.name}, {self.fill_value}]"
167165

168166
def __repr__(self) -> str:
169167
return self.name
@@ -201,7 +199,7 @@ def construct_from_string(cls, string):
201199
-------
202200
SparseDtype
203201
"""
204-
msg = "Could not construct SparseDtype from '{}'".format(string)
202+
msg = f"Could not construct SparseDtype from '{string}'"
205203
if string.startswith("Sparse"):
206204
try:
207205
sub_type, has_fill_value = cls._parse_subtype(string)
@@ -210,14 +208,14 @@ def construct_from_string(cls, string):
210208
else:
211209
result = SparseDtype(sub_type)
212210
msg = (
213-
"Could not construct SparseDtype from '{}'.\n\nIt "
211+
f"Could not construct SparseDtype from '{string}'.\n\nIt "
214212
"looks like the fill_value in the string is not "
215213
"the default for the dtype. Non-default fill_values "
216214
"are not supported. Use the 'SparseDtype()' "
217215
"constructor instead."
218216
)
219217
if has_fill_value and str(result) != string:
220-
raise TypeError(msg.format(string))
218+
raise TypeError(msg)
221219
return result
222220
else:
223221
raise TypeError(msg)
@@ -253,7 +251,7 @@ def _parse_subtype(dtype: str) -> Tuple[str, bool]:
253251
elif dtype == "Sparse":
254252
subtype = "float64"
255253
else:
256-
raise ValueError("Cannot parse {}".format(dtype))
254+
raise ValueError(f"Cannot parse {dtype}")
257255
return subtype, has_fill_value
258256

259257
@classmethod

pandas/core/arrays/sparse/scipy_sparse.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def _coo_to_sparse_series(A, dense_index: bool = False):
137137
try:
138138
s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
139139
except AttributeError:
140-
raise TypeError("Expected coo_matrix. Got {} instead.".format(type(A).__name__))
140+
raise TypeError(f"Expected coo_matrix. Got {type(A).__name__} instead.")
141141
s = s.sort_index()
142142
s = s.astype(SparseDtype(s.dtype))
143143
if dense_index:

0 commit comments

Comments
 (0)