MCPcopy
hub / github.com/pandas-dev/pandas / diff

Function diff

pandas/core/algorithms.py:1320–1428  ·  view source on GitHub ↗

difference of n between self, analogous to s-s.shift(n) Parameters ---------- arr : ndarray or ExtensionArray n : int number of periods axis : {0, 1} axis to shift on stacklevel : int, default 3 The stacklevel for the lost dtype warning.

(arr, n: int | float | np.integer | np.floating, axis: AxisInt = 0)

Source from the content-addressed store, hash-verified

1318
1319
1320def diff(arr, n: int | float | np.integer | np.floating, axis: AxisInt = 0):
1321 """
1322 difference of n between self,
1323 analogous to s-s.shift(n)
1324
1325 Parameters
1326 ----------
1327 arr : ndarray or ExtensionArray
1328 n : int
1329 number of periods
1330 axis : {0, 1}
1331 axis to shift on
1332 stacklevel : int, default 3
1333 The stacklevel for the lost dtype warning.
1334
1335 Returns
1336 -------
1337 shifted
1338 """
1339
1340 # added a check on the integer value of period
1341 # see https://github.com/pandas-dev/pandas/issues/56607
1342 if not lib.is_integer(n):
1343 if not (is_float(n) and n.is_integer()):
1344 raise ValueError("periods must be an integer")
1345 n = int(n)
1346 na = np.nan
1347 dtype = arr.dtype
1348
1349 is_bool = is_bool_dtype(dtype)
1350 if is_bool:
1351 op = operator.xor
1352 else:
1353 op = operator.sub
1354
1355 if isinstance(dtype, NumpyEADtype):
1356 # NumpyExtensionArray cannot necessarily hold shifted versions of itself.
1357 arr = arr.to_numpy()
1358 dtype = arr.dtype
1359
1360 if not isinstance(arr, np.ndarray):
1361 # i.e ExtensionArray
1362 if hasattr(arr, f"__{op.__name__}__"):
1363 if axis != 0:
1364 raise ValueError(f"cannot diff {type(arr).__name__} on axis={axis}")
1365 return op(arr, arr.shift(n))
1366 else:
1367 raise TypeError(
1368 f"{type(arr).__name__} has no 'diff' method. "
1369 "Convert to a suitable dtype prior to calling 'diff'."
1370 )
1371
1372 is_timedelta = False
1373 if arr.dtype.kind in "mM":
1374 dtype = np.int64
1375 arr = arr.view("i8")
1376 na = iNaT
1377 is_timedelta = True

Callers

nothing calls this directly

Calls 8

is_bool_dtypeFunction · 0.90
opFunction · 0.85
to_numpyMethod · 0.45
shiftMethod · 0.45
viewMethod · 0.45
reshapeMethod · 0.45
dtypeMethod · 0.45
emptyMethod · 0.45

Tested by

no test coverage detected