language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | coleifer__peewee | tests/models.py | {
"start": 177344,
"end": 177487
} | class ____(TestModel):
part = CharField(primary_key=True)
sub_part = ForeignKeyField('self', null=True)
@skip_unless(IS_POSTGRESQL)
| C_Part |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/table_metrics/table_column_count.py | {
"start": 725,
"end": 2884
} | class ____(TableMetricProvider):
metric_name = "table.column_count"
@metric_value(engine=PandasExecutionEngine)
def _pandas(
cls,
execution_engine: ExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: dict,
metrics: Dict[str, Any],
runtime_configuration: dict,
):
columns = metrics.get("table.columns")
return len(columns) # type: ignore[arg-type] # FIXME CoP
@metric_value(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(
cls,
execution_engine: ExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: dict,
metrics: Dict[str, Any],
runtime_configuration: dict,
):
columns = metrics.get("table.columns")
return len(columns) # type: ignore[arg-type] # FIXME CoP
@metric_value(engine=SparkDFExecutionEngine)
def _spark(
cls,
execution_engine: ExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: dict,
metrics: Dict[str, Any],
runtime_configuration: dict,
):
columns = metrics.get("table.columns")
return len(columns) # type: ignore[arg-type] # FIXME CoP
@classmethod
@override
def _get_evaluation_dependencies(
cls,
metric: MetricConfiguration,
configuration: Optional[ExpectationConfiguration] = None,
execution_engine: Optional[ExecutionEngine] = None,
runtime_configuration: Optional[dict] = None,
):
dependencies: dict = super()._get_evaluation_dependencies(
metric=metric,
configuration=configuration,
execution_engine=execution_engine,
runtime_configuration=runtime_configuration,
)
table_domain_kwargs: dict = {
k: v for k, v in metric.metric_domain_kwargs.items() if k != "column"
}
dependencies["table.columns"] = MetricConfiguration(
metric_name="table.columns",
metric_domain_kwargs=table_domain_kwargs,
metric_value_kwargs=None,
)
return dependencies
| TableColumnCount |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 63992,
"end": 64357
} | class ____(BaseModel, extra="forbid"):
type: "KeywordIndexType" = Field(..., description="")
is_tenant: Optional[bool] = Field(
default=None, description="If true - used for tenant optimization. Default: false."
)
on_disk: Optional[bool] = Field(default=None, description="If true, store the index on disk. Default: false.")
| KeywordIndexParams |
python | doocs__leetcode | solution/3200-3299/3297.Count Substrings That Can Be Rearranged to Contain a String I/Solution.py | {
"start": 0,
"end": 551
} | class ____:
def validSubstringCount(self, word1: str, word2: str) -> int:
if len(word1) < len(word2):
return 0
cnt = Counter(word2)
need = len(cnt)
ans = l = 0
win = Counter()
for c in word1:
win[c] += 1
if win[c] == cnt[c]:
need -= 1
while need == 0:
if win[word1[l]] == cnt[word1[l]]:
need += 1
win[word1[l]] -= 1
l += 1
ans += l
return ans
| Solution |
python | google__jax | tests/linalg_test.py | {
"start": 56229,
"end": 84686
} | class ____(jtu.JaxTestCase):
@jtu.sample_product(
args=[
(),
(1,),
(7, -2),
(3, 4, 5),
(np.ones((3, 4), dtype=float), 5,
np.random.randn(5, 2).astype(float)),
]
)
def testBlockDiag(self, args):
args_maker = lambda: args
self._CheckAgainstNumpy(osp.linalg.block_diag, jsp.linalg.block_diag,
args_maker, check_dtypes=False)
self._CompileAndCheck(jsp.linalg.block_diag, args_maker)
@jtu.sample_product(
shape=[(1, 1), (4, 5), (10, 5), (50, 50)],
dtype=float_types + complex_types,
)
def testLu(self, shape, dtype):
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(shape, dtype)]
x, = args_maker()
p, l, u = jsp.linalg.lu(x)
self.assertAllClose(x, np.matmul(p, np.matmul(l, u)),
rtol={np.float32: 1e-3, np.float64: 5e-12,
np.complex64: 1e-3, np.complex128: 1e-12},
atol={np.float32: 1e-5})
self._CompileAndCheck(jsp.linalg.lu, args_maker)
def testLuOfSingularMatrix(self):
x = jnp.array([[-1., 3./2], [2./3, -1.]], dtype=np.float32)
p, l, u = jsp.linalg.lu(x)
self.assertAllClose(x, np.matmul(p, np.matmul(l, u)))
@parameterized.parameters(lax_linalg.lu, lax_linalg._lu_python)
def testLuOnZeroMatrix(self, lu):
# Regression test for https://github.com/jax-ml/jax/issues/19076
x = jnp.zeros((2, 2), dtype=np.float32)
x_lu, _, _ = lu(x)
self.assertArraysEqual(x_lu, x)
@jtu.sample_product(
shape=[(1, 1), (4, 5), (10, 5), (10, 10), (6, 7, 7)],
dtype=float_types + complex_types,
)
def testLuGrad(self, shape, dtype):
rng = jtu.rand_default(self.rng())
a = rng(shape, dtype)
lu = vmap(jsp.linalg.lu) if len(shape) > 2 else jsp.linalg.lu
jtu.check_grads(lu, (a,), 2, atol=5e-2, rtol=3e-1)
@jtu.sample_product(
shape=[(4, 5), (6, 5)],
dtype=[jnp.float32],
)
def testLuBatching(self, shape, dtype):
rng = jtu.rand_default(self.rng())
args = [rng(shape, jnp.float32) for _ in range(10)]
expected = [osp.linalg.lu(x) for x in args]
ps = np.stack([out[0] for out in expected])
ls = np.stack([out[1] for out in expected])
us = np.stack([out[2] for out in expected])
actual_ps, actual_ls, actual_us = vmap(jsp.linalg.lu)(jnp.stack(args))
self.assertAllClose(ps, actual_ps)
self.assertAllClose(ls, actual_ls, rtol=5e-6)
self.assertAllClose(us, actual_us)
@jtu.skip_on_devices("cpu", "tpu")
@jtu.ignore_warning(category=DeprecationWarning,
message="backend and device argument")
def testLuCPUBackendOnGPU(self):
# tests running `lu` on cpu when a gpu is present.
jit(jsp.linalg.lu, backend="cpu")(np.ones((2, 2))) # does not crash
@jtu.sample_product(
n=[1, 4, 5, 200],
dtype=float_types + complex_types,
)
def testLuFactor(self, n, dtype):
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng((n, n), dtype)]
x, = args_maker()
lu, piv = jsp.linalg.lu_factor(x)
l = np.tril(lu, -1) + np.eye(n, dtype=dtype)
u = np.triu(lu)
for i in range(n):
x[[i, piv[i]],] = x[[piv[i], i],]
self.assertAllClose(x, np.matmul(l, u), rtol=1e-3,
atol=1e-3)
self._CompileAndCheck(jsp.linalg.lu_factor, args_maker)
@jtu.sample_product(
[dict(lhs_shape=lhs_shape, rhs_shape=rhs_shape)
for lhs_shape, rhs_shape in [
((1, 1), (1, 1)),
((4, 4), (4,)),
((8, 8), (8, 4)),
]
],
trans=[0, 1, 2],
dtype=float_types + complex_types,
)
@jtu.skip_on_devices("cpu") # TODO(frostig): Test fails on CPU sometimes
def testLuSolve(self, lhs_shape, rhs_shape, dtype, trans):
rng = jtu.rand_default(self.rng())
osp_fun = lambda lu, piv, rhs: osp.linalg.lu_solve((lu, piv), rhs, trans=trans)
jsp_fun = lambda lu, piv, rhs: jsp.linalg.lu_solve((lu, piv), rhs, trans=trans)
def args_maker():
a = rng(lhs_shape, dtype)
lu, piv = osp.linalg.lu_factor(a)
return [lu, piv, rng(rhs_shape, dtype)]
self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, tol=1e-3)
self._CompileAndCheck(jsp_fun, args_maker)
@jtu.sample_product(
[dict(lhs_shape=lhs_shape, rhs_shape=rhs_shape)
for lhs_shape, rhs_shape in [
((1, 1), (1, 1)),
((4, 4), (4,)),
((8, 8), (8, 4)),
]
],
[dict(assume_a=assume_a, lower=lower)
for assume_a, lower in [
('gen', False),
('pos', False),
('pos', True),
]
],
dtype=float_types + complex_types,
)
def testSolve(self, lhs_shape, rhs_shape, dtype, assume_a, lower):
rng = jtu.rand_default(self.rng())
osp_fun = lambda lhs, rhs: osp.linalg.solve(lhs, rhs, assume_a=assume_a, lower=lower)
jsp_fun = lambda lhs, rhs: jsp.linalg.solve(lhs, rhs, assume_a=assume_a, lower=lower)
def args_maker():
a = rng(lhs_shape, dtype)
if assume_a == 'pos':
a = np.matmul(a, np.conj(T(a)))
a = np.tril(a) if lower else np.triu(a)
return [a, rng(rhs_shape, dtype)]
self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, tol=1e-3)
self._CompileAndCheck(jsp_fun, args_maker)
@jtu.sample_product(
[dict(lhs_shape=lhs_shape, rhs_shape=rhs_shape)
for lhs_shape, rhs_shape in [
((4, 4), (4,)),
((4, 4), (4, 3)),
((2, 8, 8), (2, 8, 10)),
]
],
lower=[False, True],
transpose_a=[False, True],
unit_diagonal=[False, True],
dtype=float_types,
)
def testSolveTriangular(self, lower, transpose_a, unit_diagonal, lhs_shape,
rhs_shape, dtype):
rng = jtu.rand_default(self.rng())
k = rng(lhs_shape, dtype)
l = np.linalg.cholesky(np.matmul(k, T(k))
+ lhs_shape[-1] * np.eye(lhs_shape[-1]))
l = l.astype(k.dtype)
b = rng(rhs_shape, dtype)
if unit_diagonal:
a = np.tril(l, -1) + np.eye(lhs_shape[-1], dtype=dtype)
else:
a = l
a = a if lower else T(a)
inv = np.linalg.inv(T(a) if transpose_a else a).astype(a.dtype)
if len(lhs_shape) == len(rhs_shape):
np_ans = np.matmul(inv, b)
else:
np_ans = np.einsum("...ij,...j->...i", inv, b)
# The standard scipy.linalg.solve_triangular doesn't support broadcasting.
# But it seems like an inevitable extension so we support it.
ans = jsp.linalg.solve_triangular(
l if lower else T(l), b, trans=1 if transpose_a else 0, lower=lower,
unit_diagonal=unit_diagonal)
self.assertAllClose(np_ans, ans,
rtol={np.float32: 1e-4, np.float64: 1e-11})
@jtu.sample_product(
[dict(left_side=left_side, a_shape=a_shape, b_shape=b_shape)
for left_side, a_shape, b_shape in [
(False, (4, 4), (4,)),
(False, (4, 4), (1, 4,)),
(False, (3, 3), (4, 3)),
(True, (4, 4), (4,)),
(True, (4, 4), (4, 1)),
(True, (4, 4), (4, 3)),
(True, (2, 8, 8), (2, 8, 10)),
]
],
[dict(dtype=dtype, conjugate_a=conjugate_a)
for dtype in float_types + complex_types
for conjugate_a in (
[False] if jnp.issubdtype(dtype, jnp.floating) else [False, True])
],
lower=[False, True],
unit_diagonal=[False, True],
transpose_a=[False, True],
)
def testTriangularSolveGrad(
self, lower, transpose_a, conjugate_a, unit_diagonal, left_side, a_shape,
b_shape, dtype):
rng = jtu.rand_default(self.rng())
# Test lax.linalg.triangular_solve instead of scipy.linalg.solve_triangular
# because it exposes more options.
A = jnp.tril(rng(a_shape, dtype) + 5 * np.eye(a_shape[-1], dtype=dtype))
A = A if lower else T(A)
B = rng(b_shape, dtype)
f = partial(lax.linalg.triangular_solve, lower=lower, transpose_a=transpose_a,
conjugate_a=conjugate_a, unit_diagonal=unit_diagonal,
left_side=left_side)
jtu.check_grads(f, (A, B), order=1, rtol=4e-2, eps=1e-3)
@jtu.sample_product(
[dict(left_side=left_side, a_shape=a_shape, b_shape=b_shape, bdims=bdims)
for left_side, a_shape, b_shape, bdims in [
(False, (4, 4), (2, 3, 4,), (None, 0)),
(False, (2, 4, 4), (2, 2, 3, 4,), (None, 0)),
(False, (2, 4, 4), (3, 4,), (0, None)),
(False, (2, 4, 4), (2, 3, 4,), (0, 0)),
(True, (2, 4, 4), (2, 4, 3), (0, 0)),
(True, (2, 4, 4), (2, 2, 4, 3), (None, 0)),
]
],
)
def testTriangularSolveBatching(self, left_side, a_shape, b_shape, bdims):
rng = jtu.rand_default(self.rng())
A = jnp.tril(rng(a_shape, np.float32)
+ 5 * np.eye(a_shape[-1], dtype=np.float32))
B = rng(b_shape, np.float32)
solve = partial(lax.linalg.triangular_solve, lower=True, transpose_a=False,
conjugate_a=False, unit_diagonal=False, left_side=left_side)
X = vmap(solve, bdims)(A, B)
matmul = partial(jnp.matmul, precision=lax.Precision.HIGHEST)
Y = matmul(A, X) if left_side else matmul(X, A)
self.assertArraysAllClose(Y, jnp.broadcast_to(B, Y.shape), atol=1e-4)
def testTriangularSolveGradPrecision(self):
rng = jtu.rand_default(self.rng())
a = jnp.tril(rng((3, 3), np.float32))
b = rng((1, 3), np.float32)
jtu.assert_dot_precision(
lax.Precision.HIGHEST,
partial(jvp, lax.linalg.triangular_solve),
(a, b),
(a, b))
def testTriangularSolveSingularBatched(self):
x = jnp.array([[1, 1], [0, 0]], dtype=np.float32)
y = jnp.array([[1], [1.]], dtype=np.float32)
out = jax.lax.linalg.triangular_solve(x[None], y[None], left_side=True)
# x is singular. The triangular solve may contain either nans or infs, but
# it should not consist of only finite values.
self.assertFalse(np.all(np.isfinite(out)))
@jtu.sample_product(
n=[1, 4, 5, 20, 50, 100],
batch_size=[(), (2,), (3, 4)],
dtype=int_types + float_types + complex_types
)
def testExpm(self, n, batch_size, dtype):
if (jtu.test_device_matches(["cuda"]) and
_is_required_cuda_version_satisfied(12000)):
self.skipTest("Triggers a bug in cuda-12 b/287345077")
rng = jtu.rand_small(self.rng())
args_maker = lambda: [rng((*batch_size, n, n), dtype)]
# Compare to numpy with JAX type promotion semantics.
def osp_fun(A):
return osp.linalg.expm(np.array(*promote_dtypes_inexact(A)))
jsp_fun = jsp.linalg.expm
self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker)
self._CompileAndCheck(jsp_fun, args_maker)
args_maker_triu = lambda: [np.triu(rng((*batch_size, n, n), dtype))]
jsp_fun_triu = lambda a: jsp.linalg.expm(a, upper_triangular=True)
self._CheckAgainstNumpy(osp_fun, jsp_fun_triu, args_maker_triu)
self._CompileAndCheck(jsp_fun_triu, args_maker_triu)
@jtu.sample_product(
# Skip empty shapes because scipy fails: https://github.com/scipy/scipy/issues/1532
shape=[(3, 4), (3, 3), (4, 3)],
dtype=float_types + complex_types,
mode=["full", "r", "economic"],
pivoting=[False, True]
)
@jax.default_matmul_precision("float32")
def testScipyQrModes(self, shape, dtype, mode, pivoting):
if pivoting:
if not jtu.test_device_matches(["cpu", "gpu"]):
self.skipTest("Pivoting is only supported on CPU and GPU.")
rng = jtu.rand_default(self.rng())
jsp_func = partial(jax.scipy.linalg.qr, mode=mode, pivoting=pivoting)
sp_func = partial(scipy.linalg.qr, mode=mode, pivoting=pivoting)
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(sp_func, jsp_func, args_maker, rtol=1E-5, atol=1E-5)
self._CompileAndCheck(jsp_func, args_maker)
# Pivoting is unsupported by the numpy api - repeat the jvp checks performed
# in NumpyLinalgTest::testQR for the `pivoting=True` modes here. Like in the
# numpy test, `qr_and_mul` expresses the identity function.
def qr_and_mul(a):
q, r, *p = jsp_func(a)
# To express the identity function we must "undo" the pivoting of `q @ r`.
inverted_pivots = jnp.argsort(p[0])
return (q @ r)[:, inverted_pivots]
m, n = shape
if pivoting and mode != "r" and (m == n or (m > n and mode != "full")):
for a in args_maker():
jtu.check_jvp(qr_and_mul, partial(jvp, qr_and_mul), (a,), atol=3e-3)
@jtu.sample_product(
[dict(shape=shape, k=k)
for shape in [(1, 1), (3, 4, 4), (10, 5)]
# TODO(phawkins): there are some test failures on GPU for k=0
for k in range(1, shape[-1] + 1)],
dtype=float_types + complex_types,
)
def testHouseholderProduct(self, shape, k, dtype):
@partial(np.vectorize, signature='(m,n),(k)->(m,n)')
def reference_fn(a, taus):
if dtype == np.float32:
q, _, info = scipy.linalg.lapack.sorgqr(a, taus)
elif dtype == np.float64:
q, _, info = scipy.linalg.lapack.dorgqr(a, taus)
elif dtype == np.complex64:
q, _, info = scipy.linalg.lapack.cungqr(a, taus)
elif dtype == np.complex128:
q, _, info = scipy.linalg.lapack.zungqr(a, taus)
else:
assert False, dtype
assert info == 0, info
return q
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(shape, dtype), rng(shape[:-2] + (k,), dtype)]
tol = {np.float32: 1e-5, np.complex64: 1e-5, np.float64: 1e-12,
np.complex128: 1e-12}
self._CheckAgainstNumpy(reference_fn, lax.linalg.householder_product,
args_maker, rtol=tol, atol=tol)
self._CompileAndCheck(lax.linalg.householder_product, args_maker)
@jtu.sample_product(
shape=[(1, 1), (2, 4, 4), (0, 100, 100), (10, 10)],
dtype=float_types + complex_types,
calc_q=[False, True],
)
@jtu.run_on_devices("cpu")
def testHessenberg(self, shape, dtype, calc_q):
rng = jtu.rand_default(self.rng())
jsp_func = partial(jax.scipy.linalg.hessenberg, calc_q=calc_q)
if calc_q:
sp_func = np.vectorize(partial(scipy.linalg.hessenberg, calc_q=True),
otypes=(dtype, dtype),
signature='(n,n)->(n,n),(n,n)')
else:
sp_func = np.vectorize(scipy.linalg.hessenberg, signature='(n,n)->(n,n)',
otypes=(dtype,))
args_maker = lambda: [rng(shape, dtype)]
# scipy.linalg.hessenberg sometimes returns a float Q matrix for complex
# inputs
self._CheckAgainstNumpy(sp_func, jsp_func, args_maker, rtol=1e-5, atol=1e-5,
check_dtypes=not calc_q)
self._CompileAndCheck(jsp_func, args_maker)
if len(shape) == 3:
args = args_maker()
self.assertAllClose(jax.vmap(jsp_func)(*args), jsp_func(*args))
@jtu.sample_product(
shape=[(1, 1), (2, 2, 2), (4, 4), (10, 10), (2, 5, 5)],
dtype=float_types + complex_types,
lower=[False, True],
)
@jtu.skip_on_devices("tpu","rocm")
def testTridiagonal(self, shape, dtype, lower):
rng = jtu.rand_default(self.rng())
def jax_func(a):
return lax.linalg.tridiagonal(a, lower=lower)
real_dtype = jnp.finfo(dtype).dtype
@partial(np.vectorize, otypes=(dtype, real_dtype, real_dtype, dtype),
signature='(n,n)->(n,n),(n),(k),(k)')
def sp_func(a):
if dtype == np.float32:
c, d, e, tau, info = scipy.linalg.lapack.ssytrd(a, lower=lower)
elif dtype == np.float64:
c, d, e, tau, info = scipy.linalg.lapack.dsytrd(a, lower=lower)
elif dtype == np.complex64:
c, d, e, tau, info = scipy.linalg.lapack.chetrd(a, lower=lower)
elif dtype == np.complex128:
c, d, e, tau, info = scipy.linalg.lapack.zhetrd(a, lower=lower)
else:
assert False, dtype
assert info == 0
return c, d, e, tau
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(sp_func, jax_func, args_maker, rtol=1e-4, atol=1e-4,
check_dtypes=False)
if len(shape) == 3:
args = args_maker()
self.assertAllClose(jax.vmap(jax_func)(*args), jax_func(*args))
@jtu.sample_product(
n=[1, 4, 5, 20, 50, 100],
dtype=float_types + complex_types,
)
def testIssue2131(self, n, dtype):
args_maker_zeros = lambda: [np.zeros((n, n), dtype)]
osp_fun = lambda a: osp.linalg.expm(a)
jsp_fun = lambda a: jsp.linalg.expm(a)
self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker_zeros)
self._CompileAndCheck(jsp_fun, args_maker_zeros)
@jtu.sample_product(
[dict(lhs_shape=lhs_shape, rhs_shape=rhs_shape)
for lhs_shape, rhs_shape in [
[(1, 1), (1,)],
[(4, 4), (4,)],
[(4, 4), (4, 4)],
]
],
dtype=float_types,
lower=[True, False],
)
def testChoSolve(self, lhs_shape, rhs_shape, dtype, lower):
rng = jtu.rand_default(self.rng())
def args_maker():
b = rng(rhs_shape, dtype)
if lower:
L = np.tril(rng(lhs_shape, dtype))
return [(L, lower), b]
else:
U = np.triu(rng(lhs_shape, dtype))
return [(U, lower), b]
self._CheckAgainstNumpy(osp.linalg.cho_solve, jsp.linalg.cho_solve,
args_maker, tol=1e-3)
@jtu.sample_product(
n=[1, 4, 5, 20, 50, 100],
dtype=float_types + complex_types,
)
def testExpmFrechet(self, n, dtype):
rng = jtu.rand_small(self.rng())
if dtype == np.float64 or dtype == np.complex128:
target_norms = [1.0e-2, 2.0e-1, 9.0e-01, 2.0, 3.0]
# TODO(zhangqiaorjc): Reduce tol to default 1e-15.
tol = {
np.dtype(np.float64): 1e-14,
np.dtype(np.complex128): 1e-14,
}
elif dtype == np.float32 or dtype == np.complex64:
target_norms = [4.0e-1, 1.0, 3.0]
tol = None
else:
raise TypeError(f"{dtype=} is not supported.")
for norm in target_norms:
def args_maker():
a = rng((n, n), dtype)
a = a / np.linalg.norm(a, 1) * norm
e = rng((n, n), dtype)
return [a, e, ]
# compute_expm is True
osp_fun = lambda a,e: osp.linalg.expm_frechet(a,e,compute_expm=True)
jsp_fun = lambda a,e: jsp.linalg.expm_frechet(a,e,compute_expm=True)
self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker,
check_dtypes=False, tol=tol)
self._CompileAndCheck(jsp_fun, args_maker, check_dtypes=False)
# compute_expm is False
osp_fun = lambda a,e: osp.linalg.expm_frechet(a,e,compute_expm=False)
jsp_fun = lambda a,e: jsp.linalg.expm_frechet(a,e,compute_expm=False)
self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker,
check_dtypes=False, tol=tol)
self._CompileAndCheck(jsp_fun, args_maker, check_dtypes=False)
@jtu.sample_product(
n=[1, 4, 5, 20, 50],
dtype=float_types + complex_types,
)
def testExpmGrad(self, n, dtype):
rng = jtu.rand_small(self.rng())
a = rng((n, n), dtype)
if dtype == np.float64 or dtype == np.complex128:
target_norms = [1.0e-2, 2.0e-1, 9.0e-01, 2.0, 3.0]
elif dtype == np.float32 or dtype == np.complex64:
target_norms = [4.0e-1, 1.0, 3.0]
else:
raise TypeError(f"{dtype=} is not supported.")
# TODO(zhangqiaorjc): Reduce tol to default 1e-5.
# Lower tolerance is due to 2nd order derivative.
tol = {
# Note that due to inner_product, float and complex tol are coupled.
np.dtype(np.float32): 0.02,
np.dtype(np.complex64): 0.02,
np.dtype(np.float64): 1e-4,
np.dtype(np.complex128): 1e-4,
}
for norm in target_norms:
a = a / np.linalg.norm(a, 1) * norm
def expm(x):
return jsp.linalg.expm(x, upper_triangular=False, max_squarings=16)
jtu.check_grads(expm, (a,), modes=["fwd", "rev"], order=1, atol=tol,
rtol=tol)
@jtu.sample_product(
shape=[(4, 4), (15, 15), (50, 50), (100, 100)],
dtype=float_types + complex_types,
)
@jtu.run_on_devices("cpu")
def testSchur(self, shape, dtype):
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(osp.linalg.schur, jsp.linalg.schur, args_maker)
self._CompileAndCheck(jsp.linalg.schur, args_maker)
@jtu.sample_product(
shape=[(1, 1), (4, 4), (15, 15), (50, 50), (100, 100)],
dtype=float_types + complex_types,
)
@jtu.run_on_devices("cpu")
def testRsf2csf(self, shape, dtype):
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(shape, dtype), rng(shape, dtype)]
tol = 3e-5
self._CheckAgainstNumpy(
osp.linalg.rsf2csf, jsp.linalg.rsf2csf, args_maker, tol=tol
)
self._CompileAndCheck(jsp.linalg.rsf2csf, args_maker)
@jtu.sample_product(
shape=[(1, 1), (5, 5), (20, 20), (50, 50)],
dtype=float_types + complex_types,
disp=[True, False],
)
# funm uses jax.scipy.linalg.schur which is implemented for a CPU
# backend only, so tests on GPU and TPU backends are skipped here
@jtu.run_on_devices("cpu")
def testFunm(self, shape, dtype, disp):
def func(x):
return x**-2.718
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(shape, dtype)]
jnp_fun = lambda arr: jsp.linalg.funm(arr, func, disp=disp)
scp_fun = lambda arr: osp.linalg.funm(arr, func, disp=disp)
self._CheckAgainstNumpy(
jnp_fun,
scp_fun,
args_maker,
check_dtypes=False,
tol={np.complex64: 1e-5, np.complex128: 1e-6},
)
self._CompileAndCheck(jnp_fun, args_maker, atol=2e-5)
@jtu.sample_product(
shape=[(4, 4), (15, 15), (50, 50), (100, 100)],
dtype=float_types + complex_types,
)
@jtu.run_on_devices("cpu")
@jtu.ignore_warning(
category=RuntimeWarning, message='invalid value encountered in matmul'
)
def testSqrtmPSDMatrix(self, shape, dtype):
# Checks against scipy.linalg.sqrtm when the principal square root
# is guaranteed to be unique (i.e no negative real eigenvalue)
rng = jtu.rand_default(self.rng())
arg = rng(shape, dtype)
mat = arg @ arg.T
args_maker = lambda : [mat]
if dtype == np.float32 or dtype == np.complex64:
tol = 1e-4
else:
tol = 1e-8
self._CheckAgainstNumpy(osp.linalg.sqrtm, jsp.linalg.sqrtm, args_maker,
tol=tol, check_dtypes=False)
self._CompileAndCheck(jsp.linalg.sqrtm, args_maker)
@jtu.sample_product(
shape=[(4, 4), (15, 15), (50, 50), (100, 100)],
dtype=float_types + complex_types,
)
@jtu.run_on_devices("cpu")
def testSqrtmGenMatrix(self, shape, dtype):
rng = jtu.rand_default(self.rng())
arg = rng(shape, dtype)
if dtype == np.float32 or dtype == np.complex64:
tol = 2e-3
else:
tol = 1e-8
R = jsp.linalg.sqrtm(arg)
self.assertAllClose(R @ R, arg, atol=tol, check_dtypes=False)
@jtu.sample_product(
[dict(diag=diag, expected=expected)
for diag, expected in [([1, 0, 0], [1, 0, 0]), ([0, 4, 0], [0, 2, 0]),
([0, 0, 0, 9],[0, 0, 0, 3]),
([0, 0, 9, 0, 0, 4], [0, 0, 3, 0, 0, 2])]
],
dtype=float_types + complex_types,
)
@jtu.run_on_devices("cpu")
def testSqrtmEdgeCase(self, diag, expected, dtype):
"""
Tests the zero numerator condition
"""
mat = jnp.diag(jnp.array(diag)).astype(dtype)
expected = jnp.diag(jnp.array(expected))
root = jsp.linalg.sqrtm(mat)
self.assertAllClose(root, expected, check_dtypes=False)
@jtu.sample_product(
cshape=[(), (4,), (8,), (4, 7), (2, 1, 5)],
cdtype=float_types + complex_types,
rshape=[(), (3,), (7,), (4, 4), (2, 4, 0)],
rdtype=float_types + complex_types + int_types)
def testToeplitzConstruction(self, rshape, rdtype, cshape, cdtype):
if ((rdtype in [np.float64, np.complex128]
or cdtype in [np.float64, np.complex128])
and not config.enable_x64.value):
self.skipTest("Only run float64 testcase when float64 is enabled.")
int_types_excl_i8 = set(int_types) - {np.int8}
if ((rdtype in int_types_excl_i8 or cdtype in int_types_excl_i8)
and jtu.test_device_matches(["gpu"])):
self.skipTest("Integer (except int8) toeplitz is not supported on GPU yet.")
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(cshape, cdtype), rng(rshape, rdtype)]
with jax.numpy_rank_promotion("allow"):
with jtu.strict_promotion_if_dtypes_match([rdtype, cdtype]):
self._CheckAgainstNumpy(jtu.promote_like_jnp(osp_linalg_toeplitz),
jsp.linalg.toeplitz, args_maker)
self._CompileAndCheck(jsp.linalg.toeplitz, args_maker)
@jtu.sample_product(
shape=[(), (3,), (1, 4), (1, 5, 9), (11, 0, 13)],
dtype=float_types + complex_types + int_types)
@jtu.skip_on_devices("rocm")
def testToeplitzSymmetricConstruction(self, shape, dtype):
if (dtype in [np.float64, np.complex128]
and not config.enable_x64.value):
self.skipTest("Only run float64 testcase when float64 is enabled.")
int_types_excl_i8 = set(int_types) - {np.int8}
if (dtype in int_types_excl_i8
and jtu.test_device_matches(["gpu"])):
self.skipTest("Integer (except int8) toeplitz is not supported on GPU yet.")
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(shape, dtype)]
self._CheckAgainstNumpy(osp_linalg_toeplitz, jsp.linalg.toeplitz, args_maker)
self._CompileAndCheck(jsp.linalg.toeplitz, args_maker)
def testToeplitzConstructionWithKnownCases(self):
# Test with examples taken from SciPy doc for the corresponding function.
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.toeplitz.html
ret = jsp.linalg.toeplitz(np.array([1.0, 2+3j, 4-1j]))
self.assertAllClose(ret, np.array([
[ 1.+0.j, 2.-3.j, 4.+1.j],
[ 2.+3.j, 1.+0.j, 2.-3.j],
[ 4.-1.j, 2.+3.j, 1.+0.j]]))
ret = jsp.linalg.toeplitz(np.array([1, 2, 3], dtype=np.float32),
np.array([1, 4, 5, 6], dtype=np.float32))
self.assertAllClose(ret, np.array([
[1, 4, 5, 6],
[2, 1, 4, 5],
[3, 2, 1, 4]], dtype=np.float32))
@jtu.sample_product(
shape=[(2, 3), (4, 6), (50, 7), (100, 110)],
dtype = float_types + complex_types,
method = ["schur", "eigen"]
)
@jtu.run_on_devices("cpu", "gpu")
@jax.default_matmul_precision("float32")
def test_solve_sylvester(self, shape, dtype, method):
if jtu.test_device_matches(["gpu"]) and method == "schur":
self.skipTest("Schur not supported on GPU.")
tol = {np.float32: 5e-2, np.float64: 1e-9, np.complex64: 5e-2, np.complex128: 1e-9}
def args_maker():
rng = jtu.rand_default(self.rng())
m, n = shape
A = rng(shape=(m, m), dtype=dtype)
B = rng(shape=(n, n), dtype=dtype)
X_true = rng(shape=(m, n), dtype=dtype)
C = A @ X_true + X_true @ B
return [A, B, C]
jnp_fun = partial(jsp.linalg.solve_sylvester, method=method)
self._CheckAgainstNumpy(osp.linalg.solve_sylvester, jnp_fun, args_maker, tol=tol)
self._CompileAndCheck(jnp_fun, args_maker)
@jtu.sample_product(
n=[3, 6, 7, 100],
dtype = float_types + complex_types,
method = ["schur", "eigen"]
)
@jtu.run_on_devices("cpu", "gpu")
def test_ill_conditioned_sylvester(self, n, dtype, method):
"""
Test no solution case to AX + XB = C using the eigen decomposition method.
When the sum of the eigenvalues of A and B are zero there is no solution.
We simulate this case below by randomly selecting the eigenvalues of A and then assign the
eigenvalues of B as negative eigenvalues of A. We say that A and B are ill-conditioned.
"""
if jtu.test_device_matches(["gpu"]) and method == "schur":
self.skipTest("Schur not supported on GPU.")
rng = jtu.rand_default(self.rng())
# Define eigenvalues that sum to zero
eigenvalues_A = rng(shape=(n,), dtype=dtype)
eigenvalues_B = -eigenvalues_A
P = _random_invertible(rng=rng, shape=(n, n), dtype=dtype)
# Construct A and B matrices using selected eigenvalues that positionally sum to zero
D_A = np.diag(eigenvalues_A)
D_B = np.diag(eigenvalues_B)
P_inv = np.linalg.inv(P)
A = P @ D_A @ P_inv
B = P @ D_B @ P_inv
C = rng(shape=(n, n), dtype=dtype)
sylv_solution = jsp.linalg.solve_sylvester(A, B, C, method=method, tol=1e-5)
self.assertArraysEqual(sylv_solution, np.full((n, n), np.nan, dtype))
| ScipyLinalgTest |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/resnet.py | {
"start": 1571,
"end": 2341
} | class ____(nn.Module):
"""Bottleneck ResNet block."""
filters: int
conv: ModuleDef
norm: ModuleDef
act: Callable
strides: tuple[int, int] = (1, 1)
@nn.compact
def __call__(self, x):
residual = x
y = self.conv(self.filters, (1, 1))(x)
y = self.norm()(y)
y = self.act(y)
y = self.conv(self.filters, (3, 3), self.strides)(y)
y = self.norm()(y)
y = self.act(y)
y = self.conv(self.filters * 4, (1, 1))(y)
y = self.norm(scale_init=nn.initializers.zeros)(y)
if residual.shape != y.shape:
residual = self.conv(self.filters * 4, (1, 1),
self.strides, name='conv_proj')(residual)
residual = self.norm(name='norm_proj')(residual)
return self.act(residual + y)
| BottleneckResNetBlock |
python | pypa__pip | src/pip/_internal/cli/spinners.py | {
"start": 4809,
"end": 7362
} | class ____:
"""
Custom rich spinner that matches the style of the legacy spinners.
(*) Updates will be handled in a background thread by a rich live panel
which will call render() automatically at the appropriate time.
"""
def __init__(self, label: str) -> None:
self.label = label
self._spin_cycle = itertools.cycle(SPINNER_CHARS)
self._spinner_text = ""
self._finished = False
self._indent = get_indentation() * " "
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
yield self.render()
def __rich_measure__(
self, console: Console, options: ConsoleOptions
) -> Measurement:
text = self.render()
return Measurement.get(console, options, text)
def render(self) -> RenderableType:
if not self._finished:
self._spinner_text = next(self._spin_cycle)
return Text.assemble(self._indent, self.label, " ... ", self._spinner_text)
def finish(self, status: str) -> None:
"""Stop spinning and set a final status message."""
self._spinner_text = status
self._finished = True
@contextlib.contextmanager
def open_rich_spinner(label: str, console: Console | None = None) -> Generator[None]:
if not logger.isEnabledFor(logging.INFO):
# Don't show spinner if --quiet is given.
yield
return
console = console or get_console()
spinner = _PipRichSpinner(label)
with Live(spinner, refresh_per_second=SPINS_PER_SECOND, console=console):
try:
yield
except KeyboardInterrupt:
spinner.finish("canceled")
raise
except Exception:
spinner.finish("error")
raise
else:
spinner.finish("done")
HIDE_CURSOR = "\x1b[?25l"
SHOW_CURSOR = "\x1b[?25h"
@contextlib.contextmanager
def hidden_cursor(file: IO[str]) -> Generator[None, None, None]:
# The Windows terminal does not support the hide/show cursor ANSI codes,
# even via colorama. So don't even try.
if WINDOWS:
yield
# We don't want to clutter the output with control characters if we're
# writing to a file, or if the user is running with --quiet.
# See https://github.com/pypa/pip/issues/3418
elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
yield
else:
file.write(HIDE_CURSOR)
try:
yield
finally:
file.write(SHOW_CURSOR)
| _PipRichSpinner |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 65664,
"end": 66064
} | class ____(sgqlc.types.Enum):
"""Properties by which project v2 view connections can be ordered.
Enumeration Choices:
* `CREATED_AT`: Order project v2 views by creation time
* `NAME`: Order project v2 views by name
* `POSITION`: Order project v2 views by position
"""
__schema__ = github_schema
__choices__ = ("CREATED_AT", "NAME", "POSITION")
| ProjectV2ViewOrderField |
python | kamyu104__LeetCode-Solutions | Python/3sum-with-multiplicity.py | {
"start": 104,
"end": 744
} | class ____(object):
def threeSumMulti(self, A, target):
"""
:type A: List[int]
:type target: int
:rtype: int
"""
count = collections.Counter(A)
result = 0
for i, j in itertools.combinations_with_replacement(count, 2):
k = target - i - j
if i == j == k:
result += count[i] * (count[i]-1) * (count[i]-2) // 6
elif i == j != k:
result += count[i] * (count[i]-1) // 2 * count[k]
elif max(i, j) < k:
result += count[i] * count[j] * count[k]
return result % (10**9 + 7)
| Solution |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/base.py | {
"start": 782,
"end": 1053
} | class ____(IntEnum):
FRAME = enum.auto()
GROUPBY = enum.auto()
ROLLING = enum.auto()
# Follows GROUPBY semantics but useful
# to differentiate from GROUPBY so we can
# implement agg/per-row ops independently
WINDOW = enum.auto()
| ExecutionContext |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_events_trends_v2.py | {
"start": 399,
"end": 16809
} | class ____(MetricsAPIBaseTestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organization=self.org)
self.url = reverse("sentry-api-0-organization-events-trends-statsv2", args=[self.org.slug])
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "foo"},
org_id=self.org.id,
project_id=self.project.id,
value=1,
hours_before_now=1,
)
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "foo"},
org_id=self.org.id,
project_id=self.project.id,
value=2,
hours_before_now=2,
)
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "foo"},
org_id=self.org.id,
project_id=self.project.id,
value=2,
hours_before_now=2,
)
self.features = {
"organizations:performance-view": True,
"organizations:performance-new-trends": True,
}
@property
def now(self):
return MetricsAPIBaseTestCase.MOCK_DATETIME
def test_no_feature_flag(self) -> None:
response = self.client.get(
self.url,
format="json",
data={
"end": self.now - timedelta(minutes=1),
"start": self.now - timedelta(hours=4),
"field": ["project", "transaction"],
"query": "event.type:transaction",
},
)
assert response.status_code == 404, response.content
def test_no_project(self) -> None:
with self.feature(self.features):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now - timedelta(minutes=1),
"start": self.now - timedelta(hours=4),
"interval": "1h",
"field": ["project", "transaction"],
"query": "",
},
)
assert response.status_code == 200, response.content
assert response.data == []
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.detect_breakpoints")
def test_simple_with_trends(self, mock_detect_breakpoints: mock.MagicMock) -> None:
mock_trends_result = [
{
"project": self.project.id,
"transaction": "foo",
"change": "regression",
"trend_difference": -15,
"trend_percentage": 0.88,
}
]
mock_detect_breakpoints.return_value = {"data": mock_trends_result}
with self.feature(self.features):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now,
"start": self.now - timedelta(days=1),
"interval": "1h",
"field": ["project", "transaction"],
"query": "event.type:transaction",
"project": self.project.id,
},
)
assert response.status_code == 200, response.content
events = response.data["events"]
result_stats = response.data["stats"]
assert len(events["data"]) == 1
assert events["data"] == mock_trends_result
assert len(result_stats) > 0
assert len(result_stats.get(f"{self.project.id},foo", [])) > 0
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.detect_breakpoints")
def test_simple_with_no_trends(self, mock_detect_breakpoints: mock.MagicMock) -> None:
mock_trends_result: list[dict[str, Any] | None] = []
mock_detect_breakpoints.return_value = {"data": mock_trends_result}
with self.feature(self.features):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now,
"start": self.now - timedelta(days=1),
"interval": "1h",
"field": ["project", "transaction"],
"query": "event.type:transaction",
"project": self.project.id,
},
)
assert response.status_code == 200, response.content
events = response.data["events"]
result_stats = response.data["stats"]
assert len(events["data"]) == 0
assert events["data"] == []
assert len(result_stats) == 0
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.detect_breakpoints")
def test_simple_with_transaction_query(self, mock_detect_breakpoints: mock.MagicMock) -> None:
mock_trends_result: list[dict[str, Any] | None] = []
mock_detect_breakpoints.return_value = {"data": mock_trends_result}
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "bar"},
org_id=self.org.id,
project_id=self.project.id,
value=2,
hours_before_now=2,
)
with self.feature(self.features):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now,
"start": self.now - timedelta(days=1),
"interval": "1h",
"field": ["project", "transaction"],
"query": "event.type:transaction transaction:foo",
"project": self.project.id,
},
)
trends_call_args_data = mock_detect_breakpoints.call_args[0][0]["data"]
assert len(trends_call_args_data.get(f"{self.project.id},foo")) > 0
assert len(trends_call_args_data.get(f"{self.project.id},bar", [])) == 0
assert response.status_code == 200, response.content
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.detect_breakpoints")
def test_simple_with_trends_p75(self, mock_detect_breakpoints: mock.MagicMock) -> None:
mock_trends_result = [
{
"project": self.project.id,
"transaction": "foo",
"change": "regression",
"trend_difference": -15,
"trend_percentage": 0.88,
}
]
mock_detect_breakpoints.return_value = {"data": mock_trends_result}
with self.feature(self.features):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now,
"start": self.now - timedelta(days=1),
"interval": "1h",
"field": ["project", "transaction"],
"query": "event.type:transaction",
"project": self.project.id,
"trendFunction": "p75(transaction.duration)",
},
)
assert response.status_code == 200, response.content
events = response.data["events"]
result_stats = response.data["stats"]
assert len(events["data"]) == 1
assert events["data"] == mock_trends_result
assert len(result_stats) > 0
assert len(result_stats.get(f"{self.project.id},foo", [])) > 0
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.detect_breakpoints")
def test_simple_with_trends_p95(self, mock_detect_breakpoints: mock.MagicMock) -> None:
mock_trends_result = [
{
"project": self.project.id,
"transaction": "foo",
"change": "regression",
"trend_difference": -15,
"trend_percentage": 0.88,
}
]
mock_detect_breakpoints.return_value = {"data": mock_trends_result}
with self.feature(self.features):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now,
"start": self.now - timedelta(days=1),
"interval": "1h",
"field": ["project", "transaction"],
"query": "event.type:transaction",
"project": self.project.id,
"trendFunction": "p95(transaction.duration)",
},
)
assert response.status_code == 200, response.content
events = response.data["events"]
result_stats = response.data["stats"]
assert len(events["data"]) == 1
assert events["data"] == mock_trends_result
assert len(result_stats) > 0
assert len(result_stats.get(f"{self.project.id},foo", [])) > 0
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.detect_breakpoints")
def test_simple_with_top_events(self, mock_detect_breakpoints: mock.MagicMock) -> None:
# store second metric but with lower count
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "bar"},
org_id=self.org.id,
project_id=self.project.id,
value=2,
hours_before_now=2,
)
with self.feature(self.features):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now,
"start": self.now - timedelta(days=1),
"interval": "1h",
"field": ["project", "transaction"],
"query": "event.type:transaction",
"project": self.project.id,
"trendFunction": "p95(transaction.duration)",
"topEvents": 1,
},
)
assert response.status_code == 200, response.content
trends_call_args_data = mock_detect_breakpoints.call_args[0][0]["data"]
assert len(trends_call_args_data.get(f"{self.project.id},foo")) > 0
# checks that second transaction wasn't sent to the trends microservice
assert len(trends_call_args_data.get(f"{self.project.id},bar", [])) == 0
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.detect_breakpoints")
def test_two_projects_same_transaction(self, mock_detect_breakpoints: mock.MagicMock) -> None:
project1 = self.create_project(organization=self.org)
project2 = self.create_project(organization=self.org)
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "bar"},
org_id=self.org.id,
project_id=project1.id,
value=2,
hours_before_now=2,
)
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "bar"},
org_id=self.org.id,
project_id=project2.id,
value=2,
hours_before_now=2,
)
with self.feature([*self.features]):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now,
"start": self.now - timedelta(days=1),
"interval": "1h",
"field": ["project", "transaction"],
"query": "event.type:transaction",
"project": [project1.id, project2.id],
"trendFunction": "p95(transaction.duration)",
"topEvents": 2,
},
)
assert response.status_code == 200, response.content
trends_call_args_data = mock_detect_breakpoints.call_args[0][0]["data"]
assert len(trends_call_args_data.get(f"{project1.id},bar")) > 0
assert len(trends_call_args_data.get(f"{project2.id},bar")) > 0
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.detect_breakpoints")
@mock.patch("sentry.api.endpoints.organization_events_trends_v2.EVENTS_PER_QUERY", 2)
def test_two_projects_same_transaction_split_queries(self, mock_detect_breakpoints) -> None:
project1 = self.create_project(organization=self.org)
project2 = self.create_project(organization=self.org)
# force these 2 transactions from different projects
# to fall into the FIRST bucket when querying
for i in range(2):
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "foo bar*"},
org_id=self.org.id,
project_id=project1.id,
value=2,
hours_before_now=2,
)
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": 'foo bar\\\\"'},
org_id=self.org.id,
project_id=project2.id,
value=2,
hours_before_now=2,
)
# force these 2 transactions from different projects
# to fall into the SECOND bucket when querying
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": "foo bar*"},
org_id=self.org.id,
project_id=project2.id,
value=2,
hours_before_now=2,
)
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
tags={"transaction": 'foo bar\\\\"'},
org_id=self.org.id,
project_id=project1.id,
value=2,
hours_before_now=2,
)
with self.feature([*self.features]):
response = self.client.get(
self.url,
format="json",
data={
"end": self.now,
"start": self.now - timedelta(days=1),
"interval": "1h",
"field": ["project", "transaction"],
"query": "event.type:transaction",
"project": [project1.id, project2.id],
"trendFunction": "p95(transaction.duration)",
"topEvents": 4,
"statsPeriod": "3h",
},
)
assert response.status_code == 200, response.content
trends_call_args_data_1 = mock_detect_breakpoints.call_args_list[0][0][0]["data"]
trends_call_args_data_2 = mock_detect_breakpoints.call_args_list[1][0][0]["data"]
# the order the calls happen in is non-deterministic because of the async
# nature making making the requests in a thread pool so check that 1 of
# the 2 possibilities happened
assert (
len(trends_call_args_data_1.get(f"{project1.id},foo bar*", {})) > 0
and len(trends_call_args_data_1.get(f'{project2.id},foo bar\\\\"', {})) > 0
and len(trends_call_args_data_2.get(f'{project1.id},foo bar\\\\"', {})) > 0
and len(trends_call_args_data_2.get(f"{project2.id},foo bar*", {})) > 0
) or (
len(trends_call_args_data_1.get(f'{project1.id},foo bar\\\\"', {})) > 0
and len(trends_call_args_data_1.get(f"{project2.id},foo bar*", {})) > 0
and len(trends_call_args_data_2.get(f"{project1.id},foo bar*", {})) > 0
and len(trends_call_args_data_2.get(f'{project2.id},foo bar\\\\"', {})) > 0
)
for trends_call_args_data in [trends_call_args_data_1, trends_call_args_data_2]:
for k, v in trends_call_args_data.items():
count = 0
for entry in v["data"]:
# each entry should have exactly 1 data point
assert len(entry[1]) == 1
count += entry[1][0]["count"]
assert count > 0, k # make sure the timeseries has some data
| OrganizationEventsTrendsStatsV2EndpointTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/transfers/test_http_to_s3.py | {
"start": 1132,
"end": 2927
} | class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": datetime.datetime(2017, 1, 1)}
self.dag = DAG("test_dag_id", schedule=None, default_args=args)
self.http_conn_id = "HTTP_EXAMPLE"
self.response = b"Example.com fake response"
self.endpoint = "/"
self.s3_key = "test/test1.csv"
self.s3_bucket = "dummy"
def test_init(self):
operator = HttpToS3Operator(
task_id="http_to_s3_operator",
http_conn_id=self.http_conn_id,
endpoint=self.endpoint,
s3_key=self.s3_key,
s3_bucket=self.s3_bucket,
dag=self.dag,
)
assert operator.endpoint == self.endpoint
assert operator.s3_key == self.s3_key
assert operator.s3_bucket == self.s3_bucket
assert operator.http_conn_id == self.http_conn_id
@mock_aws
def test_execute(self, requests_mock):
requests_mock.register_uri("GET", EXAMPLE_URL, content=self.response)
conn = boto3.client("s3")
conn.create_bucket(Bucket=self.s3_bucket)
operator = HttpToS3Operator(
task_id="s3_to_file_sensor",
http_conn_id=self.http_conn_id,
endpoint=self.endpoint,
s3_key=self.s3_key,
s3_bucket=self.s3_bucket,
dag=self.dag,
)
operator.execute(None)
objects_in_bucket = conn.list_objects(Bucket=self.s3_bucket, Prefix=self.s3_key)
# there should be object found, and there should only be one object found
assert len(objects_in_bucket["Contents"]) == 1
# the object found should be consistent with dest_key specified earlier
assert objects_in_bucket["Contents"][0]["Key"] == self.s3_key
| TestHttpToS3Operator |
python | pappasam__jedi-language-server | tests/test_data/highlighting/highlighting_test1.py | {
"start": 183,
"end": 829
} | class ____(Enum):
"""Test class for highlighting."""
def __init__(self):
self._field = 1
def some_method1(self):
"""Test method for highlighting."""
return SOME_CONSTANT + self._field
def some_method2(self):
"""Test method for highlighting."""
return some_function(SOME_CONSTANT)
instance = SomeClass()
instance.some_method1()
instance.some_method2()
# Jedi returns an implicit definition for these special variables,
# which has no line number. Highlighting of usages with line numbers
# should still function.
print(__file__)
print(__package__)
print(__doc__)
print(__name__)
| SomeClass |
python | ansible__ansible | test/units/playbook/test_taggable.py | {
"start": 860,
"end": 1058
} | class ____(Taggable):
def __init__(self):
self._loader = DictDataLoader({})
self.tags = []
self._parent = None
def get_play(self):
return None
| TaggableTestObj |
python | python-poetry__poetry | src/poetry/console/commands/build.py | {
"start": 5021,
"end": 8038
} | class ____(EnvCommand):
name = "build"
description = "Builds a package, as a tarball and a wheel by default."
options: ClassVar[list[Option]] = [
option("format", "f", "Limit the format to either sdist or wheel.", flag=False),
option(
"clean",
description="Clean output directory before building.",
flag=True,
),
option(
"local-version",
"l",
"Add or replace a local version label to the build. (<warning>Deprecated</warning>)",
flag=False,
),
option(
"output",
"o",
"Set output directory for build artifacts. Default is `dist`.",
default="dist",
flag=False,
),
option(
"config-settings",
"c",
description="Provide config settings that should be passed to backend in <key>=<value> format.",
flag=False,
multiple=True,
),
]
loggers: ClassVar[list[str]] = [
"poetry.core.masonry.builders.builder",
"poetry.core.masonry.builders.sdist",
"poetry.core.masonry.builders.wheel",
]
@staticmethod
def _prepare_config_settings(
local_version: str | None, config_settings: list[str] | None, io: IO
) -> dict[str, str]:
config_settings = config_settings or []
result = {}
if local_version:
io.write_error_line(
f"<warning>`<fg=yellow;options=bold>--local-version</>` is deprecated."
f" Use `<fg=yellow;options=bold>--config-settings local-version={local_version}</>`"
f" instead.</warning>"
)
result["local-version"] = local_version
for config_setting in config_settings:
if "=" not in config_setting:
raise ValueError(
f"Invalid config setting format: {config_setting}. "
"Config settings must be in the format 'key=value'"
)
key, _, value = config_setting.partition("=")
result[key] = value
return result
@staticmethod
def _prepare_formats(fmt: str | None) -> list[str]:
fmt = fmt or "all"
return ["sdist", "wheel"] if fmt == "all" else [fmt]
def handle(self) -> int:
build_handler = BuildHandler(
poetry=self.poetry,
env=self.env,
io=self.io,
)
build_options = BuildOptions(
clean=self.option("clean"),
formats=self._prepare_formats(self.option("format")), # type: ignore[arg-type]
output=self.option("output"),
config_settings=self._prepare_config_settings(
local_version=self.option("local-version"),
config_settings=self.option("config-settings"),
io=self.io,
),
)
return build_handler.build(options=build_options)
| BuildCommand |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/variables/partitioned_variables_test.py | {
"start": 12119,
"end": 26741
} | class ____(test.TestCase):
def _TestSaveSpec(self, slices, expected_specs):
self.assertEqual(len(expected_specs), len(slices))
for i in range(len(expected_specs)):
self.assertEqual(expected_specs[i], slices[i]._save_slice_info.spec)
def testVecConstantInit(self):
with self.cached_session():
rnd_par = constant_op.constant([1, 2, 3, 4])
vs = partitioned_variables.create_partitioned_variables([4], [4], rnd_par)
self.evaluate(variables.global_variables_initializer())
val = array_ops.concat(vs, 0)
rnd = self.evaluate(rnd_par)
self.assertAllClose(rnd, val)
self.assertEqual([dtypes.int32] * 4, [v.dtype.base_dtype for v in vs])
self._TestSaveSpec(vs, ["4 0,1", "4 1,1", "4 2,1", "4 3,1"])
def testConstantInit(self):
with self.cached_session():
rnd_par = constant_op.constant([[1, 2, 3, 4], [5, 6, 7, 8]])
vs = partitioned_variables.create_partitioned_variables([2, 4], [1, 2],
rnd_par)
self.evaluate(variables.global_variables_initializer())
val = array_ops.concat(vs, 1)
rnd = self.evaluate(rnd_par)
self.assertAllClose(rnd, val)
self.assertEqual([dtypes.int32] * 2, [v.dtype.base_dtype for v in vs])
self._TestSaveSpec(vs, ["2 4 0,2:0,2", "2 4 0,2:2,2"])
def _testNameHelper(self, use_resource=False):
with self.cached_session():
rnd_par = constant_op.constant([[1, 2, 3, 4], [5, 6, 7, 8]])
with variable_scope.variable_scope("hi", use_resource=use_resource):
vs1 = partitioned_variables.create_partitioned_variables([2, 4], [1, 2],
rnd_par)
vs2 = partitioned_variables.create_partitioned_variables([2, 4], [1, 2],
rnd_par)
self.evaluate(variables.global_variables_initializer())
var1_name = vs1[0]._save_slice_info.full_name
var2_name = vs2[0]._save_slice_info.full_name
self.assertEqual("hi/PartitionedVariable", var1_name)
self.assertEqual("hi/PartitionedVariable_1", var2_name)
self.assertEqual(var1_name + "/part_0:0", vs1[0].name)
self.assertEqual(var1_name + "/part_1:0", vs1[1].name)
self.assertEqual(var2_name + "/part_0:0", vs2[0].name)
self.assertEqual(var2_name + "/part_1:0", vs2[1].name)
# Test same variable.
with self.cached_session():
rnd_par = constant_op.constant([[1, 2, 3, 4], [5, 6, 7, 8]])
with variable_scope.variable_scope(
"hola", use_resource=use_resource) as vs:
vs1 = partitioned_variables.create_partitioned_variables(
[2, 4], [1, 2], rnd_par, dtype=dtypes.int32)
with variable_scope.variable_scope(
vs, reuse=True, use_resource=use_resource):
vs2 = partitioned_variables.create_partitioned_variables(
[2, 4], [1, 2], rnd_par, dtype=dtypes.int32)
self.evaluate(variables.global_variables_initializer())
var1_name = vs1[0]._save_slice_info.full_name
var2_name = vs2[0]._save_slice_info.full_name
self.assertEqual("hola/PartitionedVariable", var1_name)
self.assertEqual("hola/PartitionedVariable", var2_name)
self.assertEqual(var1_name + "/part_0:0", vs1[0].name)
self.assertEqual(var1_name + "/part_1:0", vs1[1].name)
self.assertEqual(var2_name + "/part_0:0", vs2[0].name)
self.assertEqual(var2_name + "/part_1:0", vs2[1].name)
# Test name_scope
with self.cached_session():
rnd_par = constant_op.constant([[1, 2, 3, 4], [5, 6, 7, 8]])
with ops.name_scope("ola"):
vs1 = partitioned_variables.create_partitioned_variables([2, 4], [1, 2],
rnd_par)
vs2 = partitioned_variables.create_partitioned_variables([2, 4], [1, 2],
rnd_par)
self.evaluate(variables.global_variables_initializer())
var1_name = vs1[0]._save_slice_info.full_name
var2_name = vs2[0]._save_slice_info.full_name
# Currently, the name scope 'ola' has no effect.
self.assertEqual("PartitionedVariable", var1_name)
self.assertEqual("PartitionedVariable_1", var2_name)
self.assertEqual(var1_name + "/part_0:0", vs1[0].name)
self.assertEqual(var1_name + "/part_1:0", vs1[1].name)
self.assertEqual(var2_name + "/part_0:0", vs2[0].name)
self.assertEqual(var2_name + "/part_1:0", vs2[1].name)
@test_util.run_deprecated_v1
def testName(self):
self._testNameHelper(use_resource=False)
def testResourceName(self):
self._testNameHelper(use_resource=True)
def testRandomInitValue(self):
with self.cached_session():
rnd = variables.Variable(random_ops.random_uniform([200, 40]))
vs = partitioned_variables.create_partitioned_variables(
rnd.get_shape(), [1, 10], initialized_value(rnd))
self.evaluate(variables.global_variables_initializer())
val = array_ops.concat(vs, 1)
rnd = self.evaluate(rnd)
self.assertAllClose(rnd, val)
self.assertEqual([dtypes.float32] * 10, [v.dtype.base_dtype for v in vs])
self._TestSaveSpec(vs, [
"200 40 0,200:0,4", "200 40 0,200:4,4", "200 40 0,200:8,4",
"200 40 0,200:12,4", "200 40 0,200:16,4", "200 40 0,200:20,4",
"200 40 0,200:24,4", "200 40 0,200:28,4", "200 40 0,200:32,4",
"200 40 0,200:36,4"
])
def testRandomInitUnevenPartitions(self):
with self.cached_session():
rnd = variables.Variable(
random_ops.random_uniform([20, 43], dtype=dtypes.float64))
var_lists = [
partitioned_variables.create_partitioned_variables(
rnd.get_shape(), [1, i], initialized_value(rnd))
for i in range(1, 10)
]
self.evaluate(variables.global_variables_initializer())
rnd_val = self.evaluate(rnd)
# Only check the slice save specs for the first 5 tf.
save_specs = [
# One slice
["20 43 0,20:0,43"],
# Two slices
["20 43 0,20:0,22", "20 43 0,20:22,21"],
# Three slices
["20 43 0,20:0,15", "20 43 0,20:15,14", "20 43 0,20:29,14"],
# Four slices
[
"20 43 0,20:0,11", "20 43 0,20:11,11", "20 43 0,20:22,11",
"20 43 0,20:33,10"
],
# Five slices
[
"20 43 0,20:0,9", "20 43 0,20:9,9", "20 43 0,20:18,9",
"20 43 0,20:27,8", "20 43 0,20:35,8"
]
]
for i, vs in enumerate(var_lists):
var_val = array_ops.concat(vs, 1)
self.assertAllClose(rnd_val, var_val)
self.assertEqual([dtypes.float64] * len(vs),
[v.dtype.base_dtype for v in vs])
if i < len(save_specs):
self._TestSaveSpec(vs, save_specs[i])
def testDegenerate(self):
with self.cached_session():
rnd = variables.Variable(random_ops.random_uniform([10, 43]))
vs = partitioned_variables.create_partitioned_variables(
rnd.get_shape(), [1, 1], initialized_value(rnd))
self.evaluate(variables.global_variables_initializer())
val = array_ops.concat(vs, 0)
rnd = self.evaluate(rnd)
self.assertAllClose(rnd, val)
self._TestSaveSpec(vs, ["10 43 0,10:0,43"])
def testSliceSizeOne(self):
with self.cached_session():
rnd = variables.Variable(random_ops.random_uniform([10, 43]))
vs = partitioned_variables.create_partitioned_variables(
rnd.get_shape(), [10, 1], initialized_value(rnd))
self.evaluate(variables.global_variables_initializer())
val = array_ops.concat(vs, 0)
rnd = self.evaluate(rnd)
self.assertAllClose(rnd, val)
self._TestSaveSpec(vs, [
"10 43 0,1:0,43", "10 43 1,1:0,43", "10 43 2,1:0,43",
"10 43 3,1:0,43", "10 43 4,1:0,43", "10 43 5,1:0,43",
"10 43 6,1:0,43", "10 43 7,1:0,43", "10 43 8,1:0,43", "10 43 9,1:0,43"
])
def testIotaInitializer(self):
self.assertAllClose([0., 1., 2., 3.], _IotaInitializer([4]))
self.assertAllClose([[0., 1.], [0., 10.], [0., 100.], [0., 1000.]],
_IotaInitializer([4, 2]))
with self.cached_session():
vs = partitioned_variables.create_partitioned_variables([13, 5], [3, 1],
_IotaInitializer)
self.evaluate(variables.global_variables_initializer())
slice0 = _IotaInitializer([5, 5])
slice1 = _IotaInitializer([4, 5])
slice2 = _IotaInitializer([4, 5])
val = array_ops.concat(vs, 0)
self.assertAllClose(slice0 + slice1 + slice2, val)
self._TestSaveSpec(vs, ["13 5 0,5:0,5", "13 5 5,4:0,5", "13 5 9,4:0,5"])
@test_util.run_deprecated_v1
def testRandomInitializer(self):
# Sanity check that the slices uses a different seed when using a random
# initializer function.
with self.cached_session():
var0, var1 = partitioned_variables.create_partitioned_variables(
[20, 12], [1, 2], init_ops.random_uniform_initializer())
self.evaluate(variables.global_variables_initializer())
val0, val1 = self.evaluate(var0).flatten(), self.evaluate(var1).flatten()
self.assertTrue(np.linalg.norm(val0 - val1) > 1e-6)
# Negative test that proves that slices have the same values if
# the random initializer uses a seed.
with self.cached_session():
var0, var1 = partitioned_variables.create_partitioned_variables(
[20, 12], [1, 2], init_ops.random_uniform_initializer(seed=201))
self.evaluate(variables.global_variables_initializer())
val0, val1 = self.evaluate(var0).flatten(), self.evaluate(var1).flatten()
self.assertAllClose(val0, val1)
def testSomeErrors(self):
with self.cached_session():
rnd = variables.Variable(random_ops.random_uniform([10, 43]))
with self.assertRaises(ValueError):
partitioned_variables.create_partitioned_variables(
[10], [1, 1], initialized_value(rnd))
with self.assertRaises(ValueError):
partitioned_variables.create_partitioned_variables(
[10, 20], [1], initialized_value(rnd))
with self.assertRaises(ValueError):
partitioned_variables.create_partitioned_variables(
[10, 43], [1], initialized_value(rnd))
with self.assertRaises(ValueError):
partitioned_variables.create_partitioned_variables(
[10, 43], [1, 2, 3], initialized_value(rnd))
with self.assertRaises(ValueError):
partitioned_variables.create_partitioned_variables(
[10, 43], [11, 1], initialized_value(rnd))
with self.assertRaises(ValueError):
partitioned_variables.create_partitioned_variables(
[10, 43], [20, 1], initialized_value(rnd))
with self.assertRaises(ValueError):
partitioned_variables.create_partitioned_variables(
[10, 43], [1, 50], initialized_value(rnd))
@test_util.run_deprecated_v1
def testControlDepsNone(self):
with self.cached_session() as session:
c = constant_op.constant(1.0)
with ops.control_dependencies([c]):
# d get the control dependency.
d = constant_op.constant(2.0)
# Partitioned variables do not.
var_x = variable_scope.get_variable(
"x",
shape=[2],
initializer=init_ops.ones_initializer(),
partitioner=partitioned_variables.variable_axis_size_partitioner(4))
ops_before_read = session.graph.get_operations()
var_x.as_tensor() # Caches the ops for subsequent reads.
reading_ops = [
op for op in session.graph.get_operations()
if op not in ops_before_read
]
self.assertEqual([c.op], d.op.control_inputs)
# Tests that no control dependencies are added to reading a partitioned
# variable which is similar to reading a variable.
for op in reading_ops:
self.assertEqual([], op.control_inputs)
@test_util.run_deprecated_v1
def testConcat(self):
with self.cached_session() as session:
var_x = variable_scope.get_variable(
"x",
initializer=constant_op.constant([1., 2.]),
partitioner=partitioned_variables.variable_axis_size_partitioner(4))
c = constant_op.constant(1.0)
with ops.control_dependencies([c]):
ops_before_concat = session.graph.get_operations()
value = var_x._concat() # pylint: disable=protected-access
concat_ops = [
op for op in session.graph.get_operations()
if op not in ops_before_concat
]
concat_control_inputs = [
ci for op in concat_ops for ci in op.control_inputs
]
self.assertTrue(
c.op in concat_control_inputs,
"var_x._concat() should get control dependencies from its scope.")
self.evaluate(variables.global_variables_initializer())
self.assertAllClose(value, var_x.as_tensor())
def testMetaGraphSaveLoad(self):
save_prefix = os.path.join(self.get_temp_dir(), "ckpt")
save_graph = ops.Graph()
with save_graph.as_default(), self.session(
graph=save_graph) as session:
partitioner = partitioned_variables.fixed_size_partitioner(5, axis=0)
with variable_scope.variable_scope("root", partitioner=partitioner):
v0 = variable_scope.get_variable(
"v0", dtype=dtypes.float32, shape=(10, 10))
v0_list = v0._get_variable_list()
v0_part = v0._get_partitions()
self.assertEqual(len(v0_list), 5)
self.assertAllEqual(v0_part, (5, 1))
self.evaluate(variables.global_variables_initializer())
save_graph.get_collection_ref("partvar").append(v0)
saver = saver_lib.Saver()
save_graph.finalize()
save_path = saver.save(sess=session, save_path=save_prefix)
previous_value = session.run(
save_graph.get_tensor_by_name(v0.name + ":0"))
restore_graph = ops.Graph()
with restore_graph.as_default(), self.session(
graph=restore_graph) as session:
saver = saver_lib.import_meta_graph(save_path + ".meta")
saver.restore(sess=session, save_path=save_path)
v0, = save_graph.get_collection_ref("partvar")
self.assertIsInstance(v0, variables.PartitionedVariable)
self.assertAllEqual(
previous_value,
session.run(restore_graph.get_tensor_by_name(v0.name + ":0")))
if __name__ == "__main__":
test.main()
| PartitionedVariablesTestCase |
python | great-expectations__great_expectations | tests/integration/fixtures/partition_and_sample_data/partitioner_test_cases_and_fixtures.py | {
"start": 8325,
"end": 8980
} | class ____(ABC):
def __init__(self, taxi_test_data: TaxiTestData):
self._taxi_test_data = taxi_test_data
@property
def taxi_test_data(self) -> TaxiTestData:
return self._taxi_test_data
@property
def test_df(self) -> pd.DataFrame:
return self._taxi_test_data.test_df
@property
def test_column_name(self) -> str:
return self._taxi_test_data.test_column_name
@property
def test_column_names(self) -> List[str]:
return self._taxi_test_data.test_column_names
@abstractmethod
def test_cases(self) -> List[TaxiPartitioningTestCase]:
pass
| TaxiPartitioningTestCasesBase |
python | ansible__ansible | test/units/plugins/callback/test_callback.py | {
"start": 13623,
"end": 14603
} | class ____(unittest.TestCase):
def _find_on_methods(self, callback):
cb_dir = dir(callback)
method_names = [x for x in cb_dir if '_on_' in x]
methods = [getattr(callback, mn) for mn in method_names]
return methods
def test_are_methods(self):
cb = CallbackBase()
for method in self._find_on_methods(cb):
self.assertIsInstance(method, types.MethodType)
def test_on_any(self):
cb = CallbackBase()
cb.v2_on_any('whatever', some_keyword='blippy')
cb.on_any('whatever', some_keyword='blippy')
def test_v2_v1_method_map() -> None:
"""Ensure that all v2 callback methods appear in the method map."""
expected_names = [name for name in dir(CallbackBase) if name.startswith('v2_')]
mapped_names = {method.__name__ for method in CallbackBase._v2_v1_method_map}
missing = [name for name in expected_names if name not in mapped_names]
assert not missing
| TestCallbackOnMethods |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/_7zip/package.py | {
"start": 227,
"end": 466
} | class ____(AutotoolsPackage):
"""Simple package with a name starting with a digit"""
homepage = "http://www.example.com"
url = "http://www.example.com/a-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
| _7zip |
python | doocs__leetcode | solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py | {
"start": 0,
"end": 678
} | class ____:
def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:
def bfs(u: int, v: int) -> int:
dist = [inf] * n
dist[u] = 0
q = deque([u])
while q:
i = q.popleft()
for j in g[i]:
if (i, j) != (u, v) and (j, i) != (u, v) and dist[j] == inf:
dist[j] = dist[i] + 1
q.append(j)
return dist[v] + 1
g = defaultdict(set)
for u, v in edges:
g[u].add(v)
g[v].add(u)
ans = min(bfs(u, v) for u, v in edges)
return ans if ans < inf else -1
| Solution |
python | dask__dask | dask/dataframe/dask_expr/io/io.py | {
"start": 19533,
"end": 22179
} | class ____(PartitionsFiltered, BlockwiseIO):
_parameters = [
"frame",
"chunksize",
"original_columns",
"meta",
"columns",
"_partitions",
]
_defaults = {
"chunksize": 50_000,
"original_columns": None,
"meta": None,
"columns": None,
"_partitions": None,
}
_absorb_projections = True
@functools.cached_property
def _meta(self):
meta = _meta_from_array(
self.frame, self.operand("original_columns"), self.operand("meta")
)
if self.operand("columns") is not None:
return meta[self.operand("columns")]
return meta
@functools.cached_property
def original_columns(self):
if self.operand("original_columns") is None:
if is_series_like(self._meta):
return [0]
return list(range(len(self._meta.columns)))
return self.operand("original_columns")
@functools.cached_property
def _column_indices(self):
if self.operand("columns") is None:
return slice(0, len(self.original_columns))
return [
i
for i, col in enumerate(self.original_columns)
if col in self.operand("columns")
]
def _divisions(self):
divisions = tuple(range(0, len(self.frame), self.chunksize))
divisions = divisions + (len(self.frame) - 1,)
return divisions
@functools.cached_property
def unfiltered_divisions(self):
return self._divisions()
def _filtered_task(self, name: Key, index: int) -> Task:
data = self.frame[slice(index * self.chunksize, (index + 1) * self.chunksize)]
if index == len(self.unfiltered_divisions) - 2:
idx = range(
self.unfiltered_divisions[index],
self.unfiltered_divisions[index + 1] + 1,
)
else:
idx = range(
self.unfiltered_divisions[index], self.unfiltered_divisions[index + 1]
)
if is_series_like(self._meta):
return Task(
name,
type(self._meta),
data,
idx,
self._meta.dtype,
self._meta.name,
_data_producer=True,
)
else:
if data.ndim == 2:
data = data[:, self._column_indices]
return Task(
name,
type(self._meta),
data,
idx,
self._meta.columns,
_data_producer=True,
)
| FromArray |
python | astropy__astropy | astropy/coordinates/matching.py | {
"start": 8357,
"end": 19913
} | class ____(NamedTuple):
"""Results of searching close pairs between two sets of sources.
See Also
--------
astropy.coordinates.search_around_3d
astropy.coordinates.search_around_sky
SkyCoord.search_around_3d
SkyCoord.search_around_sky
"""
indices_to_first_set: NDArray[np.int32] | NDArray[np.int64]
"""Indices of the elements of the found pairs in the first set of
sources."""
indices_to_second_set: NDArray[np.int32] | NDArray[np.int64]
"""Indices of the elements of the found pairs in the second set of
sources."""
angular_separation: Angle
"""The angular separations between the paired sources."""
physical_separation: Quantity
"""The physical separations between the paired sources. If either of
the source sets lack distances then the physical separations are
computed assuming all coordinates are points on the unit sphere."""
def search_around_3d(coords1, coords2, distlimit, storekdtree="kdtree_3d"):
"""
Searches for pairs of points that are at least as close as a specified
distance in 3D space.
This is intended for use on coordinate objects with arrays of coordinates,
not scalars. For scalar coordinates, it is better to use the
``separation_3d`` methods.
Parameters
----------
coords1 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`
The first set of coordinates, which will be searched for matches from
``coords2`` within ``seplimit``. Must be a one-dimensional coordinate array.
coords2 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`
The second set of coordinates, which will be searched for matches from
``coords1`` within ``seplimit``. Must be a one-dimensional coordinate array.
distlimit : `~astropy.units.Quantity` ['length']
The physical radius to search within. It should be broadcastable to the
same shape as ``coords1``.
storekdtree : bool or str, optional
If a string, will store the KD-Tree used in the search with the name
``storekdtree`` in ``coords2.cache``. This speeds up subsequent calls
to this function. If False, the KD-Trees are not saved.
Returns
-------
CoordinateSearchResult
A `~typing.NamedTuple` with attributes representing the indices
of the elements of found pairs in both source sets and angular
and physical separations of the pairs.
Notes
-----
This function requires `SciPy <https://www.scipy.org/>`_
to be installed or it will fail.
If you are using this function to search in a catalog for matches around
specific points, the convention is for ``coords2`` to be the catalog, and
``coords1`` are the points to search around. While these operations are
mathematically the same if ``coords1`` and ``coords2`` are flipped, some of
the optimizations may work better if this convention is obeyed.
In the current implementation, the return values are always sorted in the
same order as the ``coords1`` (so ``idx1`` is in ascending order). This is
considered an implementation detail, though, so it could change in a future
release.
"""
if coords1.ndim != 1 or coords2.ndim != 1:
msg = "search_around_3d only supports 1-dimensional coordinate arrays."
if coords1.isscalar or coords2.isscalar:
msg += " With a scalar array, use ``coord1.separation(coord2) < seplimit``."
raise ValueError(msg)
kdt2 = _get_cartesian_kdtree(coords2, storekdtree)
cunit = coords2.cartesian.x.unit
# we convert coord1 to match coord2's frame. We do it this way
# so that if the conversion does happen, the KD tree of coord2 at least gets
# saved. (by convention, coord2 is the "catalog" if that makes sense)
coords1 = coords1.transform_to(coords2)
kdt1 = _get_cartesian_kdtree(coords1, storekdtree, forceunit=cunit)
idxs1 = []
idxs2 = []
if distlimit.isscalar:
for i, matches in enumerate(
kdt1.query_ball_tree(kdt2, distlimit.to_value(cunit))
):
idxs1.extend(len(matches) * [i])
idxs2.extend(matches)
else:
for i, (point, distance) in enumerate(zip(kdt1.data, distlimit, strict=True)):
matches = kdt2.query_ball_point(point, distance.to_value(cunit))
idxs1.extend(len(matches) * [i])
idxs2.extend(matches)
return CoordinateSearchResult(
np.array(idxs1, dtype=int),
np.array(idxs2, dtype=int),
coords1[idxs1].separation(coords2[idxs2]),
coords1[idxs1].separation_3d(coords2[idxs2]),
)
def search_around_sky(coords1, coords2, seplimit, storekdtree="kdtree_sky"):
"""
Searches for pairs of points that have an angular separation at least as
close as a specified angle.
This is intended for use on coordinate objects with arrays of coordinates,
not scalars. For scalar coordinates, it is better to use the ``separation``
methods.
Parameters
----------
coords1 : coordinate-like
The first set of coordinates, which will be searched for matches from
``coords2`` within ``seplimit``. Must be a one-dimensional coordinate array.
coords2 : coordinate-like
The second set of coordinates, which will be searched for matches from
``coords1`` within ``seplimit``. Must be a one-dimensional coordinate array.
seplimit : `~astropy.units.Quantity` ['angle']
The on-sky separation to search within. It should be broadcastable to the same
shape as ``coords1``.
storekdtree : bool or str, optional
If a string, will store the KD-Tree used in the search with the name
``storekdtree`` in ``coords2.cache``. This speeds up subsequent calls
to this function. If False, the KD-Trees are not saved.
Returns
-------
CoordinateSearchResult
A `~typing.NamedTuple` with attributes representing the indices
of the elements of found pairs in both source sets and angular
and physical separations of the pairs. If either set of sources
lack distances, the physical separation is the 3D distance on
the unit sphere, rather than a true distance.
Notes
-----
This function requires `SciPy <https://www.scipy.org/>`_
to be installed or it will fail.
In the current implementation, the return values are always sorted in the
same order as the ``coords1`` (so ``idx1`` is in ascending order). This is
considered an implementation detail, though, so it could change in a future
release.
"""
if coords1.ndim != 1 or coords2.ndim != 1:
msg = "search_around_sky only supports 1-dimensional coordinate arrays."
if coords1.isscalar or coords2.isscalar:
msg += " With a scalar array, use ``coord1.separation(coord2) < seplimit``."
raise ValueError(msg)
# we convert coord1 to match coord2's frame. We do it this way
# so that if the conversion does happen, the KD tree of coord2 at least gets
# saved. (by convention, coord2 is the "catalog" if that makes sense)
coords1 = coords1.transform_to(coords2)
# strip out distance info
urepr1 = coords1.data.represent_as(UnitSphericalRepresentation)
kdt1 = _get_cartesian_kdtree(coords1.realize_frame(urepr1), storekdtree)
if storekdtree and coords2.cache.get(storekdtree):
# just use the stored KD-Tree
kdt2 = coords2.cache[storekdtree]
else:
# strip out distance info
urepr2 = coords2.data.represent_as(UnitSphericalRepresentation)
kdt2 = _get_cartesian_kdtree(coords2.realize_frame(urepr2), storekdtree)
if storekdtree:
coords2.cache["kdtree" if storekdtree is True else storekdtree] = kdt2
idxs1 = []
idxs2 = []
if seplimit.isscalar:
# this is the *cartesian* 3D distance that corresponds to the given angle
r = (2 * np.sin(Angle(0.5 * seplimit))).value
for i, matches in enumerate(kdt1.query_ball_tree(kdt2, r)):
idxs1.extend(len(matches) * [i])
idxs2.extend(matches)
else:
for i, (point, sep) in enumerate(zip(kdt1.data, seplimit, strict=True)):
radius = (2 * np.sin(Angle(0.5 * sep))).value
matches = kdt2.query_ball_point(point, radius)
idxs1.extend(len(matches) * [i])
idxs2.extend(matches)
d2ds = coords1[idxs1].separation(coords2[idxs2])
try:
d3ds = coords1[idxs1].separation_3d(coords2[idxs2])
except ValueError:
# they don't have distances, so we just fall back on the cartesian
# distance, computed from d2ds
d3ds = 2 * np.sin(0.5 * d2ds)
return CoordinateSearchResult(
np.array(idxs1, dtype=int), np.array(idxs2, dtype=int), d2ds, d3ds
)
def _get_cartesian_kdtree(coord, attrname_or_kdt="kdtree", forceunit=None):
"""
This is a utility function to retrieve (and build/cache, if necessary)
a 3D cartesian KD-Tree from various sorts of astropy coordinate objects.
Parameters
----------
coord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`
The coordinates to build the KD-Tree for.
attrname_or_kdt : bool or str or KDTree
If a string, will store the KD-Tree used for the computation in the
``coord``, in ``coord.cache`` with the provided name. If given as a
KD-Tree, it will just be used directly.
forceunit : unit or None
If a unit, the cartesian coordinates will convert to that unit before
being put in the KD-Tree. If None, whatever unit it's already in
will be used
Returns
-------
kdt : `~scipy.spatial.KDTree`
The KD-Tree representing the 3D cartesian representation of the input
coordinates.
"""
from scipy.spatial import KDTree
if attrname_or_kdt is True: # backwards compatibility for pre v0.4
attrname_or_kdt = "kdtree"
# figure out where any cached KDTree might be
if isinstance(attrname_or_kdt, str):
kdt = coord.cache.get(attrname_or_kdt, None)
if kdt is not None and not isinstance(kdt, KDTree):
raise TypeError(
f'The `attrname_or_kdt` "{attrname_or_kdt}" is not a scipy KD tree!'
)
elif isinstance(attrname_or_kdt, KDTree):
kdt = attrname_or_kdt
attrname_or_kdt = None
elif not attrname_or_kdt:
kdt = None
else:
raise TypeError(
"Invalid `attrname_or_kdt` argument for KD-Tree:" + str(attrname_or_kdt)
)
if kdt is None:
# need to build the cartesian KD-tree for the catalog
if forceunit is None:
cartxyz = coord.cartesian.xyz
else:
cartxyz = coord.cartesian.xyz.to(forceunit)
flatxyz = cartxyz.reshape((3, np.prod(cartxyz.shape) // 3))
# There should be no NaNs in the kdtree data.
if np.isnan(flatxyz.value).any():
raise ValueError("Catalog coordinates cannot contain NaN entries.")
# Not obvious if compact_nodes=False, balanced_tree=False is still needed but
# we stay backwards-compatible with previous versions of `astropy` for now.
kdt = KDTree(flatxyz.value.T, compact_nodes=False, balanced_tree=False)
if attrname_or_kdt:
# cache the kdtree in `coord`
coord.cache[attrname_or_kdt] = kdt
return kdt
| CoordinateSearchResult |
python | doocs__leetcode | solution/2600-2699/2679.Sum in a Matrix/Solution.py | {
"start": 0,
"end": 160
} | class ____:
def matrixSum(self, nums: List[List[int]]) -> int:
for row in nums:
row.sort()
return sum(map(max, zip(*nums)))
| Solution |
python | python-openxml__python-docx | tests/opc/test_phys_pkg.py | {
"start": 2099,
"end": 2272
} | class ____:
def it_raises_when_pkg_path_is_not_a_package(self):
with pytest.raises(PackageNotFoundError):
PhysPkgReader("foobar")
| DescribePhysPkgReader |
python | scipy__scipy | scipy/linalg/tests/test_blas.py | {
"start": 29997,
"end": 31396
} | class ____:
def setup_method(self):
self.a = np.array([[1., 0.],
[0., -2.],
[2., 3.]])
self.b = np.array([[0., 1.],
[1., 0.],
[0, 1.]])
self.t = np.array([[0., -1., 3.],
[-1., 0., 0.],
[3., 0., 6.]])
self.tt = np.array([[0., 1.],
[1., 6]])
@parametrize_blas(fblas, "syr2k", "sdcz")
def test_syr2k(self, f, dtype):
c = f(a=self.a, b=self.b, alpha=1.)
assert_array_almost_equal(np.triu(c), np.triu(self.t))
c = f(a=self.a, b=self.b, alpha=1., lower=1)
assert_array_almost_equal(np.tril(c), np.tril(self.t))
c0 = np.ones(self.t.shape)
c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0)
assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
c = f(a=self.a, b=self.b, alpha=1., trans=1)
assert_array_almost_equal(np.triu(c), np.triu(self.tt))
# prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
@parametrize_blas(fblas, "syr2k", "sdcz")
def test_syr2k_wrong_c(self, f, dtype):
with pytest.raises(Exception):
f(a=self.a, b=self.b, alpha=1., c=np.zeros((15, 8)))
# if C is supplied, it must have compatible dimensions
| TestBLAS3Syr2k |
python | coleifer__peewee | tests/cysqlite.py | {
"start": 7820,
"end": 11558
} | class ____(CyDatabaseTestCase):
def setUp(self):
super(TestBlob, self).setUp()
self.Register = Table('register', ('id', 'data'))
self.execute('CREATE TABLE register (id INTEGER NOT NULL PRIMARY KEY, '
'data BLOB NOT NULL)')
def create_blob_row(self, nbytes):
Register = self.Register.bind(self.database)
Register.insert({Register.data: ZeroBlob(nbytes)}).execute()
return self.database.last_insert_rowid
def test_blob(self):
rowid1024 = self.create_blob_row(1024)
rowid16 = self.create_blob_row(16)
blob = Blob(self.database, 'register', 'data', rowid1024)
self.assertEqual(len(blob), 1024)
blob.write(b'x' * 1022)
blob.write(b'zz')
blob.seek(1020)
self.assertEqual(blob.tell(), 1020)
data = blob.read(3)
self.assertEqual(data, b'xxz')
self.assertEqual(blob.read(), b'z')
self.assertEqual(blob.read(), b'')
blob.seek(-10, 2)
self.assertEqual(blob.tell(), 1014)
self.assertEqual(blob.read(), b'xxxxxxxxzz')
blob.reopen(rowid16)
self.assertEqual(blob.tell(), 0)
self.assertEqual(len(blob), 16)
blob.write(b'x' * 15)
self.assertEqual(blob.tell(), 15)
def test_blob_exceed_size(self):
rowid = self.create_blob_row(16)
blob = self.database.blob_open('register', 'data', rowid)
with self.assertRaisesCtx(ValueError):
blob.seek(17, 0)
with self.assertRaisesCtx(ValueError):
blob.write(b'x' * 17)
blob.write(b'x' * 16)
self.assertEqual(blob.tell(), 16)
blob.seek(0)
data = blob.read(17) # Attempting to read more data is OK.
self.assertEqual(data, b'x' * 16)
data = blob.read(1)
self.assertEqual(data, b'')
blob.seek(0)
blob.write(b'0123456789abcdef')
self.assertEqual(blob[0], b'0')
self.assertEqual(blob[-1], b'f')
self.assertRaises(IndexError, lambda: data[17])
blob.close()
def test_blob_errors_opening(self):
rowid = self.create_blob_row(4)
with self.assertRaisesCtx(OperationalError):
blob = self.database.blob_open('register', 'data', rowid + 1)
with self.assertRaisesCtx(OperationalError):
blob = self.database.blob_open('register', 'missing', rowid)
with self.assertRaisesCtx(OperationalError):
blob = self.database.blob_open('missing', 'data', rowid)
def test_blob_operating_on_closed(self):
rowid = self.create_blob_row(4)
blob = self.database.blob_open('register', 'data', rowid)
self.assertEqual(len(blob), 4)
blob.close()
with self.assertRaisesCtx(InterfaceError):
len(blob)
self.assertRaises(InterfaceError, blob.read)
self.assertRaises(InterfaceError, blob.write, b'foo')
self.assertRaises(InterfaceError, blob.seek, 0, 0)
self.assertRaises(InterfaceError, blob.tell)
self.assertRaises(InterfaceError, blob.reopen, rowid)
blob.close() # Safe to call again.
def test_blob_readonly(self):
rowid = self.create_blob_row(4)
blob = self.database.blob_open('register', 'data', rowid)
blob.write(b'huey')
blob.seek(0)
self.assertEqual(blob.read(), b'huey')
blob.close()
blob = self.database.blob_open('register', 'data', rowid, True)
self.assertEqual(blob.read(), b'huey')
blob.seek(0)
with self.assertRaisesCtx(OperationalError):
blob.write(b'meow')
# BLOB is read-only.
self.assertEqual(blob.read(), b'huey')
| TestBlob |
python | pandas-dev__pandas | pandas/core/generic.py | {
"start": 4959,
"end": 432875
} | class ____(PandasObject, indexing.IndexingMixin):
"""
N-dimensional analogue of DataFrame. Store multi-dimensional in a
size-mutable, labeled data structure
Parameters
----------
data : BlockManager
axes : list
copy : bool, default False
"""
_internal_names: list[str] = [
"_mgr",
"_cache",
"_name",
"_metadata",
"_flags",
]
_internal_names_set: set[str] = set(_internal_names)
_accessors: set[str] = set()
_hidden_attrs: frozenset[str] = frozenset([])
_metadata: list[str] = []
_mgr: Manager
_attrs: dict[Hashable, Any]
_typ: str
# ----------------------------------------------------------------------
# Constructors
def __init__(self, data: Manager) -> None:
object.__setattr__(self, "_mgr", data)
object.__setattr__(self, "_attrs", {})
object.__setattr__(self, "_flags", Flags(self, allows_duplicate_labels=True))
@final
@classmethod
def _init_mgr(
cls,
mgr: Manager,
axes: dict[Literal["index", "columns"], Axes | None],
dtype: DtypeObj | None = None,
copy: bool = False,
) -> Manager:
"""passed a manager and a axes dict"""
for a, axe in axes.items():
if axe is not None:
axe = ensure_index(axe)
bm_axis = cls._get_block_manager_axis(a)
mgr = mgr.reindex_axis(axe, axis=bm_axis)
# make a copy if explicitly requested
if copy:
mgr = mgr.copy(deep=True)
if dtype is not None:
# avoid further copies if we can
if (
isinstance(mgr, BlockManager)
and len(mgr.blocks) == 1
and mgr.blocks[0].values.dtype == dtype
):
pass
else:
mgr = mgr.astype(dtype=dtype)
return mgr
@final
@classmethod
def _from_mgr(cls, mgr: Manager, axes: list[Index]) -> Self:
"""
Construct a new object of this type from a Manager object and axes.
Parameters
----------
mgr : Manager
Must have the same ndim as cls.
axes : list[Index]
Notes
-----
The axes must match mgr.axes, but are required for future-proofing
in the event that axes are refactored out of the Manager objects.
"""
obj = cls.__new__(cls)
NDFrame.__init__(obj, mgr)
return obj
# ----------------------------------------------------------------------
# attrs and flags
@property
def attrs(self) -> dict[Hashable, Any]:
"""
Dictionary of global attributes of this dataset.
.. warning::
attrs is experimental and may change without warning.
See Also
--------
DataFrame.flags : Global flags applying to this object.
Notes
-----
Many operations that create new datasets will copy ``attrs``. Copies
are always deep so that changing ``attrs`` will only affect the
present dataset. :func:`pandas.concat` and :func:`pandas.merge` will
only copy ``attrs`` if all input datasets have the same ``attrs``.
Examples
--------
For Series:
>>> ser = pd.Series([1, 2, 3])
>>> ser.attrs = {"A": [10, 20, 30]}
>>> ser.attrs
{'A': [10, 20, 30]}
For DataFrame:
>>> df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
>>> df.attrs = {"A": [10, 20, 30]}
>>> df.attrs
{'A': [10, 20, 30]}
"""
return self._attrs
@attrs.setter
def attrs(self, value: Mapping[Hashable, Any]) -> None:
self._attrs = dict(value)
@final
@property
def flags(self) -> Flags:
"""
Get the properties associated with this pandas object.
The available flags are
* :attr:`Flags.allows_duplicate_labels`
See Also
--------
Flags : Flags that apply to pandas objects.
DataFrame.attrs : Global metadata applying to this dataset.
Notes
-----
"Flags" differ from "metadata". Flags reflect properties of the
pandas object (the Series or DataFrame). Metadata refer to properties
of the dataset, and should be stored in :attr:`DataFrame.attrs`.
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2]})
>>> df.flags
<Flags(allows_duplicate_labels=True)>
Flags can be get or set using ``.``
>>> df.flags.allows_duplicate_labels
True
>>> df.flags.allows_duplicate_labels = False
Or by slicing with a key
>>> df.flags["allows_duplicate_labels"]
False
>>> df.flags["allows_duplicate_labels"] = True
"""
return self._flags
@final
def set_flags(
self,
*,
copy: bool | lib.NoDefault = lib.no_default,
allows_duplicate_labels: bool | None = None,
) -> Self:
"""
Return a new object with updated flags.
This method creates a shallow copy of the original object, preserving its
underlying data while modifying its global flags. In particular, it allows
you to update properties such as whether duplicate labels are permitted. This
behavior is especially useful in method chains, where one wishes to
adjust DataFrame or Series characteristics without altering the original object.
Parameters
----------
copy : bool, default False
Specify if a copy of the object should be made.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
allows_duplicate_labels : bool, optional
Whether the returned object allows duplicate labels.
Returns
-------
Series or DataFrame
The same type as the caller.
See Also
--------
DataFrame.attrs : Global metadata applying to this dataset.
DataFrame.flags : Global flags applying to this object.
Notes
-----
This method returns a new object that's a view on the same data
as the input. Mutating the input or the output values will be reflected
in the other.
This method is intended to be used in method chains.
"Flags" differ from "metadata". Flags reflect properties of the
pandas object (the Series or DataFrame). Metadata refer to properties
of the dataset, and should be stored in :attr:`DataFrame.attrs`.
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2]})
>>> df.flags.allows_duplicate_labels
True
>>> df2 = df.set_flags(allows_duplicate_labels=False)
>>> df2.flags.allows_duplicate_labels
False
"""
self._check_copy_deprecation(copy)
df = self.copy(deep=False)
if allows_duplicate_labels is not None:
df.flags["allows_duplicate_labels"] = allows_duplicate_labels
return df
@final
@classmethod
def _validate_dtype(cls, dtype) -> DtypeObj | None:
"""validate the passed dtype"""
if dtype is not None:
dtype = pandas_dtype(dtype)
# a compound dtype
if dtype.kind == "V":
raise NotImplementedError(
"compound dtypes are not implemented "
f"in the {cls.__name__} constructor"
)
return dtype
# ----------------------------------------------------------------------
# Construction
# error: Signature of "_constructor" incompatible with supertype "PandasObject"
@property
def _constructor(self) -> Callable[..., Self]: # type: ignore[override]
"""
Used when a manipulation result has the same dimensions as the
original.
"""
raise AbstractMethodError(self)
# ----------------------------------------------------------------------
# Axis
_AXIS_ORDERS: list[Literal["index", "columns"]]
_AXIS_TO_AXIS_NUMBER: dict[Axis, AxisInt] = {0: 0, "index": 0, "rows": 0}
_info_axis_number: int
_info_axis_name: Literal["index", "columns"]
_AXIS_LEN: int
@final
def _construct_axes_dict(
self, axes: Sequence[Axis] | None = None, **kwargs: AxisInt
) -> dict:
"""Return an axes dictionary for myself."""
d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
# error: Argument 1 to "update" of "MutableMapping" has incompatible type
# "Dict[str, Any]"; expected "SupportsKeysAndGetItem[Union[int, str], Any]"
d.update(kwargs) # type: ignore[arg-type]
return d
@final
@classmethod
def _get_axis_number(cls, axis: Axis) -> AxisInt:
try:
return cls._AXIS_TO_AXIS_NUMBER[axis]
except KeyError as err:
raise ValueError(
f"No axis named {axis} for object type {cls.__name__}"
) from err
@final
@classmethod
def _get_axis_name(cls, axis: Axis) -> Literal["index", "columns"]:
axis_number = cls._get_axis_number(axis)
return cls._AXIS_ORDERS[axis_number]
@final
def _get_axis(self, axis: Axis) -> Index:
axis_number = self._get_axis_number(axis)
assert axis_number in {0, 1}
return self.index if axis_number == 0 else self.columns
@final
@classmethod
def _get_block_manager_axis(cls, axis: Axis) -> AxisInt:
"""Map the axis to the block_manager axis."""
axis = cls._get_axis_number(axis)
ndim = cls._AXIS_LEN
if ndim == 2:
# i.e. DataFrame
return 1 - axis
return axis
@final
def _get_axis_resolvers(self, axis: str) -> dict[str, Series | MultiIndex]:
# index or columns
axis_index = getattr(self, axis)
d = {}
prefix = axis[0]
for i, name in enumerate(axis_index.names):
if name is not None:
key = level = name
else:
# prefix with 'i' or 'c' depending on the input axis
# e.g., you must do ilevel_0 for the 0th level of an unnamed
# multiiindex
key = f"{prefix}level_{i}"
level = i
level_values = axis_index.get_level_values(level)
s = level_values.to_series()
s.index = axis_index
d[key] = s
# put the index/columns itself in the dict
if isinstance(axis_index, MultiIndex):
dindex = axis_index
else:
dindex = axis_index.to_series()
d[axis] = dindex
return d
@final
def _get_index_resolvers(self) -> dict[Hashable, Series | MultiIndex]:
from pandas.core.computation.parsing import clean_column_name
d: dict[str, Series | MultiIndex] = {}
for axis_name in self._AXIS_ORDERS:
d.update(self._get_axis_resolvers(axis_name))
return {clean_column_name(k): v for k, v in d.items() if not isinstance(k, int)}
@final
def _get_cleaned_column_resolvers(self) -> dict[Hashable, Series]:
"""
Return the special character free column resolvers of a DataFrame.
Column names with special characters are 'cleaned up' so that they can
be referred to by backtick quoting.
Used in :meth:`DataFrame.eval`.
"""
from pandas.core.computation.parsing import clean_column_name
from pandas.core.series import Series
if isinstance(self, ABCSeries):
return {clean_column_name(self.name): self}
dtypes = self.dtypes
return {
clean_column_name(k): Series(
v, copy=False, index=self.index, name=k, dtype=dtype
).__finalize__(self)
for k, v, dtype in zip(
self.columns,
self._iter_column_arrays(),
dtypes,
strict=True,
)
}
@final
@property
def _info_axis(self) -> Index:
return getattr(self, self._info_axis_name)
@property
def shape(self) -> tuple[int, ...]:
"""
Return a tuple of axis dimensions
"""
return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)
@property
def axes(self) -> list[Index]:
"""
Return index label(s) of the internal NDFrame
"""
# we do it this way because if we have reversed axes, then
# the block manager shows then reversed
return [self._get_axis(a) for a in self._AXIS_ORDERS]
@final
@property
def ndim(self) -> int:
"""
Return an int representing the number of axes / array dimensions.
Return 1 if Series. Otherwise return 2 if DataFrame.
See Also
--------
numpy.ndarray.ndim : Number of array dimensions.
Examples
--------
>>> s = pd.Series({"a": 1, "b": 2, "c": 3})
>>> s.ndim
1
>>> df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
>>> df.ndim
2
"""
return self._mgr.ndim
@final
@property
def size(self) -> int:
"""
Return an int representing the number of elements in this object.
Return the number of rows if Series. Otherwise return the number of
rows times number of columns if DataFrame.
See Also
--------
numpy.ndarray.size : Number of elements in the array.
Examples
--------
>>> s = pd.Series({"a": 1, "b": 2, "c": 3})
>>> s.size
3
>>> df = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]})
>>> df.size
4
"""
return int(np.prod(self.shape))
def set_axis(
self,
labels,
*,
axis: Axis = 0,
copy: bool | lib.NoDefault = lib.no_default,
) -> Self:
"""
Assign desired index to given axis.
Indexes for%(extended_summary_sub)s row labels can be changed by assigning
a list-like or Index.
Parameters
----------
labels : list-like, Index
The values for the new index.
axis : %(axes_single_arg)s, default 0
The axis to update. The value 0 identifies the rows. For `Series`
this parameter is unused and defaults to 0.
copy : bool, default False
Whether to make a copy of the underlying data.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
Returns
-------
%(klass)s
An object of type %(klass)s.
See Also
--------
%(klass)s.rename_axis : Alter the name of the index%(see_also_sub)s.
"""
self._check_copy_deprecation(copy)
return self._set_axis_nocheck(labels, axis, inplace=False)
@overload
def _set_axis_nocheck(
self, labels, axis: Axis, inplace: Literal[False]
) -> Self: ...
@overload
def _set_axis_nocheck(self, labels, axis: Axis, inplace: Literal[True]) -> None: ...
@overload
def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool) -> Self | None: ...
@final
def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool) -> Self | None:
if inplace:
setattr(self, self._get_axis_name(axis), labels)
return None
obj = self.copy(deep=False)
setattr(obj, obj._get_axis_name(axis), labels)
return obj
@final
def _set_axis(self, axis: AxisInt, labels: AnyArrayLike | list) -> None:
"""
This is called from the cython code when we set the `index` attribute
directly, e.g. `series.index = [1, 2, 3]`.
"""
labels = ensure_index(labels)
self._mgr.set_axis(axis, labels)
@final
@doc(klass=_shared_doc_kwargs["klass"])
def droplevel(self, level: IndexLabel, axis: Axis = 0) -> Self:
"""
Return {klass} with requested index / column level(s) removed.
Parameters
----------
level : int, str, or list-like
If a string is given, must be the name of a level
If list-like, elements must be names or positional indexes
of levels.
axis : {{0 or 'index', 1 or 'columns'}}, default 0
Axis along which the level(s) is removed:
* 0 or 'index': remove level(s) in column.
* 1 or 'columns': remove level(s) in row.
For `Series` this parameter is unused and defaults to 0.
Returns
-------
{klass}
{klass} with requested index / column level(s) removed.
See Also
--------
DataFrame.replace : Replace values given in `to_replace` with `value`.
DataFrame.pivot : Return reshaped DataFrame organized by given
index / column values.
Examples
--------
>>> df = (
... pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
... .set_index([0, 1])
... .rename_axis(["a", "b"])
... )
>>> df.columns = pd.MultiIndex.from_tuples(
... [("c", "e"), ("d", "f")], names=["level_1", "level_2"]
... )
>>> df
level_1 c d
level_2 e f
a b
1 2 3 4
5 6 7 8
9 10 11 12
>>> df.droplevel("a")
level_1 c d
level_2 e f
b
2 3 4
6 7 8
10 11 12
>>> df.droplevel("level_2", axis=1)
level_1 c d
a b
1 2 3 4
5 6 7 8
9 10 11 12
"""
labels = self._get_axis(axis)
new_labels = labels.droplevel(level)
return self.set_axis(new_labels, axis=axis)
def pop(self, item: Hashable) -> Series | Any:
result = self[item]
del self[item]
return result
@final
def squeeze(self, axis: Axis | None = None) -> Scalar | Series | DataFrame:
"""
Squeeze 1 dimensional axis objects into scalars.
Series or DataFrames with a single element are squeezed to a scalar.
DataFrames with a single column or a single row are squeezed to a
Series. Otherwise the object is unchanged.
This method is most useful when you don't know if your
object is a Series or DataFrame, but you do know it has just a single
column. In that case you can safely call `squeeze` to ensure you have a
Series.
Parameters
----------
axis : {0 or 'index', 1 or 'columns', None}, default None
A specific axis to squeeze. By default, all length-1 axes are
squeezed. For `Series` this parameter is unused and defaults to `None`.
Returns
-------
DataFrame, Series, or scalar
The projection after squeezing `axis` or all the axes.
See Also
--------
Series.iloc : Integer-location based indexing for selecting scalars.
DataFrame.iloc : Integer-location based indexing for selecting Series.
Series.to_frame : Inverse of DataFrame.squeeze for a
single-column DataFrame.
Examples
--------
>>> primes = pd.Series([2, 3, 5, 7])
Slicing might produce a Series with a single value:
>>> even_primes = primes[primes % 2 == 0]
>>> even_primes
0 2
dtype: int64
>>> even_primes.squeeze()
np.int64(2)
Squeezing objects with more than one value in every axis does nothing:
>>> odd_primes = primes[primes % 2 == 1]
>>> odd_primes
1 3
2 5
3 7
dtype: int64
>>> odd_primes.squeeze()
1 3
2 5
3 7
dtype: int64
Squeezing is even more effective when used with DataFrames.
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
>>> df
a b
0 1 2
1 3 4
Slicing a single column will produce a DataFrame with the columns
having only one value:
>>> df_a = df[["a"]]
>>> df_a
a
0 1
1 3
So the columns can be squeezed down, resulting in a Series:
>>> df_a.squeeze("columns")
0 1
1 3
Name: a, dtype: int64
Slicing a single row from a single column will produce a single
scalar DataFrame:
>>> df_0a = df.loc[df.index < 1, ["a"]]
>>> df_0a
a
0 1
Squeezing the rows produces a single scalar Series:
>>> df_0a.squeeze("rows")
a 1
Name: 0, dtype: int64
Squeezing all axes will project directly into a scalar:
>>> df_0a.squeeze()
np.int64(1)
"""
axes = range(self._AXIS_LEN) if axis is None else (self._get_axis_number(axis),)
result = self.iloc[
tuple(
0 if i in axes and len(a) == 1 else slice(None)
for i, a in enumerate(self.axes)
)
]
if isinstance(result, NDFrame):
result = result.__finalize__(self, method="squeeze")
return result
# ----------------------------------------------------------------------
# Rename
@overload
def _rename(
self,
mapper: Renamer | None = ...,
*,
index: Renamer | None = ...,
columns: Renamer | None = ...,
axis: Axis | None = ...,
inplace: Literal[False] = ...,
level: Level | None = ...,
errors: str = ...,
) -> Self: ...
@overload
def _rename(
self,
mapper: Renamer | None = ...,
*,
index: Renamer | None = ...,
columns: Renamer | None = ...,
axis: Axis | None = ...,
inplace: Literal[True],
level: Level | None = ...,
errors: str = ...,
) -> None: ...
@overload
def _rename(
self,
mapper: Renamer | None = ...,
*,
index: Renamer | None = ...,
columns: Renamer | None = ...,
axis: Axis | None = ...,
inplace: bool,
level: Level | None = ...,
errors: str = ...,
) -> Self | None: ...
@final
def _rename(
self,
mapper: Renamer | None = None,
*,
index: Renamer | None = None,
columns: Renamer | None = None,
axis: Axis | None = None,
inplace: bool = False,
level: Level | None = None,
errors: str = "ignore",
) -> Self | None:
# called by Series.rename and DataFrame.rename
if mapper is None and index is None and columns is None:
raise TypeError("must pass an index to rename")
if index is not None or columns is not None:
if axis is not None:
raise TypeError(
"Cannot specify both 'axis' and any of 'index' or 'columns'"
)
if mapper is not None:
raise TypeError(
"Cannot specify both 'mapper' and any of 'index' or 'columns'"
)
else:
# use the mapper argument
if axis and self._get_axis_number(axis) == 1:
columns = mapper
else:
index = mapper
self._check_inplace_and_allows_duplicate_labels(inplace)
result = self if inplace else self.copy(deep=False)
for axis_no, replacements in enumerate((index, columns)):
if replacements is None:
continue
ax = self._get_axis(axis_no)
f = common.get_rename_function(replacements)
if level is not None:
level = ax._get_level_number(level)
if isinstance(replacements, ABCSeries) and not replacements.index.is_unique:
# GH#58621
raise ValueError("Cannot rename with a Series with non-unique index.")
# GH 13473
if not callable(replacements):
if ax._is_multi and level is not None:
indexer = ax.get_level_values(level).get_indexer_for(replacements)
else:
indexer = ax.get_indexer_for(replacements)
if errors == "raise" and len(indexer[indexer == -1]):
missing_labels = [
label
for index, label in enumerate(replacements)
if indexer[index] == -1
]
raise KeyError(f"{missing_labels} not found in axis")
new_index = ax._transform_index(f, level=level)
result._set_axis_nocheck(new_index, axis=axis_no, inplace=True)
if inplace:
self._update_inplace(result)
return None
else:
return result.__finalize__(self, method="rename")
@overload
def rename_axis(
self,
mapper: IndexLabel | lib.NoDefault = ...,
*,
index=...,
columns=...,
axis: Axis = ...,
copy: bool | lib.NoDefault = lib.no_default,
inplace: Literal[False] = ...,
) -> Self: ...
@overload
def rename_axis(
self,
mapper: IndexLabel | lib.NoDefault = ...,
*,
index=...,
columns=...,
axis: Axis = ...,
copy: bool | lib.NoDefault = lib.no_default,
inplace: Literal[True],
) -> None: ...
@overload
def rename_axis(
self,
mapper: IndexLabel | lib.NoDefault = ...,
*,
index=...,
columns=...,
axis: Axis = ...,
copy: bool | lib.NoDefault = lib.no_default,
inplace: bool = ...,
) -> Self | None: ...
def rename_axis(
self,
mapper: IndexLabel | lib.NoDefault = lib.no_default,
*,
index=lib.no_default,
columns=lib.no_default,
axis: Axis = 0,
copy: bool | lib.NoDefault = lib.no_default,
inplace: bool = False,
) -> Self | None:
"""
Set the name of the axis for the index or columns.
Parameters
----------
mapper : scalar, list-like, optional
Value to set the axis name attribute.
Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index``
and/or ``columns``.
index : scalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to
apply to that axis' values.
columns : scalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to
apply to that axis' values.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to rename.
copy : bool, default False
Also copy underlying data.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
inplace : bool, default False
Modifies the object directly, instead of creating a new Series
or DataFrame.
Returns
-------
DataFrame, or None
The same type as the caller or None if ``inplace=True``.
See Also
--------
Series.rename : Alter Series index labels or name.
DataFrame.rename : Alter DataFrame index labels or name.
Index.rename : Set new names on index.
Notes
-----
``DataFrame.rename_axis`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
The first calling convention will only modify the names of
the index and/or the names of the Index object that is the columns.
In this case, the parameter ``copy`` is ignored.
The second calling convention will modify the names of the
corresponding index if mapper is a list or a scalar.
However, if mapper is dict-like or a function, it will use the
deprecated behavior of modifying the axis *labels*.
We *highly* recommend using keyword arguments to clarify your
intent.
Examples
--------
**DataFrame**
>>> df = pd.DataFrame(
... {"num_legs": [4, 4, 2], "num_arms": [0, 0, 2]}, ["dog", "cat", "monkey"]
... )
>>> df
num_legs num_arms
dog 4 0
cat 4 0
monkey 2 2
>>> df = df.rename_axis("animal")
>>> df
num_legs num_arms
animal
dog 4 0
cat 4 0
monkey 2 2
>>> df = df.rename_axis("limbs", axis="columns")
>>> df
limbs num_legs num_arms
animal
dog 4 0
cat 4 0
monkey 2 2
**MultiIndex**
>>> df.index = pd.MultiIndex.from_product(
... [["mammal"], ["dog", "cat", "monkey"]], names=["type", "name"]
... )
>>> df
limbs num_legs num_arms
type name
mammal dog 4 0
cat 4 0
monkey 2 2
>>> df.rename_axis(index={"type": "class"})
limbs num_legs num_arms
class name
mammal dog 4 0
cat 4 0
monkey 2 2
>>> df.rename_axis(columns=str.upper)
LIMBS num_legs num_arms
type name
mammal dog 4 0
cat 4 0
monkey 2 2
"""
self._check_copy_deprecation(copy)
axes = {"index": index, "columns": columns}
if axis is not None:
axis = self._get_axis_number(axis)
inplace = validate_bool_kwarg(inplace, "inplace")
if mapper is not lib.no_default:
# Use v0.23 behavior if a scalar or list
non_mapper = is_scalar(mapper) or (
is_list_like(mapper) and not is_dict_like(mapper)
)
if non_mapper:
return self._set_axis_name(mapper, axis=axis, inplace=inplace)
else:
raise ValueError("Use `.rename` to alter labels with a mapper.")
else:
# Use new behavior. Means that index and/or columns
# is specified
result = self if inplace else self.copy(deep=False)
for axis in range(self._AXIS_LEN):
v = axes.get(self._get_axis_name(axis))
if v is lib.no_default:
continue
non_mapper = is_scalar(v) or (is_list_like(v) and not is_dict_like(v))
if non_mapper:
newnames = v
else:
f = common.get_rename_function(v)
curnames = self._get_axis(axis).names
newnames = [f(name) for name in curnames]
result._set_axis_name(newnames, axis=axis, inplace=True)
if not inplace:
return result
return None
@overload
def _set_axis_name(
self, name, axis: Axis = ..., *, inplace: Literal[False] = ...
) -> Self: ...
@overload
def _set_axis_name(
self, name, axis: Axis = ..., *, inplace: Literal[True]
) -> None: ...
@overload
def _set_axis_name(
self, name, axis: Axis = ..., *, inplace: bool
) -> Self | None: ...
@final
def _set_axis_name(
self, name, axis: Axis = 0, *, inplace: bool = False
) -> Self | None:
"""
Set the name(s) of the axis.
Parameters
----------
name : str or list of str
Name(s) to set.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to set the label. The value 0 or 'index' specifies index,
and the value 1 or 'columns' specifies columns.
inplace : bool, default False
If `True`, do operation inplace and return None.
Returns
-------
Series, DataFrame, or None
The same type as the caller or `None` if `inplace` is `True`.
See Also
--------
DataFrame.rename : Alter the axis labels of :class:`DataFrame`.
Series.rename : Alter the index labels or set the index name
of :class:`Series`.
Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.
Examples
--------
>>> df = pd.DataFrame({"num_legs": [4, 4, 2]}, ["dog", "cat", "monkey"])
>>> df
num_legs
dog 4
cat 4
monkey 2
>>> df._set_axis_name("animal")
num_legs
animal
dog 4
cat 4
monkey 2
>>> df.index = pd.MultiIndex.from_product(
... [["mammal"], ["dog", "cat", "monkey"]]
... )
>>> df._set_axis_name(["type", "name"])
num_legs
type name
mammal dog 4
cat 4
monkey 2
"""
axis = self._get_axis_number(axis)
idx = self._get_axis(axis).set_names(name)
inplace = validate_bool_kwarg(inplace, "inplace")
renamed = self if inplace else self.copy(deep=False)
if axis == 0:
renamed.index = idx
else:
renamed.columns = idx
if not inplace:
return renamed
return None
# ----------------------------------------------------------------------
# Comparison Methods
@final
def _indexed_same(self, other) -> bool:
return all(
self._get_axis(a).equals(other._get_axis(a)) for a in self._AXIS_ORDERS
)
@final
def equals(self, other: object) -> bool:
"""
Test whether two objects contain the same elements.
This function allows two Series or DataFrames to be compared against
each other to see if they have the same shape and elements. NaNs in
the same location are considered equal.
The row/column index do not need to have the same type, as long
as the values are considered equal. Corresponding columns and
index must be of the same dtype.
Parameters
----------
other : Series or DataFrame
The other Series or DataFrame to be compared with the first.
Returns
-------
bool
True if all elements are the same in both objects, False
otherwise.
See Also
--------
Series.eq : Compare two Series objects of the same length
and return a Series where each element is True if the element
in each Series is equal, False otherwise.
DataFrame.eq : Compare two DataFrame objects of the same shape and
return a DataFrame where each element is True if the respective
element in each DataFrame is equal, False otherwise.
testing.assert_series_equal : Raises an AssertionError if left and
right are not equal. Provides an easy interface to ignore
inequality in dtypes, indexes and precision among others.
testing.assert_frame_equal : Like assert_series_equal, but targets
DataFrames.
numpy.array_equal : Return True if two arrays have the same shape
and elements, False otherwise.
Examples
--------
>>> df = pd.DataFrame({1: [10], 2: [20]})
>>> df
1 2
0 10 20
DataFrames df and exactly_equal have the same types and values for
their elements and column labels, which will return True.
>>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})
>>> exactly_equal
1 2
0 10 20
>>> df.equals(exactly_equal)
True
DataFrames df and different_column_type have the same element
types and values, but have different types for the column labels,
which will still return True.
>>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})
>>> different_column_type
1.0 2.0
0 10 20
>>> df.equals(different_column_type)
True
DataFrames df and different_data_type have different types for the
same values for their elements, and will return False even though
their column labels are the same values and types.
>>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})
>>> different_data_type
1 2
0 10.0 20.0
>>> df.equals(different_data_type)
False
"""
if not (isinstance(other, type(self)) or isinstance(self, type(other))):
return False
other = cast(NDFrame, other)
return self._mgr.equals(other._mgr)
# -------------------------------------------------------------------------
# Unary Methods
@final
def __neg__(self) -> Self:
def blk_func(values: ArrayLike):
if is_bool_dtype(values.dtype):
# error: Argument 1 to "inv" has incompatible type "Union
# [ExtensionArray, ndarray[Any, Any]]"; expected
# "_SupportsInversion[ndarray[Any, dtype[bool_]]]"
return operator.inv(values) # type: ignore[arg-type]
else:
# error: Argument 1 to "neg" has incompatible type "Union
# [ExtensionArray, ndarray[Any, Any]]"; expected
# "_SupportsNeg[ndarray[Any, dtype[Any]]]"
return operator.neg(values) # type: ignore[arg-type]
new_data = self._mgr.apply(blk_func)
res = self._constructor_from_mgr(new_data, axes=new_data.axes)
return res.__finalize__(self, method="__neg__")
@final
def __pos__(self) -> Self:
def blk_func(values: ArrayLike):
if is_bool_dtype(values.dtype):
return values.copy()
else:
# error: Argument 1 to "pos" has incompatible type "Union
# [ExtensionArray, ndarray[Any, Any]]"; expected
# "_SupportsPos[ndarray[Any, dtype[Any]]]"
return operator.pos(values) # type: ignore[arg-type]
new_data = self._mgr.apply(blk_func)
res = self._constructor_from_mgr(new_data, axes=new_data.axes)
return res.__finalize__(self, method="__pos__")
@final
def __invert__(self) -> Self:
if not self.size:
# inv fails with 0 len
return self.copy(deep=False)
new_data = self._mgr.apply(operator.invert)
res = self._constructor_from_mgr(new_data, axes=new_data.axes)
return res.__finalize__(self, method="__invert__")
@final
def __bool__(self) -> NoReturn:
raise ValueError(
f"The truth value of a {type(self).__name__} is ambiguous. "
"Use a.empty, a.bool(), a.item(), a.any() or a.all()."
)
@final
def abs(self) -> Self:
"""
Return a Series/DataFrame with absolute numeric value of each element.
This function only applies to elements that are all numeric.
Returns
-------
abs
Series/DataFrame containing the absolute value of each element.
See Also
--------
numpy.absolute : Calculate the absolute value element-wise.
Notes
-----
For ``complex`` inputs, ``1.2 + 1j``, the absolute value is
:math:`\\sqrt{ a^2 + b^2 }`.
Examples
--------
Absolute numeric values in a Series.
>>> s = pd.Series([-1.10, 2, -3.33, 4])
>>> s.abs()
0 1.10
1 2.00
2 3.33
3 4.00
dtype: float64
Absolute numeric values in a Series with complex numbers.
>>> s = pd.Series([1.2 + 1j])
>>> s.abs()
0 1.56205
dtype: float64
Absolute numeric values in a Series with a Timedelta element.
>>> s = pd.Series([pd.Timedelta("1 days")])
>>> s.abs()
0 1 days
dtype: timedelta64[ns]
Select rows with data closest to certain value using argsort (from
`StackOverflow <https://stackoverflow.com/a/17758115>`__).
>>> df = pd.DataFrame(
... {"a": [4, 5, 6, 7], "b": [10, 20, 30, 40], "c": [100, 50, -30, -50]}
... )
>>> df
a b c
0 4 10 100
1 5 20 50
2 6 30 -30
3 7 40 -50
>>> df.loc[(df.c - 43).abs().argsort()]
a b c
1 5 20 50
0 4 10 100
2 6 30 -30
3 7 40 -50
"""
res_mgr = self._mgr.apply(np.abs)
return self._constructor_from_mgr(res_mgr, axes=res_mgr.axes).__finalize__(
self, name="abs"
)
@final
def __abs__(self) -> Self:
return self.abs()
@final
def __round__(self, decimals: int = 0) -> Self:
return self.round(decimals).__finalize__(self, method="__round__")
# -------------------------------------------------------------------------
# Label or Level Combination Helpers
#
# A collection of helper methods for DataFrame/Series operations that
# accept a combination of column/index labels and levels. All such
# operations should utilize/extend these methods when possible so that we
# have consistent precedence and validation logic throughout the library.
@final
def _is_level_reference(self, key: Level, axis: Axis = 0) -> bool:
"""
Test whether a key is a level reference for a given axis.
To be considered a level reference, `key` must be a string that:
- (axis=0): Matches the name of an index level and does NOT match
a column label.
- (axis=1): Matches the name of a column level and does NOT match
an index label.
Parameters
----------
key : Hashable
Potential level name for the given axis
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
is_level : bool
"""
axis_int = self._get_axis_number(axis)
return (
key is not None
and is_hashable(key)
and key in self.axes[axis_int].names
and not self._is_label_reference(key, axis=axis_int)
)
@final
def _is_label_reference(self, key: Level, axis: Axis = 0) -> bool:
"""
Test whether a key is a label reference for a given axis.
To be considered a label reference, `key` must be a string that:
- (axis=0): Matches a column label
- (axis=1): Matches an index label
Parameters
----------
key : Hashable
Potential label name, i.e. Index entry.
axis : int, default 0
Axis perpendicular to the axis that labels are associated with
(0 means search for column labels, 1 means search for index labels)
Returns
-------
is_label: bool
"""
axis_int = self._get_axis_number(axis)
other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis_int)
return is_hashable(key) and any(key in self.axes[ax] for ax in other_axes)
@final
def _is_label_or_level_reference(self, key: Level, axis: AxisInt = 0) -> bool:
"""
Test whether a key is a label or level reference for a given axis.
To be considered either a label or a level reference, `key` must be a
string that:
- (axis=0): Matches a column label or an index level
- (axis=1): Matches an index label or a column level
Parameters
----------
key : Hashable
Potential label or level name
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
bool
"""
return self._is_level_reference(key, axis=axis) or self._is_label_reference(
key, axis=axis
)
@final
def _check_label_or_level_ambiguity(self, key: Level, axis: Axis = 0) -> None:
"""
Check whether `key` is ambiguous.
By ambiguous, we mean that it matches both a level of the input
`axis` and a label of the other axis.
Parameters
----------
key : Hashable
Label or level name.
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns).
Raises
------
ValueError: `key` is ambiguous
"""
axis_int = self._get_axis_number(axis)
other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis_int)
if (
key is not None
and is_hashable(key)
and key in self.axes[axis_int].names
and any(key in self.axes[ax] for ax in other_axes)
):
# Build an informative and grammatical warning
level_article, level_type = (
("an", "index") if axis_int == 0 else ("a", "column")
)
label_article, label_type = (
("a", "column") if axis_int == 0 else ("an", "index")
)
msg = (
f"'{key}' is both {level_article} {level_type} level and "
f"{label_article} {label_type} label, which is ambiguous."
)
raise ValueError(msg)
@final
def _get_label_or_level_values(self, key: Level, axis: AxisInt = 0) -> ArrayLike:
"""
Return a 1-D array of values associated with `key`, a label or level
from the given `axis`.
Retrieval logic:
- (axis=0): Return column values if `key` matches a column label.
Otherwise return index level values if `key` matches an index
level.
- (axis=1): Return row values if `key` matches an index label.
Otherwise return column level values if 'key' matches a column
level
Parameters
----------
key : Hashable
Label or level name.
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
np.ndarray or ExtensionArray
Raises
------
KeyError
if `key` matches neither a label nor a level
ValueError
if `key` matches multiple labels
"""
axis = self._get_axis_number(axis)
first_other_axes = next(
(ax for ax in range(self._AXIS_LEN) if ax != axis), None
)
if self._is_label_reference(key, axis=axis):
self._check_label_or_level_ambiguity(key, axis=axis)
if first_other_axes is None:
raise ValueError("axis matched all axes")
values = self.xs(key, axis=first_other_axes)._values
elif self._is_level_reference(key, axis=axis):
values = self.axes[axis].get_level_values(key)._values
else:
raise KeyError(key)
# Check for duplicates
if values.ndim > 1:
if first_other_axes is not None and isinstance(
self._get_axis(first_other_axes), MultiIndex
):
multi_message = (
"\n"
"For a multi-index, the label must be a "
"tuple with elements corresponding to each level."
)
else:
multi_message = ""
label_axis_name = "column" if axis == 0 else "index"
raise ValueError(
f"The {label_axis_name} label '{key}' is not unique.{multi_message}"
)
return values
@final
def _drop_labels_or_levels(self, keys, axis: AxisInt = 0):
"""
Drop labels and/or levels for the given `axis`.
For each key in `keys`:
- (axis=0): If key matches a column label then drop the column.
Otherwise if key matches an index level then drop the level.
- (axis=1): If key matches an index label then drop the row.
Otherwise if key matches a column level then drop the level.
Parameters
----------
keys : str or list of str
labels or levels to drop
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
dropped: DataFrame
Raises
------
ValueError
if any `keys` match neither a label nor a level
"""
axis = self._get_axis_number(axis)
# Validate keys
keys = common.maybe_make_list(keys)
invalid_keys = [
k for k in keys if not self._is_label_or_level_reference(k, axis=axis)
]
if invalid_keys:
raise ValueError(
"The following keys are not valid labels or "
f"levels for axis {axis}: {invalid_keys}"
)
# Compute levels and labels to drop
levels_to_drop = [k for k in keys if self._is_level_reference(k, axis=axis)]
labels_to_drop = [k for k in keys if not self._is_level_reference(k, axis=axis)]
# Perform copy upfront and then use inplace operations below.
# This ensures that we always perform exactly one copy.
# ``copy`` and/or ``inplace`` options could be added in the future.
dropped = self.copy(deep=False)
if axis == 0:
# Handle dropping index levels
if levels_to_drop:
dropped.reset_index(levels_to_drop, drop=True, inplace=True)
# Handle dropping columns labels
if labels_to_drop:
dropped.drop(labels_to_drop, axis=1, inplace=True)
else:
# Handle dropping column levels
if levels_to_drop:
if isinstance(dropped.columns, MultiIndex):
# Drop the specified levels from the MultiIndex
dropped.columns = dropped.columns.droplevel(levels_to_drop)
else:
# Drop the last level of Index by replacing with
# a RangeIndex
dropped.columns = default_index(dropped.columns.size)
# Handle dropping index labels
if labels_to_drop:
dropped.drop(labels_to_drop, axis=0, inplace=True)
return dropped
# ----------------------------------------------------------------------
# Iteration
# https://github.com/python/typeshed/issues/2148#issuecomment-520783318
# Incompatible types in assignment (expression has type "None", base class
# "object" defined the type as "Callable[[object], int]")
__hash__: ClassVar[None] # type: ignore[assignment]
def __iter__(self) -> Iterator:
"""
Iterate over info axis.
Returns
-------
iterator
Info axis as iterator.
See Also
--------
DataFrame.items : Iterate over (column name, Series) pairs.
DataFrame.itertuples : Iterate over DataFrame rows as namedtuples.
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> for x in df:
... print(x)
A
B
"""
return iter(self._info_axis)
# can we get a better explanation of this?
def keys(self) -> Index:
"""
Get the 'info axis' (see Indexing for more).
This is index for Series, columns for DataFrame.
Returns
-------
Index
Info axis.
See Also
--------
DataFrame.index : The index (row labels) of the DataFrame.
DataFrame.columns: The column labels of the DataFrame.
Examples
--------
>>> d = pd.DataFrame(
... data={"A": [1, 2, 3], "B": [0, 4, 8]}, index=["a", "b", "c"]
... )
>>> d
A B
a 1 0
b 2 4
c 3 8
>>> d.keys()
Index(['A', 'B'], dtype='str')
"""
return self._info_axis
def items(self):
"""
Iterate over (label, values) on info axis
This is index for Series and columns for DataFrame.
Returns
-------
Generator
"""
for h in self._info_axis:
yield h, self[h]
def __len__(self) -> int:
"""Returns length of info axis"""
return len(self._info_axis)
@final
def __contains__(self, key) -> bool:
"""True if the key is in the info axis"""
return key in self._info_axis
@property
def empty(self) -> bool:
"""
Indicator whether Series/DataFrame is empty.
True if Series/DataFrame is entirely empty (no items), meaning any of the
axes are of length 0.
Returns
-------
bool
If Series/DataFrame is empty, return True, if not return False.
See Also
--------
Series.dropna : Return series without null values.
DataFrame.dropna : Return DataFrame with labels on given axis omitted
where (all or any) data are missing.
Notes
-----
If Series/DataFrame contains only NaNs, it is still not considered empty. See
the example below.
Examples
--------
An example of an actual empty DataFrame. Notice the index is empty:
>>> df_empty = pd.DataFrame({"A": []})
>>> df_empty
Empty DataFrame
Columns: [A]
Index: []
>>> df_empty.empty
True
If we only have NaNs in our DataFrame, it is not considered empty! We
will need to drop the NaNs to make the DataFrame empty:
>>> df = pd.DataFrame({"A": [np.nan]})
>>> df
A
0 NaN
>>> df.empty
False
>>> df.dropna().empty
True
>>> ser_empty = pd.Series({"A": []})
>>> ser_empty
A []
dtype: object
>>> ser_empty.empty
False
>>> ser_empty = pd.Series()
>>> ser_empty.empty
True
"""
return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS)
# ----------------------------------------------------------------------
# Array Interface
# This is also set in IndexOpsMixin
# GH#23114 Ensure ndarray.__op__(DataFrame) returns NotImplemented
__array_priority__: int = 1000
def __array__(
self, dtype: npt.DTypeLike | None = None, copy: bool | None = None
) -> np.ndarray:
if copy is False and not self._mgr.is_single_block and not self.empty:
# check this manually, otherwise ._values will already return a copy
# and np.array(values, copy=False) will not raise an error
raise ValueError(
"Unable to avoid copy while creating an array as requested."
)
values = self._values
if copy is None:
# Note: branch avoids `copy=None` for NumPy 1.x support
arr = np.asarray(values, dtype=dtype)
else:
arr = np.array(values, dtype=dtype, copy=copy)
if (
copy is not True
and astype_is_view(values.dtype, arr.dtype)
and self._mgr.is_single_block
):
# Check if both conversions can be done without a copy
if astype_is_view(self.dtypes.iloc[0], values.dtype) and astype_is_view(
values.dtype, arr.dtype
):
arr = arr.view()
arr.flags.writeable = False
return arr
@final
def __array_ufunc__(
self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any
):
return arraylike.array_ufunc(self, ufunc, method, *inputs, **kwargs)
# ----------------------------------------------------------------------
# Picklability
@final
def __getstate__(self) -> dict[str, Any]:
meta = {k: getattr(self, k, None) for k in self._metadata}
return {
"_mgr": self._mgr,
"_typ": self._typ,
"_metadata": self._metadata,
"attrs": self.attrs,
"_flags": {k: self.flags[k] for k in self.flags._keys},
**meta,
}
@final
def __setstate__(self, state) -> None:
if isinstance(state, BlockManager):
self._mgr = state
elif isinstance(state, dict):
if "_data" in state and "_mgr" not in state:
# compat for older pickles
state["_mgr"] = state.pop("_data")
typ = state.get("_typ")
if typ is not None:
attrs = state.get("_attrs", {})
if attrs is None: # should not happen, but better be on the safe side
attrs = {}
object.__setattr__(self, "_attrs", attrs)
flags = state.get("_flags", {"allows_duplicate_labels": True})
object.__setattr__(self, "_flags", Flags(self, **flags))
# set in the order of internal names
# to avoid definitional recursion
# e.g. say fill_value needing _mgr to be
# defined
meta = set(self._internal_names + self._metadata)
for k in meta:
if k in state and k != "_flags":
v = state[k]
object.__setattr__(self, k, v)
for k, v in state.items():
if k not in meta:
object.__setattr__(self, k, v)
else:
raise NotImplementedError("Pre-0.12 pickles are no longer supported")
elif len(state) == 2:
raise NotImplementedError("Pre-0.12 pickles are no longer supported")
# ----------------------------------------------------------------------
# Rendering Methods
def __repr__(self) -> str:
# string representation based upon iterating over self
# (since, by definition, `PandasContainers` are iterable)
prepr = f"[{','.join(map(pprint_thing, self))}]"
return f"{type(self).__name__}({prepr})"
@final
def _repr_latex_(self):
"""
Returns a LaTeX representation for a particular object.
Mainly for use with nbconvert (jupyter notebook conversion to pdf).
"""
if config.get_option("styler.render.repr") == "latex":
return self.to_latex()
else:
return None
@final
def _repr_data_resource_(self):
"""
Not a real Jupyter special repr method, but we use the same
naming convention.
"""
if config.get_option("display.html.table_schema"):
data = self.head(config.get_option("display.max_rows"))
as_json = data.to_json(orient="table")
as_json = cast(str, as_json)
return loads(as_json, object_pairs_hook=collections.OrderedDict)
# ----------------------------------------------------------------------
# I/O Methods
@final
@doc(
klass="object",
storage_options=_shared_docs["storage_options"],
storage_options_versionadded="1.2.0",
encoding_parameter="",
verbose_parameter="",
extra_parameters=textwrap.dedent(
"""\
engine_kwargs : dict, optional
Arbitrary keyword arguments passed to excel engine.
"""
),
)
def to_excel(
self,
excel_writer: FilePath | WriteExcelBuffer | ExcelWriter,
*,
sheet_name: str = "Sheet1",
na_rep: str = "",
float_format: str | None = None,
columns: Sequence[Hashable] | None = None,
header: Sequence[Hashable] | bool = True,
index: bool = True,
index_label: IndexLabel | None = None,
startrow: int = 0,
startcol: int = 0,
engine: Literal["openpyxl", "xlsxwriter"] | None = None,
merge_cells: bool = True,
inf_rep: str = "inf",
freeze_panes: tuple[int, int] | None = None,
storage_options: StorageOptions | None = None,
engine_kwargs: dict[str, Any] | None = None,
autofilter: bool = False,
) -> None:
"""
Write {klass} to an Excel sheet.
To write a single {klass} to an Excel .xlsx file it is only necessary to
specify a target file name. To write to multiple sheets it is necessary to
create an `ExcelWriter` object with a target file name, and specify a sheet
in the file to write to.
Multiple sheets may be written to by specifying unique `sheet_name`.
With all data written to the file it is necessary to save the changes.
Note that creating an `ExcelWriter` object with a file name that already
exists will result in the contents of the existing file being erased.
Parameters
----------
excel_writer : path-like, file-like, or ExcelWriter object
File path or existing ExcelWriter.
sheet_name : str, default 'Sheet1'
Name of sheet which will contain DataFrame.
na_rep : str, default ''
Missing data representation.
float_format : str, optional
Format string for floating point numbers. For example
``float_format="%.2f"`` will format 0.1234 to 0.12.
columns : sequence or list of str, optional
Columns to write.
header : bool or list of str, default True
Write out the column names. If a list of string is given it is
assumed to be aliases for the column names.
index : bool, default True
Write row names (index).
index_label : str or sequence, optional
Column label for index column(s) if desired. If not specified, and
`header` and `index` are True, then the index names are used. A
sequence should be given if the DataFrame uses MultiIndex.
startrow : int, default 0
Upper left cell row to dump data frame.
startcol : int, default 0
Upper left cell column to dump data frame.
engine : str, optional
Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this
via the options ``io.excel.xlsx.writer`` or
``io.excel.xlsm.writer``.
merge_cells : bool or 'columns', default False
If True, write MultiIndex index and columns as merged cells.
If 'columns', merge MultiIndex column cells only.
{encoding_parameter}
inf_rep : str, default 'inf'
Representation for infinity (there is no native representation for
infinity in Excel).
{verbose_parameter}
freeze_panes : tuple of int (length 2), optional
Specifies the one-based bottommost row and rightmost column that
is to be frozen.
{storage_options}
.. versionadded:: {storage_options_versionadded}
{extra_parameters}
autofilter : bool, default False
If True, add automatic filters to all columns.
See Also
--------
to_csv : Write DataFrame to a comma-separated values (csv) file.
ExcelWriter : Class for writing DataFrame objects into excel sheets.
read_excel : Read an Excel file into a pandas DataFrame.
read_csv : Read a comma-separated values (csv) file into DataFrame.
io.formats.style.Styler.to_excel : Add styles to Excel sheet.
Notes
-----
For compatibility with :meth:`~DataFrame.to_csv`,
to_excel serializes lists and dicts to strings before writing.
Once a workbook has been saved it is not possible to write further
data without rewriting the whole workbook.
pandas will check the number of rows, columns,
and cell character count does not exceed Excel's limitations.
All other limitations must be checked by the user.
Examples
--------
Create, write to and save a workbook:
>>> df1 = pd.DataFrame(
... [["a", "b"], ["c", "d"]],
... index=["row 1", "row 2"],
... columns=["col 1", "col 2"],
... )
>>> df1.to_excel("output.xlsx") # doctest: +SKIP
To specify the sheet name:
>>> df1.to_excel("output.xlsx", sheet_name="Sheet_name_1") # doctest: +SKIP
If you wish to write to more than one sheet in the workbook, it is
necessary to specify an ExcelWriter object:
>>> df2 = df1.copy()
>>> with pd.ExcelWriter("output.xlsx") as writer: # doctest: +SKIP
... df1.to_excel(writer, sheet_name="Sheet_name_1")
... df2.to_excel(writer, sheet_name="Sheet_name_2")
ExcelWriter can also be used to append to an existing Excel file:
>>> with pd.ExcelWriter("output.xlsx", mode="a") as writer: # doctest: +SKIP
... df1.to_excel(writer, sheet_name="Sheet_name_3")
To set the library that is used to write the Excel file,
you can pass the `engine` keyword (the default engine is
automatically chosen depending on the file extension):
>>> df1.to_excel("output1.xlsx", engine="xlsxwriter") # doctest: +SKIP
"""
if engine_kwargs is None:
engine_kwargs = {}
df = self if isinstance(self, ABCDataFrame) else self.to_frame()
from pandas.io.formats.excel import ExcelFormatter
formatter = ExcelFormatter(
df,
na_rep=na_rep,
cols=columns,
header=header,
float_format=float_format,
index=index,
index_label=index_label,
merge_cells=merge_cells,
inf_rep=inf_rep,
autofilter=autofilter,
)
formatter.write(
excel_writer,
sheet_name=sheet_name,
startrow=startrow,
startcol=startcol,
freeze_panes=freeze_panes,
engine=engine,
storage_options=storage_options,
engine_kwargs=engine_kwargs,
)
@final
@doc(
storage_options=_shared_docs["storage_options"],
compression_options=_shared_docs["compression_options"] % "path_or_buf",
)
def to_json(
self,
path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,
*,
orient: Literal["split", "records", "index", "table", "columns", "values"]
| None = None,
date_format: str | None = None,
double_precision: int = 10,
force_ascii: bool = True,
date_unit: TimeUnit = "ms",
default_handler: Callable[[Any], JSONSerializable] | None = None,
lines: bool = False,
compression: CompressionOptions = "infer",
index: bool | None = None,
indent: int | None = None,
storage_options: StorageOptions | None = None,
mode: Literal["a", "w"] = "w",
) -> str | None:
"""
Convert the object to a JSON string.
Note NaN's and None will be converted to null and datetime objects
will be converted to UNIX timestamps.
Parameters
----------
path_or_buf : str, path object, file-like object, or None, default None
String, path object (implementing os.PathLike[str]), or file-like
object implementing a write() function. If None, the result is
returned as a string.
orient : str
Indication of expected JSON string format.
* Series:
- default is 'index'
- allowed values are: {{'split', 'records', 'index', 'table'}}.
* DataFrame:
- default is 'columns'
- allowed values are: {{'split', 'records', 'index', 'columns',
'values', 'table'}}.
* The format of the JSON string:
- 'split' : dict like {{'index' -> [index], 'columns' -> [columns],
'data' -> [values]}}
- 'records' : list like [{{column -> value}}, ... , {{column -> value}}]
- 'index' : dict like {{index -> {{column -> value}}}}
- 'columns' : dict like {{column -> {{index -> value}}}}
- 'values' : just the values array
- 'table' : dict like {{'schema': {{schema}}, 'data': {{data}}}}
Describing the data, where data component is like ``orient='records'``.
date_format : {{None, 'epoch', 'iso'}}
Type of date conversion. 'epoch' = epoch milliseconds,
'iso' = ISO8601. The default depends on the `orient`. For
``orient='table'``, the default is 'iso'. For all other orients,
the default is 'epoch'.
.. deprecated:: 3.0.0
'epoch' date format is deprecated and will be removed in a future
version, please use 'iso' instead.
double_precision : int, default 10
The number of decimal places to use when encoding
floating point values. The possible maximal value is 15.
Passing double_precision greater than 15 will raise a ValueError.
force_ascii : bool, default True
Force encoded string to be ASCII.
date_unit : str, default 'ms' (milliseconds)
The time unit to encode to, governs timestamp and ISO8601
precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,
microsecond, and nanosecond respectively.
default_handler : callable, default None
Handler to call if object cannot otherwise be converted to a
suitable format for JSON. Should receive a single argument which is
the object to convert and return a serialisable object.
lines : bool, default False
If 'orient' is 'records' write out line-delimited json format. Will
throw ValueError if incorrect 'orient' since others are not
list-like.
{compression_options}
index : bool or None, default None
The index is only used when 'orient' is 'split', 'index', 'column',
or 'table'. Of these, 'index' and 'column' do not support
`index=False`. The string 'index' as a column name with empty :class:`Index`
or if it is 'index' will raise a ``ValueError``.
indent : int, optional
Length of whitespace used to indent each record.
{storage_options}
mode : str, default 'w' (writing)
Specify the IO mode for output when supplying a path_or_buf.
Accepted args are 'w' (writing) and 'a' (append) only.
mode='a' is only supported when lines is True and orient is 'records'.
Returns
-------
None or str
If path_or_buf is None, returns the resulting json format as a
string. Otherwise returns None.
See Also
--------
read_json : Convert a JSON string to pandas object.
Notes
-----
The behavior of ``indent=0`` varies from the stdlib, which does not
indent the output but does insert newlines. Currently, ``indent=0``
and the default ``indent=None`` are equivalent in pandas, though this
may change in a future release.
``orient='table'`` contains a 'pandas_version' field under 'schema'.
This stores the version of `pandas` used in the latest revision of the
schema.
Examples
--------
>>> from json import loads, dumps
>>> df = pd.DataFrame(
... [["a", "b"], ["c", "d"]],
... index=["row 1", "row 2"],
... columns=["col 1", "col 2"],
... )
>>> result = df.to_json(orient="split")
>>> parsed = loads(result)
>>> dumps(parsed, indent=4) # doctest: +SKIP
{{
"columns": [
"col 1",
"col 2"
],
"index": [
"row 1",
"row 2"
],
"data": [
[
"a",
"b"
],
[
"c",
"d"
]
]
}}
Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
Note that index labels are not preserved with this encoding.
>>> result = df.to_json(orient="records")
>>> parsed = loads(result)
>>> dumps(parsed, indent=4) # doctest: +SKIP
[
{{
"col 1": "a",
"col 2": "b"
}},
{{
"col 1": "c",
"col 2": "d"
}}
]
Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
>>> result = df.to_json(orient="index")
>>> parsed = loads(result)
>>> dumps(parsed, indent=4) # doctest: +SKIP
{{
"row 1": {{
"col 1": "a",
"col 2": "b"
}},
"row 2": {{
"col 1": "c",
"col 2": "d"
}}
}}
Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:
>>> result = df.to_json(orient="columns")
>>> parsed = loads(result)
>>> dumps(parsed, indent=4) # doctest: +SKIP
{{
"col 1": {{
"row 1": "a",
"row 2": "c"
}},
"col 2": {{
"row 1": "b",
"row 2": "d"
}}
}}
Encoding/decoding a Dataframe using ``'values'`` formatted JSON:
>>> result = df.to_json(orient="values")
>>> parsed = loads(result)
>>> dumps(parsed, indent=4) # doctest: +SKIP
[
[
"a",
"b"
],
[
"c",
"d"
]
]
Encoding with Table Schema:
>>> result = df.to_json(orient="table")
>>> parsed = loads(result)
>>> dumps(parsed, indent=4) # doctest: +SKIP
{{
"schema": {{
"fields": [
{{
"name": "index",
"type": "string"
}},
{{
"name": "col 1",
"type": "string"
}},
{{
"name": "col 2",
"type": "string"
}}
],
"primaryKey": [
"index"
],
"pandas_version": "1.4.0"
}},
"data": [
{{
"index": "row 1",
"col 1": "a",
"col 2": "b"
}},
{{
"index": "row 2",
"col 1": "c",
"col 2": "d"
}}
]
}}
"""
from pandas.io import json
if date_format is None and orient == "table":
date_format = "iso"
elif date_format is None:
date_format = "epoch"
dtypes = self.dtypes if self.ndim == 2 else [self.dtype]
if any(lib.is_np_dtype(dtype, "mM") for dtype in dtypes):
warnings.warn(
"The default 'epoch' date format is deprecated and will be removed "
"in a future version, please use 'iso' date format instead.",
Pandas4Warning,
stacklevel=find_stack_level(),
)
elif date_format == "epoch":
# GH#57063
warnings.warn(
"'epoch' date format is deprecated and will be removed in a future "
"version, please use 'iso' date format instead.",
Pandas4Warning,
stacklevel=find_stack_level(),
)
config.is_nonnegative_int(indent)
indent = indent or 0
return json.to_json(
path_or_buf=path_or_buf,
obj=self,
orient=orient,
date_format=date_format,
double_precision=double_precision,
force_ascii=force_ascii,
date_unit=date_unit,
default_handler=default_handler,
lines=lines,
compression=compression,
index=index,
indent=indent,
storage_options=storage_options,
mode=mode,
)
@final
def to_hdf(
self,
path_or_buf: FilePath | HDFStore,
*,
key: str,
mode: Literal["a", "w", "r+"] = "a",
complevel: int | None = None,
complib: Literal["zlib", "lzo", "bzip2", "blosc"] | None = None,
append: bool = False,
format: Literal["fixed", "table"] | None = None,
index: bool = True,
min_itemsize: int | dict[str, int] | None = None,
nan_rep=None,
dropna: bool | None = None,
data_columns: Literal[True] | list[str] | None = None,
errors: OpenFileErrors = "strict",
encoding: str = "UTF-8",
) -> None:
"""
Write the contained data to an HDF5 file using HDFStore.
Hierarchical Data Format (HDF) is self-describing, allowing an
application to interpret the structure and contents of a file with
no outside information. One HDF file can hold a mix of related objects
which can be accessed as a group or as individual objects.
In order to add another DataFrame or Series to an existing HDF file
please use append mode and a different a key.
.. warning::
One can store a subclass of ``DataFrame`` or ``Series`` to HDF5,
but the type of the subclass is lost upon storing.
For more information see the :ref:`user guide <io.hdf5>`.
Parameters
----------
path_or_buf : str or pandas.HDFStore
File path or HDFStore object.
key : str
Identifier for the group in the store.
mode : {'a', 'w', 'r+'}, default 'a'
Mode to open file:
- 'w': write, a new file is created (an existing file with
the same name would be deleted).
- 'a': append, an existing file is opened for reading and
writing, and if the file does not exist it is created.
- 'r+': similar to 'a', but the file must already exist.
complevel : {0-9}, default None
Specifies a compression level for data.
A value of 0 or None disables compression.
complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
Specifies the compression library to be used.
These additional compressors for Blosc are supported
(default if no compressor specified: 'blosc:blosclz'):
{'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
'blosc:zlib', 'blosc:zstd'}.
Specifying a compression library which is not available issues
a ValueError.
append : bool, default False
For Table formats, append the input data to the existing.
format : {'fixed', 'table', None}, default 'fixed'
Possible values:
- 'fixed': Fixed format. Fast writing/reading. Not-appendable,
nor searchable.
- 'table': Table format. Write as a PyTables Table structure
which may perform worse but allow more flexible operations
like searching / selecting subsets of the data.
- If None, pd.get_option('io.hdf.default_format') is checked,
followed by fallback to "fixed".
index : bool, default True
Write DataFrame index as a column.
min_itemsize : dict or int, optional
Map column names to minimum string sizes for columns.
nan_rep : Any, optional
How to represent null values as str.
Not allowed with append=True.
dropna : bool, default False, optional
Remove missing values.
data_columns : list of columns or True, optional
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See
:ref:`Query via data columns<io.hdf5-query-data-columns>`. for
more information.
Applicable only to format='table'.
errors : str, default 'strict'
Specifies how encoding and decoding errors are to be handled.
See the errors argument for :func:`open` for a full list
of options.
encoding : str, default "UTF-8"
Set character encoding.
See Also
--------
read_hdf : Read from HDF file.
DataFrame.to_orc : Write a DataFrame to the binary orc format.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
DataFrame.to_sql : Write to a SQL table.
DataFrame.to_feather : Write out feather-format for DataFrames.
DataFrame.to_csv : Write out to a csv file.
Examples
--------
>>> df = pd.DataFrame(
... {"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "c"]
... ) # doctest: +SKIP
>>> df.to_hdf("data.h5", key="df", mode="w") # doctest: +SKIP
We can add another object to the same file:
>>> s = pd.Series([1, 2, 3, 4]) # doctest: +SKIP
>>> s.to_hdf("data.h5", key="s") # doctest: +SKIP
Reading from HDF file:
>>> pd.read_hdf("data.h5", "df") # doctest: +SKIP
A B
a 1 4
b 2 5
c 3 6
>>> pd.read_hdf("data.h5", "s") # doctest: +SKIP
0 1
1 2
2 3
3 4
dtype: int64
"""
from pandas.io import pytables
# Argument 3 to "to_hdf" has incompatible type "NDFrame"; expected
# "Union[DataFrame, Series]" [arg-type]
pytables.to_hdf(
path_or_buf,
key,
self, # type: ignore[arg-type]
mode=mode,
complevel=complevel,
complib=complib,
append=append,
format=format,
index=index,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
dropna=dropna,
data_columns=data_columns,
errors=errors,
encoding=encoding,
)
@final
def to_sql(
self,
name: str,
con,
*,
schema: str | None = None,
if_exists: Literal["fail", "replace", "append", "delete_rows"] = "fail",
index: bool = True,
index_label: IndexLabel | None = None,
chunksize: int | None = None,
dtype: DtypeArg | None = None,
method: Literal["multi"] | Callable | None = None,
) -> int | None:
"""
Write records stored in a DataFrame to a SQL database.
Databases supported by SQLAlchemy [1]_ are supported. Tables can be
newly created, appended to, or overwritten.
.. warning::
The pandas library does not attempt to sanitize inputs provided via a to_sql call.
Please refer to the documentation for the underlying database driver to see if it
will properly prevent injection, or alternatively be advised of a security risk when
executing arbitrary commands in a to_sql call.
Parameters
----------
name : str
Name of SQL table.
con : ADBC connection, sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
ADBC provides high performance I/O with native type support, where available.
Using SQLAlchemy makes it possible to use any DB supported by that
library. Legacy support is provided for sqlite3.Connection objects. The user
is responsible for engine disposal and connection closure for the SQLAlchemy
connectable. See `here \
<https://docs.sqlalchemy.org/en/20/core/connections.html>`_.
If passing a sqlalchemy.engine.Connection which is already in a transaction,
the transaction will not be committed. If passing a sqlite3.Connection,
it will not be possible to roll back the record insertion.
schema : str, optional
Specify the schema (if database flavor supports this). If None, use
default schema.
if_exists : {'fail', 'replace', 'append', 'delete_rows'}, default 'fail'
How to behave if the table already exists.
* fail: Raise a ValueError.
* replace: Drop the table before inserting new values.
* append: Insert new values to the existing table.
* delete_rows: If a table exists, delete all records and insert data.
index : bool, default True
Write DataFrame index as a column. Uses `index_label` as the column
name in the table. Creates a table index for this column.
index_label : str or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
chunksize : int, optional
Specify the number of rows in each batch to be written to the database connection at a time.
By default, all rows will be written at once. Also see the method keyword.
dtype : dict or scalar, optional
Specifying the datatype for columns. If a dictionary is used, the
keys should be the column names and the values should be the
SQLAlchemy types or strings for the sqlite3 legacy mode. If a
scalar is provided, it will be applied to all columns.
method : {None, 'multi', callable}, optional
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
Returns
-------
None or int
Number of rows affected by to_sql. None is returned if the callable
passed into ``method`` does not return an integer number of rows.
The number of returned rows affected is the sum of the ``rowcount``
attribute of ``sqlite3.Cursor`` or SQLAlchemy connectable which may not
reflect the exact number of written rows as stipulated in the
`sqlite3 <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.rowcount>`__ or
`SQLAlchemy <https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.CursorResult.rowcount>`__.
Raises
------
ValueError
When the table already exists and `if_exists` is 'fail' (the
default).
See Also
--------
read_sql : Read a DataFrame from a table.
Notes
-----
Timezone aware datetime columns will be written as
``Timestamp with timezone`` type with SQLAlchemy if supported by the
database. Otherwise, the datetimes will be stored as timezone unaware
timestamps local to the original timezone.
Not all datastores support ``method="multi"``. Oracle, for example,
does not support multi-value insert.
References
----------
.. [1] https://docs.sqlalchemy.org
.. [2] https://www.python.org/dev/peps/pep-0249/
Examples
--------
Create an in-memory SQLite database.
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite://', echo=False)
Create a table from scratch with 3 rows.
>>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
>>> df
name
0 User 1
1 User 2
2 User 3
>>> df.to_sql(name='users', con=engine)
3
>>> from sqlalchemy import text
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM users")).fetchall()
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]
An `sqlalchemy.engine.Connection` can also be passed to `con`:
>>> with engine.begin() as connection:
... df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
... df1.to_sql(name='users', con=connection, if_exists='append')
2
This is allowed to support operations that require that the same
DBAPI connection is used for the entire operation.
>>> df2 = pd.DataFrame({'name' : ['User 6', 'User 7']})
>>> df2.to_sql(name='users', con=engine, if_exists='append')
2
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM users")).fetchall()
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
(0, 'User 4'), (1, 'User 5'), (0, 'User 6'),
(1, 'User 7')]
Overwrite the table with just ``df2``.
>>> df2.to_sql(name='users', con=engine, if_exists='replace',
... index_label='id')
2
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM users")).fetchall()
[(0, 'User 6'), (1, 'User 7')]
Delete all rows before inserting new records with ``df3``
>>> df3 = pd.DataFrame({"name": ['User 8', 'User 9']})
>>> df3.to_sql(name='users', con=engine, if_exists='delete_rows',
... index_label='id')
2
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM users")).fetchall()
[(0, 'User 8'), (1, 'User 9')]
Use ``method`` to define a callable insertion method to do nothing
if there's a primary key conflict on a table in a PostgreSQL database.
>>> from sqlalchemy.dialects.postgresql import insert
>>> def insert_on_conflict_nothing(table, conn, keys, data_iter):
... # "a" is the primary key in "conflict_table"
... data = [dict(zip(keys, row)) for row in data_iter]
... stmt = insert(table.table).values(data).on_conflict_do_nothing(index_elements=["a"])
... result = conn.execute(stmt)
... return result.rowcount
>>> df_conflict.to_sql(name="conflict_table", con=conn, if_exists="append", # noqa: F821
... method=insert_on_conflict_nothing) # doctest: +SKIP
0
For MySQL, a callable to update columns ``b`` and ``c`` if there's a conflict
on a primary key.
>>> from sqlalchemy.dialects.mysql import insert # noqa: F811
>>> def insert_on_conflict_update(table, conn, keys, data_iter):
... # update columns "b" and "c" on primary key conflict
... data = [dict(zip(keys, row)) for row in data_iter]
... stmt = (
... insert(table.table)
... .values(data)
... )
... stmt = stmt.on_duplicate_key_update(b=stmt.inserted.b, c=stmt.inserted.c)
... result = conn.execute(stmt)
... return result.rowcount
>>> df_conflict.to_sql(name="conflict_table", con=conn, if_exists="append", # noqa: F821
... method=insert_on_conflict_update) # doctest: +SKIP
2
Specify the dtype (especially useful for integers with missing values).
Notice that while pandas is forced to store the data as floating point,
the database supports nullable integers. When fetching the data with
Python, we get back integer scalars.
>>> df = pd.DataFrame({"A": [1, None, 2]})
>>> df
A
0 1.0
1 NaN
2 2.0
>>> from sqlalchemy.types import Integer
>>> df.to_sql(name='integers', con=engine, index=False,
... dtype={"A": Integer()})
3
>>> with engine.connect() as conn:
... conn.execute(text("SELECT * FROM integers")).fetchall()
[(1,), (None,), (2,)]
.. versionadded:: 2.2.0
pandas now supports writing via ADBC drivers
>>> df = pd.DataFrame({'name' : ['User 10', 'User 11', 'User 12']})
>>> df
name
0 User 10
1 User 11
2 User 12
>>> from adbc_driver_sqlite import dbapi # doctest:+SKIP
>>> with dbapi.connect("sqlite://") as conn: # doctest:+SKIP
... df.to_sql(name="users", con=conn)
3
""" # noqa: E501
from pandas.io import sql
return sql.to_sql(
self,
name,
con,
schema=schema,
if_exists=if_exists,
index=index,
index_label=index_label,
chunksize=chunksize,
dtype=dtype,
method=method,
)
@final
@doc(
storage_options=_shared_docs["storage_options"],
compression_options=_shared_docs["compression_options"] % "path",
)
def to_pickle(
self,
path: FilePath | WriteBuffer[bytes],
*,
compression: CompressionOptions = "infer",
protocol: int = pickle.HIGHEST_PROTOCOL,
storage_options: StorageOptions | None = None,
) -> None:
"""
Pickle (serialize) object to file.
Parameters
----------
path : str, path object, or file-like object
String, path object (implementing ``os.PathLike[str]``), or file-like
object implementing a binary ``write()`` function. File path where
the pickled object will be stored.
{compression_options}
protocol : int
Int which indicates which protocol should be used by the pickler,
default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
values are 0, 1, 2, 3, 4, 5. A negative value for the protocol
parameter is equivalent to setting its value to HIGHEST_PROTOCOL.
.. [1] https://docs.python.org/3/library/pickle.html.
{storage_options}
See Also
--------
read_pickle : Load pickled pandas object (or any object) from file.
DataFrame.to_hdf : Write DataFrame to an HDF5 file.
DataFrame.to_sql : Write DataFrame to a SQL database.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
Examples
--------
>>> original_df = pd.DataFrame(
... {{"foo": range(5), "bar": range(5, 10)}}
... ) # doctest: +SKIP
>>> original_df # doctest: +SKIP
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> original_df.to_pickle("./dummy.pkl") # doctest: +SKIP
>>> unpickled_df = pd.read_pickle("./dummy.pkl") # doctest: +SKIP
>>> unpickled_df # doctest: +SKIP
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
"""
from pandas.io.pickle import to_pickle
to_pickle(
self,
path,
compression=compression,
protocol=protocol,
storage_options=storage_options,
)
@final
def to_clipboard(
self, *, excel: bool = True, sep: str | None = None, **kwargs
) -> None:
r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
Produce output in a csv format for easy pasting into excel.
- True, use the provided separator for csv pasting.
- False, write a string representation of the object to the clipboard.
sep : str, default ``'\t'``
Field delimiter.
**kwargs
These parameters will be passed to DataFrame.to_csv.
See Also
--------
DataFrame.to_csv : Write a DataFrame to a comma-separated values
(csv) file.
read_clipboard : Read text from clipboard and pass to read_csv.
Notes
-----
Requirements for your platform.
- Linux : `xclip`, or `xsel` (with `PyQt4` modules)
- Windows : none
- macOS : none
This method uses the processes developed for the package `pyperclip`. A
solution to render any output string format is given in the examples.
Examples
--------
Copy the contents of a DataFrame to the clipboard.
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"])
>>> df.to_clipboard(sep=",") # doctest: +SKIP
... # Wrote the following to the system clipboard:
... # ,A,B,C
... # 0,1,2,3
... # 1,4,5,6
We can omit the index by passing the keyword `index` and setting
it to false.
>>> df.to_clipboard(sep=",", index=False) # doctest: +SKIP
... # Wrote the following to the system clipboard:
... # A,B,C
... # 1,2,3
... # 4,5,6
Using the original `pyperclip` package for any string output format.
.. code-block:: python
import pyperclip
html = df.style.to_html()
pyperclip.copy(html)
"""
from pandas.io import clipboards
clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)
@final
def to_xarray(self):
"""
Return an xarray object from the pandas object.
Returns
-------
xarray.DataArray or xarray.Dataset
Data in the pandas structure converted to Dataset if the object is
a DataFrame, or a DataArray if the object is a Series.
See Also
--------
DataFrame.to_hdf : Write DataFrame to an HDF5 file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
Notes
-----
See the `xarray docs <https://xarray.pydata.org/en/stable/>`__
Examples
--------
>>> df = pd.DataFrame(
... [
... ("falcon", "bird", 389.0, 2),
... ("parrot", "bird", 24.0, 2),
... ("lion", "mammal", 80.5, 4),
... ("monkey", "mammal", np.nan, 4),
... ],
... columns=["name", "class", "max_speed", "num_legs"],
... )
>>> df
name class max_speed num_legs
0 falcon bird 389.0 2
1 parrot bird 24.0 2
2 lion mammal 80.5 4
3 monkey mammal NaN 4
>>> df.to_xarray() # doctest: +SKIP
<xarray.Dataset>
Dimensions: (index: 4)
Coordinates:
* index (index) int64 32B 0 1 2 3
Data variables:
name (index) object 32B 'falcon' 'parrot' 'lion' 'monkey'
class (index) object 32B 'bird' 'bird' 'mammal' 'mammal'
max_speed (index) float64 32B 389.0 24.0 80.5 nan
num_legs (index) int64 32B 2 2 4 4
>>> df["max_speed"].to_xarray() # doctest: +SKIP
<xarray.DataArray 'max_speed' (index: 4)>
array([389. , 24. , 80.5, nan])
Coordinates:
* index (index) int64 0 1 2 3
>>> dates = pd.to_datetime(
... ["2018-01-01", "2018-01-01", "2018-01-02", "2018-01-02"]
... )
>>> df_multiindex = pd.DataFrame(
... {
... "date": dates,
... "animal": ["falcon", "parrot", "falcon", "parrot"],
... "speed": [350, 18, 361, 15],
... }
... )
>>> df_multiindex = df_multiindex.set_index(["date", "animal"])
>>> df_multiindex
speed
date animal
2018-01-01 falcon 350
parrot 18
2018-01-02 falcon 361
parrot 15
>>> df_multiindex.to_xarray() # doctest: +SKIP
<xarray.Dataset>
Dimensions: (date: 2, animal: 2)
Coordinates:
* date (date) datetime64[s] 2018-01-01 2018-01-02
* animal (animal) object 'falcon' 'parrot'
Data variables:
speed (date, animal) int64 350 18 361 15
"""
xarray = import_optional_dependency("xarray")
if self.ndim == 1:
return xarray.DataArray.from_series(self)
else:
return xarray.Dataset.from_dataframe(self)
@overload
def to_latex(
self,
buf: None = ...,
*,
columns: Sequence[Hashable] | None = ...,
header: bool | SequenceNotStr[str] = ...,
index: bool = ...,
na_rep: str = ...,
formatters: FormattersType | None = ...,
float_format: FloatFormatType | None = ...,
sparsify: bool | None = ...,
index_names: bool = ...,
bold_rows: bool = ...,
column_format: str | None = ...,
longtable: bool | None = ...,
escape: bool | None = ...,
encoding: str | None = ...,
decimal: str = ...,
multicolumn: bool | None = ...,
multicolumn_format: str | None = ...,
multirow: bool | None = ...,
caption: str | tuple[str, str] | None = ...,
label: str | None = ...,
position: str | None = ...,
) -> str: ...
@overload
def to_latex(
self,
buf: FilePath | WriteBuffer[str],
*,
columns: Sequence[Hashable] | None = ...,
header: bool | SequenceNotStr[str] = ...,
index: bool = ...,
na_rep: str = ...,
formatters: FormattersType | None = ...,
float_format: FloatFormatType | None = ...,
sparsify: bool | None = ...,
index_names: bool = ...,
bold_rows: bool = ...,
column_format: str | None = ...,
longtable: bool | None = ...,
escape: bool | None = ...,
encoding: str | None = ...,
decimal: str = ...,
multicolumn: bool | None = ...,
multicolumn_format: str | None = ...,
multirow: bool | None = ...,
caption: str | tuple[str, str] | None = ...,
label: str | None = ...,
position: str | None = ...,
) -> None: ...
@final
def to_latex(
self,
buf: FilePath | WriteBuffer[str] | None = None,
*,
columns: Sequence[Hashable] | None = None,
header: bool | SequenceNotStr[str] = True,
index: bool = True,
na_rep: str = "NaN",
formatters: FormattersType | None = None,
float_format: FloatFormatType | None = None,
sparsify: bool | None = None,
index_names: bool = True,
bold_rows: bool = False,
column_format: str | None = None,
longtable: bool | None = None,
escape: bool | None = None,
encoding: str | None = None,
decimal: str = ".",
multicolumn: bool | None = None,
multicolumn_format: str | None = None,
multirow: bool | None = None,
caption: str | tuple[str, str] | None = None,
label: str | None = None,
position: str | None = None,
) -> str | None:
r"""
Render object to a LaTeX tabular, longtable, or nested table.
Requires ``\usepackage{booktabs}``. The output can be copy/pasted
into a main LaTeX document or read from an external file
with ``\input{table.tex}``.
.. versionchanged:: 2.0.0
Refactored to use the Styler implementation via jinja2 templating.
Parameters
----------
buf : str, Path or StringIO-like, optional, default None
Buffer to write to. If None, the output is returned as a string.
columns : list of label, optional
The subset of columns to write. Writes all columns by default.
header : bool or list of str, default True
Write out the column names. If a list of strings is given,
it is assumed to be aliases for the column names. Braces must be escaped.
index : bool, default True
Write row names (index).
na_rep : str, default 'NaN'
Missing data representation.
formatters : list of functions or dict of {str: function}, optional
Formatter functions to apply to columns' elements by position or
name. The result of each function must be a unicode string.
List must be of length equal to the number of columns.
float_format : one-parameter function or str, optional, default None
Formatter for floating point numbers. For example
``float_format="%.2f"`` and ``float_format="{:0.2f}".format`` will
both result in 0.1234 being formatted as 0.12.
sparsify : bool, optional
Set to False for a DataFrame with a hierarchical index to print
every multiindex key at each row. By default, the value will be
read from the config module.
index_names : bool, default True
Prints the names of the indexes.
bold_rows : bool, default False
Make the row labels bold in the output.
column_format : str, optional
The columns format as specified in `LaTeX table format
<https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3
columns. By default, 'l' will be used for all columns except
columns of numbers, which default to 'r'.
longtable : bool, optional
Use a longtable environment instead of tabular. Requires
adding a \usepackage{longtable} to your LaTeX preamble.
By default, the value will be read from the pandas config
module, and set to `True` if the option ``styler.latex.environment`` is
`"longtable"`.
.. versionchanged:: 2.0.0
The pandas option affecting this argument has changed.
escape : bool, optional
By default, the value will be read from the pandas config
module and set to `True` if the option ``styler.format.escape`` is
`"latex"`. When set to False prevents from escaping latex special
characters in column names.
.. versionchanged:: 2.0.0
The pandas option affecting this argument has changed, as has the
default value to `False`.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'utf-8'.
decimal : str, default '.'
Character recognized as decimal separator, e.g. ',' in Europe.
multicolumn : bool, default True
Use \multicolumn to enhance MultiIndex columns.
The default will be read from the config module, and is set
as the option ``styler.sparse.columns``.
.. versionchanged:: 2.0.0
The pandas option affecting this argument has changed.
multicolumn_format : str, default 'r'
The alignment for multicolumns, similar to `column_format`
The default will be read from the config module, and is set as the option
``styler.latex.multicol_align``.
.. versionchanged:: 2.0.0
The pandas option affecting this argument has changed, as has the
default value to "r".
multirow : bool, default True
Use \multirow to enhance MultiIndex rows. Requires adding a
\usepackage{multirow} to your LaTeX preamble. Will print
centered labels (instead of top-aligned) across the contained
rows, separating groups via clines. The default will be read
from the pandas config module, and is set as the option
``styler.sparse.index``.
.. versionchanged:: 2.0.0
The pandas option affecting this argument has changed, as has the
default value to `True`.
caption : str or tuple, optional
Tuple (full_caption, short_caption),
which results in ``\caption[short_caption]{full_caption}``;
if a single string is passed, no short caption will be set.
label : str, optional
The LaTeX label to be placed inside ``\label{}`` in the output.
This is used with ``\ref{}`` in the main ``.tex`` file.
position : str, optional
The LaTeX positional argument for tables, to be placed after
``\begin{}`` in the output.
Returns
-------
str or None
If buf is None, returns the result as a string. Otherwise returns None.
See Also
--------
io.formats.style.Styler.to_latex : Render a DataFrame to LaTeX
with conditional formatting.
DataFrame.to_string : Render a DataFrame to a console-friendly
tabular output.
DataFrame.to_html : Render a DataFrame as an HTML table.
Notes
-----
As of v2.0.0 this method has changed to use the Styler implementation as
part of :meth:`.Styler.to_latex` via ``jinja2`` templating. This means
that ``jinja2`` is a requirement, and needs to be installed, for this method
to function. It is advised that users switch to using Styler, since that
implementation is more frequently updated and contains much more
flexibility with the output.
Examples
--------
Convert a general DataFrame to LaTeX with formatting:
>>> df = pd.DataFrame(dict(name=['Raphael', 'Donatello'],
... age=[26, 45],
... height=[181.23, 177.65]))
>>> print(df.to_latex(index=False,
... formatters={"name": str.upper},
... float_format="{:.1f}".format,
... )) # doctest: +SKIP
\begin{tabular}{lrr}
\toprule
name & age & height \\
\midrule
RAPHAEL & 26 & 181.2 \\
DONATELLO & 45 & 177.7 \\
\bottomrule
\end{tabular}
"""
# Get defaults from the pandas config
if self.ndim == 1:
self = self.to_frame()
if longtable is None:
longtable = config.get_option("styler.latex.environment") == "longtable"
if escape is None:
escape = config.get_option("styler.format.escape") == "latex"
if multicolumn is None:
multicolumn = config.get_option("styler.sparse.columns")
if multicolumn_format is None:
multicolumn_format = config.get_option("styler.latex.multicol_align")
if multirow is None:
multirow = config.get_option("styler.sparse.index")
if column_format is not None and not isinstance(column_format, str):
raise ValueError("`column_format` must be str or unicode")
length = len(self.columns) if columns is None else len(columns)
if isinstance(header, (list, tuple)) and len(header) != length:
raise ValueError(f"Writing {length} cols but got {len(header)} aliases")
# Refactor formatters/float_format/decimal/na_rep/escape to Styler structure
base_format_ = {
"na_rep": na_rep,
"escape": "latex" if escape else None,
"decimal": decimal,
}
index_format_: dict[str, Any] = {"axis": 0, **base_format_}
column_format_: dict[str, Any] = {"axis": 1, **base_format_}
if isinstance(float_format, str):
float_format_: Callable | None = lambda x: float_format % x
else:
float_format_ = float_format
def _wrap(x, alt_format_):
if isinstance(x, (float, complex)) and float_format_ is not None:
return float_format_(x)
else:
return alt_format_(x)
formatters_: list | tuple | dict | Callable | None = None
if isinstance(formatters, list):
formatters_ = {
c: partial(_wrap, alt_format_=formatters[i])
for i, c in enumerate(self.columns)
}
elif isinstance(formatters, dict):
index_formatter = formatters.pop("__index__", None)
column_formatter = formatters.pop("__columns__", None)
if index_formatter is not None:
index_format_.update({"formatter": index_formatter})
if column_formatter is not None:
column_format_.update({"formatter": column_formatter})
formatters_ = formatters
float_columns = self.select_dtypes(include="float").columns
for col in float_columns:
if col not in formatters.keys():
formatters_.update({col: float_format_})
elif formatters is None and float_format is not None:
formatters_ = partial(_wrap, alt_format_=lambda v: v)
format_index_ = [index_format_, column_format_]
format_index_names_ = [index_format_, column_format_]
# Deal with hiding indexes and relabelling column names
hide_: list[dict] = []
relabel_index_: list[dict] = []
if columns:
hide_.append(
{
"subset": [c for c in self.columns if c not in columns],
"axis": "columns",
}
)
if header is False:
hide_.append({"axis": "columns"})
elif isinstance(header, (list, tuple)):
relabel_index_.append({"labels": header, "axis": "columns"})
format_index_ = [index_format_] # column_format is overwritten
if index is False:
hide_.append({"axis": "index"})
if index_names is False:
hide_.append({"names": True, "axis": "index"})
render_kwargs_ = {
"hrules": True,
"sparse_index": sparsify,
"sparse_columns": sparsify,
"environment": "longtable" if longtable else None,
"multicol_align": multicolumn_format
if multicolumn
else f"naive-{multicolumn_format}",
"multirow_align": "t" if multirow else "naive",
"encoding": encoding,
"caption": caption,
"label": label,
"position": position,
"column_format": column_format,
"clines": "skip-last;data"
if (multirow and isinstance(self.index, MultiIndex))
else None,
"bold_rows": bold_rows,
}
return self._to_latex_via_styler(
buf,
hide=hide_,
relabel_index=relabel_index_,
format={"formatter": formatters_, **base_format_},
format_index=format_index_,
format_index_names=format_index_names_,
render_kwargs=render_kwargs_,
)
@final
def _to_latex_via_styler(
self,
buf=None,
*,
hide: dict | list[dict] | None = None,
relabel_index: dict | list[dict] | None = None,
format: dict | list[dict] | None = None,
format_index: dict | list[dict] | None = None,
format_index_names: dict | list[dict] | None = None,
render_kwargs: dict | None = None,
):
"""
Render object to a LaTeX tabular, longtable, or nested table.
Uses the ``Styler`` implementation with the following, ordered, method chaining:
.. code-block:: python
styler = Styler(DataFrame)
styler.hide(**hide)
styler.relabel_index(**relabel_index)
styler.format(**format)
styler.format_index(**format_index)
styler.to_latex(buf=buf, **render_kwargs)
Parameters
----------
buf : str, Path or StringIO-like, optional, default None
Buffer to write to. If None, the output is returned as a string.
hide : dict, list of dict
Keyword args to pass to the method call of ``Styler.hide``. If a list will
call the method numerous times.
relabel_index : dict, list of dict
Keyword args to pass to the method of ``Styler.relabel_index``. If a list
will call the method numerous times.
format : dict, list of dict
Keyword args to pass to the method call of ``Styler.format``. If a list will
call the method numerous times.
format_index : dict, list of dict
Keyword args to pass to the method call of ``Styler.format_index``. If a
list will call the method numerous times.
render_kwargs : dict
Keyword args to pass to the method call of ``Styler.to_latex``.
Returns
-------
str or None
If buf is None, returns the result as a string. Otherwise returns None.
"""
from pandas.io.formats.style import Styler
self = cast("DataFrame", self)
styler = Styler(self, uuid="")
for kw_name in [
"hide",
"relabel_index",
"format",
"format_index",
"format_index_names",
]:
kw = vars()[kw_name]
if isinstance(kw, dict):
getattr(styler, kw_name)(**kw)
elif isinstance(kw, list):
for sub_kw in kw:
getattr(styler, kw_name)(**sub_kw)
# bold_rows is not a direct kwarg of Styler.to_latex
render_kwargs = {} if render_kwargs is None else render_kwargs
if render_kwargs.pop("bold_rows"):
styler.map_index(lambda v: "textbf:--rwrap;")
return styler.to_latex(buf=buf, **render_kwargs)
@overload
def to_csv(
self,
path_or_buf: None = ...,
*,
sep: str = ...,
na_rep: str = ...,
float_format: str | Callable | None = ...,
columns: Sequence[Hashable] | None = ...,
header: bool | list[str] = ...,
index: bool = ...,
index_label: IndexLabel | None = ...,
mode: str = ...,
encoding: str | None = ...,
compression: CompressionOptions = ...,
quoting: int | None = ...,
quotechar: str = ...,
lineterminator: str | None = ...,
chunksize: int | None = ...,
date_format: str | None = ...,
doublequote: bool = ...,
escapechar: str | None = ...,
decimal: str = ...,
errors: OpenFileErrors = ...,
storage_options: StorageOptions = ...,
) -> str: ...
@overload
def to_csv(
self,
path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str],
*,
sep: str = ...,
na_rep: str = ...,
float_format: str | Callable | None = ...,
columns: Sequence[Hashable] | None = ...,
header: bool | list[str] = ...,
index: bool = ...,
index_label: IndexLabel | None = ...,
mode: str = ...,
encoding: str | None = ...,
compression: CompressionOptions = ...,
quoting: int | None = ...,
quotechar: str = ...,
lineterminator: str | None = ...,
chunksize: int | None = ...,
date_format: str | None = ...,
doublequote: bool = ...,
escapechar: str | None = ...,
decimal: str = ...,
errors: OpenFileErrors = ...,
storage_options: StorageOptions = ...,
) -> None: ...
@final
@doc(
storage_options=_shared_docs["storage_options"],
compression_options=_shared_docs["compression_options"] % "path_or_buf",
)
def to_csv(
self,
path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,
*,
sep: str = ",",
na_rep: str = "",
float_format: str | Callable | None = None,
columns: Sequence[Hashable] | None = None,
header: bool | list[str] = True,
index: bool = True,
index_label: IndexLabel | None = None,
mode: str = "w",
encoding: str | None = None,
compression: CompressionOptions = "infer",
quoting: int | None = None,
quotechar: str = '"',
lineterminator: str | None = None,
chunksize: int | None = None,
date_format: str | None = None,
doublequote: bool = True,
escapechar: str | None = None,
decimal: str = ".",
errors: OpenFileErrors = "strict",
storage_options: StorageOptions | None = None,
) -> str | None:
r"""
Write object to a comma-separated values (csv) file.
Parameters
----------
path_or_buf : str, path object, file-like object, or None, default None
String, path object (implementing os.PathLike[str]), or file-like
object implementing a write() function. If None, the result is
returned as a string. If a non-binary file object is passed, it should
be opened with `newline=''`, disabling universal newlines. If a binary
file object is passed, `mode` might need to contain a `'b'`.
sep : str, default ','
String of length 1. Field delimiter for the output file.
na_rep : str, default ''
Missing data representation.
float_format : str, Callable, default None
Format string for floating point numbers. If a Callable is given, it takes
precedence over other numeric formatting parameters, like decimal.
columns : sequence, optional
Columns to write.
header : bool or list of str, default True
Write out the column names. If a list of strings is given it is
assumed to be aliases for the column names.
index : bool, default True
Write row names (index).
index_label : str or sequence, or False, default None
Column label for index column(s) if desired. If None is given, and
`header` and `index` are True, then the index names are used. A
sequence should be given if the object uses MultiIndex. If
False do not print fields for index names. Use index_label=False
for easier importing in R.
mode : {{'w', 'x', 'a'}}, default 'w'
Forwarded to either `open(mode=)` or `fsspec.open(mode=)` to control
the file opening. Typical values include:
- 'w', truncate the file first.
- 'x', exclusive creation, failing if the file already exists.
- 'a', append to the end of file if it exists.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'utf-8'. `encoding` is not supported if `path_or_buf`
is a non-binary file object.
{compression_options}
May be a dict with key 'method' as compression mode
and other entries as additional compression options if
compression mode is 'zip'.
Passing compression options as keys in dict is
supported for compression modes 'gzip', 'bz2', 'zstd', and 'zip'.
quoting : optional constant from csv module
Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`
then floats are converted to strings and thus csv.QUOTE_NONNUMERIC
will treat them as non-numeric.
quotechar : str, default '\"'
String of length 1. Character used to quote fields.
lineterminator : str, optional
The newline character or character sequence to use in the output
file. Defaults to `os.linesep`, which depends on the OS in which
this method is called ('\\n' for linux, '\\r\\n' for Windows, i.e.).
chunksize : int or None
Rows to write at a time.
date_format : str, default None
Format string for datetime objects.
doublequote : bool, default True
Control quoting of `quotechar` inside a field.
escapechar : str, default None
String of length 1. Character used to escape `sep` and `quotechar`
when appropriate.
decimal : str, default '.'
Character recognized as decimal separator. E.g. use ',' for
European data.
errors : str, default 'strict'
Specifies how encoding and decoding errors are to be handled.
See the errors argument for :func:`open` for a full list
of options.
{storage_options}
Returns
-------
None or str
If path_or_buf is None, returns the resulting csv format as a
string. Otherwise returns None.
See Also
--------
read_csv : Load a CSV file into a DataFrame.
to_excel : Write DataFrame to an Excel file.
Examples
--------
Create 'out.csv' containing 'df' without indices
>>> df = pd.DataFrame(
... [["Raphael", "red", "sai"], ["Donatello", "purple", "bo staff"]],
... columns=["name", "mask", "weapon"],
... )
>>> df.to_csv("out.csv", index=False) # doctest: +SKIP
Create 'out.zip' containing 'out.csv'
>>> df.to_csv(index=False)
'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
>>> compression_opts = dict(
... method="zip", archive_name="out.csv"
... ) # doctest: +SKIP
>>> df.to_csv(
... "out.zip", index=False, compression=compression_opts
... ) # doctest: +SKIP
To write a csv file to a new folder or nested folder you will first
need to create it using either Pathlib or os:
>>> from pathlib import Path # doctest: +SKIP
>>> filepath = Path("folder/subfolder/out.csv") # doctest: +SKIP
>>> filepath.parent.mkdir(parents=True, exist_ok=True) # doctest: +SKIP
>>> df.to_csv(filepath) # doctest: +SKIP
>>> import os # doctest: +SKIP
>>> os.makedirs("folder/subfolder", exist_ok=True) # doctest: +SKIP
>>> df.to_csv("folder/subfolder/out.csv") # doctest: +SKIP
Format floats to two decimal places:
>>> df.to_csv("out1.csv", float_format="%.2f") # doctest: +SKIP
Format floats using scientific notation:
>>> df.to_csv("out2.csv", float_format="{{:.2e}}".format) # doctest: +SKIP
"""
df = self if isinstance(self, ABCDataFrame) else self.to_frame()
formatter = DataFrameFormatter(
frame=df,
header=header,
index=index,
na_rep=na_rep,
float_format=float_format,
decimal=decimal,
)
return DataFrameRenderer(formatter).to_csv(
path_or_buf,
lineterminator=lineterminator,
sep=sep,
encoding=encoding,
errors=errors,
compression=compression,
quoting=quoting,
columns=columns,
index_label=index_label,
mode=mode,
chunksize=chunksize,
quotechar=quotechar,
date_format=date_format,
doublequote=doublequote,
escapechar=escapechar,
storage_options=storage_options,
)
# ----------------------------------------------------------------------
# Indexing Methods
@final
def take(self, indices, axis: Axis = 0, **kwargs) -> Self:
"""
Return the elements in the given *positional* indices along an axis.
This means that we are not indexing according to actual values in
the index attribute of the object. We are indexing according to the
actual position of the element in the object.
Parameters
----------
indices : array-like
An array of ints indicating which positions to take.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis on which to select elements. ``0`` means that we are
selecting rows, ``1`` means that we are selecting columns.
For `Series` this parameter is unused and defaults to 0.
**kwargs
For compatibility with :meth:`numpy.take`. Has no effect on the
output.
Returns
-------
same type as caller
An array-like containing the elements taken from the object.
See Also
--------
DataFrame.loc : Select a subset of a DataFrame by labels.
DataFrame.iloc : Select a subset of a DataFrame by positions.
numpy.take : Take elements from an array along an axis.
Examples
--------
>>> df = pd.DataFrame(
... [
... ("falcon", "bird", 389.0),
... ("parrot", "bird", 24.0),
... ("lion", "mammal", 80.5),
... ("monkey", "mammal", np.nan),
... ],
... columns=["name", "class", "max_speed"],
... index=[0, 2, 3, 1],
... )
>>> df
name class max_speed
0 falcon bird 389.0
2 parrot bird 24.0
3 lion mammal 80.5
1 monkey mammal NaN
Take elements at positions 0 and 3 along the axis 0 (default).
Note how the actual indices selected (0 and 1) do not correspond to
our selected indices 0 and 3. That's because we are selecting the 0th
and 3rd rows, not rows whose indices equal 0 and 3.
>>> df.take([0, 3])
name class max_speed
0 falcon bird 389.0
1 monkey mammal NaN
Take elements at indices 1 and 2 along the axis 1 (column selection).
>>> df.take([1, 2], axis=1)
class max_speed
0 bird 389.0
2 bird 24.0
3 mammal 80.5
1 mammal NaN
We may take elements using negative integers for positive indices,
starting from the end of the object, just like with Python lists.
>>> df.take([-1, -2])
name class max_speed
1 monkey mammal NaN
3 lion mammal 80.5
"""
nv.validate_take((), kwargs)
if isinstance(indices, slice):
raise TypeError(
f"{type(self).__name__}.take requires a sequence of integers, "
"not slice."
)
indices = np.asarray(indices, dtype=np.intp)
if axis == 0 and indices.ndim == 1 and is_range_indexer(indices, len(self)):
return self.copy(deep=False)
new_data = self._mgr.take(
indices,
axis=self._get_block_manager_axis(axis),
verify=True,
)
return self._constructor_from_mgr(new_data, axes=new_data.axes).__finalize__(
self, method="take"
)
@final
def xs(
self,
key: IndexLabel,
axis: Axis = 0,
level: IndexLabel | None = None,
drop_level: bool = True,
) -> Self:
"""
Return cross-section from the Series/DataFrame.
This method takes a `key` argument to select data at a particular
level of a MultiIndex.
Parameters
----------
key : label or tuple of label
Label contained in the index, or partially in a MultiIndex.
axis : {0 or 'index', 1 or 'columns'}, default 0
Axis to retrieve cross-section on.
level : object, defaults to first n levels (n=1 or len(key))
In case of a key partially contained in a MultiIndex, indicate
which levels are used. Levels can be referred by label or position.
drop_level : bool, default True
If False, returns object with same levels as self.
Returns
-------
Series or DataFrame
Cross-section from the original Series or DataFrame
corresponding to the selected index levels.
See Also
--------
DataFrame.loc : Access a group of rows and columns
by label(s) or a boolean array.
DataFrame.iloc : Purely integer-location based indexing
for selection by position.
Notes
-----
`xs` can not be used to set values.
MultiIndex Slicers is a generic way to get/set values on
any level or levels.
It is a superset of `xs` functionality, see
:ref:`MultiIndex Slicers <advanced.mi_slicers>`.
Examples
--------
>>> d = {
... "num_legs": [4, 4, 2, 2],
... "num_wings": [0, 0, 2, 2],
... "class": ["mammal", "mammal", "mammal", "bird"],
... "animal": ["cat", "dog", "bat", "penguin"],
... "locomotion": ["walks", "walks", "flies", "walks"],
... }
>>> df = pd.DataFrame(data=d)
>>> df = df.set_index(["class", "animal", "locomotion"])
>>> df
num_legs num_wings
class animal locomotion
mammal cat walks 4 0
dog walks 4 0
bat flies 2 2
bird penguin walks 2 2
Get values at specified index
>>> df.xs("mammal")
num_legs num_wings
animal locomotion
cat walks 4 0
dog walks 4 0
bat flies 2 2
Get values at several indexes
>>> df.xs(("mammal", "dog", "walks"))
num_legs 4
num_wings 0
Name: (mammal, dog, walks), dtype: int64
Get values at specified index and level
>>> df.xs("cat", level=1)
num_legs num_wings
class locomotion
mammal walks 4 0
Get values at several indexes and levels
>>> df.xs(("bird", "walks"), level=[0, "locomotion"])
num_legs num_wings
animal
penguin 2 2
Get values at specified column and axis
>>> df.xs("num_wings", axis=1)
class animal locomotion
mammal cat walks 0
dog walks 0
bat flies 2
bird penguin walks 2
Name: num_wings, dtype: int64
"""
axis = self._get_axis_number(axis)
labels = self._get_axis(axis)
if isinstance(key, list):
raise TypeError("list keys are not supported in xs, pass a tuple instead")
if level is not None:
if not isinstance(labels, MultiIndex):
raise TypeError("Index must be a MultiIndex")
loc, new_ax = labels.get_loc_level(key, level=level, drop_level=drop_level)
# create the tuple of the indexer
_indexer = [slice(None)] * self.ndim
_indexer[axis] = loc
indexer = tuple(_indexer)
result = self.iloc[indexer]
setattr(result, result._get_axis_name(axis), new_ax)
return result
if axis == 1:
if drop_level:
return self[key]
index = self.columns
else:
index = self.index
if isinstance(index, MultiIndex):
loc, new_index = index._get_loc_level(key, level=0)
if not drop_level:
if lib.is_integer(loc):
# Slice index must be an integer or None
new_index = index[loc : loc + 1]
else:
new_index = index[loc]
else:
loc = index.get_loc(key)
if isinstance(loc, np.ndarray):
if loc.dtype == np.bool_:
(inds,) = loc.nonzero()
return self.take(inds, axis=axis)
else:
return self.take(loc, axis=axis)
if not is_scalar(loc):
new_index = index[loc]
if is_scalar(loc) and axis == 0:
# In this case loc should be an integer
if self.ndim == 1:
# if we encounter an array-like and we only have 1 dim
# that means that their are list/ndarrays inside the Series!
# so just return them (GH 6394)
return self._values[loc]
new_mgr = self._mgr.fast_xs(loc)
result = self._constructor_sliced_from_mgr(new_mgr, axes=new_mgr.axes)
result._name = self.index[loc]
result = result.__finalize__(self)
elif is_scalar(loc):
result = self.iloc[:, slice(loc, loc + 1)]
elif axis == 1:
result = self.iloc[:, loc]
else:
result = self.iloc[loc]
result.index = new_index
return result
def __getitem__(self, item):
raise AbstractMethodError(self)
@final
def _getitem_slice(self, key: slice) -> Self:
"""
__getitem__ for the case where the key is a slice object.
"""
# _convert_slice_indexer to determine if this slice is positional
# or label based, and if the latter, convert to positional
slobj = self.index._convert_slice_indexer(key, kind="getitem")
if isinstance(slobj, np.ndarray):
# reachable with DatetimeIndex
indexer = lib.maybe_indices_to_slice(slobj.astype(np.intp), len(self))
if isinstance(indexer, np.ndarray):
# GH#43223 If we can not convert, use take
return self.take(indexer, axis=0)
slobj = indexer
return self._slice(slobj)
def _slice(self, slobj: slice, axis: AxisInt = 0) -> Self:
"""
Construct a slice of this container.
Slicing with this method is *always* positional.
"""
assert isinstance(slobj, slice), type(slobj)
axis = self._get_block_manager_axis(axis)
new_mgr = self._mgr.get_slice(slobj, axis=axis)
result = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
result = result.__finalize__(self)
return result
@final
def __delitem__(self, key) -> None:
"""
Delete item
"""
deleted = False
maybe_shortcut = False
if self.ndim == 2 and isinstance(self.columns, MultiIndex):
try:
# By using engine's __contains__ we effectively
# restrict to same-length tuples
maybe_shortcut = key not in self.columns._engine
except TypeError:
pass
if maybe_shortcut:
# Allow shorthand to delete all columns whose first len(key)
# elements match key:
if not isinstance(key, tuple):
key = (key,)
for col in self.columns:
if isinstance(col, tuple) and col[: len(key)] == key:
del self[col]
deleted = True
if not deleted:
# If the above loop ran and didn't delete anything because
# there was no match, this call should raise the appropriate
# exception:
loc = self.axes[-1].get_loc(key)
self._mgr = self._mgr.idelete(loc)
# ----------------------------------------------------------------------
# Unsorted
@final
def _check_inplace_and_allows_duplicate_labels(self, inplace: bool) -> None:
if inplace and not self.flags.allows_duplicate_labels:
raise ValueError(
"Cannot specify 'inplace=True' when "
"'self.flags.allows_duplicate_labels' is False."
)
@final
def get(self, key, default=None):
"""
Get item from object for given key (ex: DataFrame column).
Returns ``default`` value if not found.
Parameters
----------
key : object
Key for which item should be returned.
default : object, default None
Default value to return if key is not found.
Returns
-------
same type as items contained in object
Item for given key or ``default`` value, if key is not found.
See Also
--------
DataFrame.get : Get item from object for given key (ex: DataFrame column).
Series.get : Get item from object for given key (ex: DataFrame column).
Examples
--------
>>> df = pd.DataFrame(
... [
... [24.3, 75.7, "high"],
... [31, 87.8, "high"],
... [22, 71.6, "medium"],
... [35, 95, "medium"],
... ],
... columns=["temp_celsius", "temp_fahrenheit", "windspeed"],
... index=pd.date_range(start="2014-02-12", end="2014-02-15", freq="D"),
... )
>>> df
temp_celsius temp_fahrenheit windspeed
2014-02-12 24.3 75.7 high
2014-02-13 31.0 87.8 high
2014-02-14 22.0 71.6 medium
2014-02-15 35.0 95.0 medium
>>> df.get(["temp_celsius", "windspeed"])
temp_celsius windspeed
2014-02-12 24.3 high
2014-02-13 31.0 high
2014-02-14 22.0 medium
2014-02-15 35.0 medium
>>> ser = df["windspeed"]
>>> ser.get("2014-02-13")
'high'
If the key isn't found, the default value will be used.
>>> df.get(["temp_celsius", "temp_kelvin"], default="default_value")
'default_value'
>>> ser.get("2014-02-10", "[unknown]")
'[unknown]'
"""
try:
return self[key]
except (KeyError, ValueError, IndexError):
return default
@staticmethod
def _check_copy_deprecation(copy):
if copy is not lib.no_default:
warnings.warn(
"The copy keyword is deprecated and will be removed in a future "
"version. Copy-on-Write is active in pandas since 3.0 which utilizes "
"a lazy copy mechanism that defers copies until necessary. Use "
".copy() to make an eager copy if necessary.",
Pandas4Warning,
stacklevel=find_stack_level(),
)
# issue 58667
@deprecate_kwarg(Pandas4Warning, "method", new_arg_name=None)
@final
def reindex_like(
self,
other,
method: Literal["backfill", "bfill", "pad", "ffill", "nearest"] | None = None,
copy: bool | lib.NoDefault = lib.no_default,
limit: int | None = None,
tolerance=None,
) -> Self:
"""
Return an object with matching indices as other object.
Conform the object to the same index on all axes. Optional
filling logic, placing NaN in locations having no value
in the previous index. A new object is produced unless the
new index is equivalent to the current one and copy=False.
Parameters
----------
other : Object of the same data type
Its row and column indices are used to define the new indices
of this object.
method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}
Method to use for filling holes in reindexed DataFrame.
Please note: this is only applicable to DataFrames/Series with a
monotonically increasing/decreasing index.
.. deprecated:: 3.0.0
* None (default): don't fill gaps
* pad / ffill: propagate last valid observation forward to next
valid
* backfill / bfill: use next valid observation to fill gap
* nearest: use nearest valid observations to fill gap.
copy : bool, default False
Return a new object, even if the passed indexes are the same.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
limit : int, default None
Maximum number of consecutive labels to fill for inexact matches.
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
Tolerance may be a scalar value, which applies the same tolerance
to all values, or list-like, which applies variable tolerance per
element. List-like includes list, tuple, array, Series, and must be
the same size as the index and its dtype must exactly match the
index's type.
Returns
-------
Series or DataFrame
Same type as caller, but with changed indices on each axis.
See Also
--------
DataFrame.set_index : Set row labels.
DataFrame.reset_index : Remove row labels or move them to new columns.
DataFrame.reindex : Change to new indices or expand indices.
Notes
-----
Same as calling
``.reindex(index=other.index, columns=other.columns,...)``.
Examples
--------
>>> df1 = pd.DataFrame(
... [
... [24.3, 75.7, "high"],
... [31, 87.8, "high"],
... [22, 71.6, "medium"],
... [35, 95, "medium"],
... ],
... columns=["temp_celsius", "temp_fahrenheit", "windspeed"],
... index=pd.date_range(start="2014-02-12", end="2014-02-15", freq="D"),
... )
>>> df1
temp_celsius temp_fahrenheit windspeed
2014-02-12 24.3 75.7 high
2014-02-13 31.0 87.8 high
2014-02-14 22.0 71.6 medium
2014-02-15 35.0 95.0 medium
>>> df2 = pd.DataFrame(
... [[28, "low"], [30, "low"], [35.1, "medium"]],
... columns=["temp_celsius", "windspeed"],
... index=pd.DatetimeIndex(["2014-02-12", "2014-02-13", "2014-02-15"]),
... )
>>> df2
temp_celsius windspeed
2014-02-12 28.0 low
2014-02-13 30.0 low
2014-02-15 35.1 medium
>>> df2.reindex_like(df1)
temp_celsius temp_fahrenheit windspeed
2014-02-12 28.0 NaN low
2014-02-13 30.0 NaN low
2014-02-14 NaN NaN NaN
2014-02-15 35.1 NaN medium
"""
self._check_copy_deprecation(copy)
d = other._construct_axes_dict(
axes=self._AXIS_ORDERS,
method=method,
limit=limit,
tolerance=tolerance,
)
return self.reindex(**d)
@overload
def drop(
self,
labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
index: IndexLabel | ListLike = ...,
columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: Literal[True],
errors: IgnoreRaise = ...,
) -> None: ...
@overload
def drop(
self,
labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
index: IndexLabel | ListLike = ...,
columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: Literal[False] = ...,
errors: IgnoreRaise = ...,
) -> Self: ...
@overload
def drop(
self,
labels: IndexLabel | ListLike = ...,
*,
axis: Axis = ...,
index: IndexLabel | ListLike = ...,
columns: IndexLabel | ListLike = ...,
level: Level | None = ...,
inplace: bool = ...,
errors: IgnoreRaise = ...,
) -> Self | None: ...
def drop(
self,
labels: IndexLabel | ListLike = None,
*,
axis: Axis = 0,
index: IndexLabel | ListLike = None,
columns: IndexLabel | ListLike = None,
level: Level | None = None,
inplace: bool = False,
errors: IgnoreRaise = "raise",
) -> Self | None:
inplace = validate_bool_kwarg(inplace, "inplace")
if labels is not None:
if index is not None or columns is not None:
raise ValueError("Cannot specify both 'labels' and 'index'/'columns'")
axis_name = self._get_axis_name(axis)
axes = {axis_name: labels}
elif index is not None or columns is not None:
if axis == 1:
raise ValueError("Cannot specify both 'axis' and 'index'/'columns'")
axes = {"index": index}
if self.ndim == 2:
axes["columns"] = columns
else:
raise ValueError(
"Need to specify at least one of 'labels', 'index' or 'columns'"
)
obj = self
for axis, labels in axes.items():
if labels is not None:
obj = obj._drop_axis(labels, axis, level=level, errors=errors)
if inplace:
self._update_inplace(obj)
return None
else:
return obj
@final
def _drop_axis(
self,
labels,
axis,
level=None,
errors: IgnoreRaise = "raise",
only_slice: bool = False,
) -> Self:
"""
Drop labels from specified axis. Used in the ``drop`` method
internally.
Parameters
----------
labels : single label or list-like
axis : int or axis name
level : int or level name, default None
For MultiIndex
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and existing labels are dropped.
only_slice : bool, default False
Whether indexing along columns should be view-only.
"""
axis_num = self._get_axis_number(axis)
axis = self._get_axis(axis)
if axis.is_unique:
if level is not None:
if not isinstance(axis, MultiIndex):
raise AssertionError("axis must be a MultiIndex")
new_axis = axis.drop(labels, level=level, errors=errors)
else:
new_axis = axis.drop(labels, errors=errors)
indexer = axis.get_indexer(new_axis)
# Case for non-unique axis
else:
is_tuple_labels = is_nested_list_like(labels) or isinstance(labels, tuple)
labels = ensure_object(common.index_labels_to_array(labels))
if level is not None:
if not isinstance(axis, MultiIndex):
raise AssertionError("axis must be a MultiIndex")
mask = ~axis.get_level_values(level).isin(labels)
# GH 18561 MultiIndex.drop should raise if label is absent
if errors == "raise" and mask.all():
raise KeyError(f"{labels} not found in axis")
elif (
isinstance(axis, MultiIndex)
and labels.dtype == "object"
and not is_tuple_labels
):
# Set level to zero in case of MultiIndex and label is string,
# because isin can't handle strings for MultiIndexes GH#36293
# In case of tuples we get dtype object but have to use isin GH#42771
mask = ~axis.get_level_values(0).isin(labels)
else:
mask = ~axis.isin(labels)
# Check if label doesn't exist along axis
labels_missing = (axis.get_indexer_for(labels) == -1).any()
if errors == "raise" and labels_missing:
raise KeyError(f"{labels} not found in axis")
if isinstance(mask.dtype, ExtensionDtype):
# GH#45860
mask = mask.to_numpy(dtype=bool)
indexer = mask.nonzero()[0]
new_axis = axis.take(indexer)
bm_axis = self.ndim - axis_num - 1
new_mgr = self._mgr.reindex_indexer(
new_axis,
indexer,
axis=bm_axis,
allow_dups=True,
only_slice=only_slice,
)
result = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
if self.ndim == 1:
result._name = self.name
return result.__finalize__(self)
@final
def _update_inplace(self, result) -> None:
"""
Replace self internals with result.
Parameters
----------
result : same type as self
"""
# NOTE: This does *not* call __finalize__ and that's an explicit
# decision that we may revisit in the future.
self._mgr = result._mgr
@final
def add_prefix(self, prefix: str, axis: Axis | None = None) -> Self:
"""
Prefix labels with string `prefix`.
For Series, the row labels are prefixed.
For DataFrame, the column labels are prefixed.
Parameters
----------
prefix : str
The string to add before each label.
axis : {0 or 'index', 1 or 'columns', None}, default None
Axis to add prefix on
.. versionadded:: 2.0.0
Returns
-------
Series or DataFrame
New Series or DataFrame with updated labels.
See Also
--------
Series.add_suffix: Suffix row labels with string `suffix`.
DataFrame.add_suffix: Suffix column labels with string `suffix`.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.add_prefix("item_")
item_0 1
item_1 2
item_2 3
item_3 4
dtype: int64
>>> df = pd.DataFrame({"A": [1, 2, 3, 4], "B": [3, 4, 5, 6]})
>>> df
A B
0 1 3
1 2 4
2 3 5
3 4 6
>>> df.add_prefix("col_")
col_A col_B
0 1 3
1 2 4
2 3 5
3 4 6
"""
f = lambda x: f"{prefix}{x}"
axis_name = self._info_axis_name
if axis is not None:
axis_name = self._get_axis_name(axis)
mapper = {axis_name: f}
# error: Keywords must be strings
# error: No overload variant of "_rename" of "NDFrame" matches
# argument type "dict[Literal['index', 'columns'], Callable[[Any], str]]"
return self._rename(**mapper) # type: ignore[call-overload, misc]
@final
def add_suffix(self, suffix: str, axis: Axis | None = None) -> Self:
"""
Suffix labels with string `suffix`.
For Series, the row labels are suffixed.
For DataFrame, the column labels are suffixed.
Parameters
----------
suffix : str
The string to add after each label.
axis : {0 or 'index', 1 or 'columns', None}, default None
Axis to add suffix on
.. versionadded:: 2.0.0
Returns
-------
Series or DataFrame
New Series or DataFrame with updated labels.
See Also
--------
Series.add_prefix: Prefix row labels with string `prefix`.
DataFrame.add_prefix: Prefix column labels with string `prefix`.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.add_suffix("_item")
0_item 1
1_item 2
2_item 3
3_item 4
dtype: int64
>>> df = pd.DataFrame({"A": [1, 2, 3, 4], "B": [3, 4, 5, 6]})
>>> df
A B
0 1 3
1 2 4
2 3 5
3 4 6
>>> df.add_suffix("_col")
A_col B_col
0 1 3
1 2 4
2 3 5
3 4 6
"""
f = lambda x: f"{x}{suffix}"
axis_name = self._info_axis_name
if axis is not None:
axis_name = self._get_axis_name(axis)
mapper = {axis_name: f}
# error: Keywords must be strings
# error: No overload variant of "_rename" of "NDFrame" matches argument
# type "dict[Literal['index', 'columns'], Callable[[Any], str]]"
return self._rename(**mapper) # type: ignore[call-overload, misc]
@overload
def sort_values(
self,
*,
axis: Axis = ...,
ascending: bool | Sequence[bool] = ...,
inplace: Literal[False] = ...,
kind: SortKind = ...,
na_position: NaPosition = ...,
ignore_index: bool = ...,
key: ValueKeyFunc = ...,
) -> Self: ...
@overload
def sort_values(
self,
*,
axis: Axis = ...,
ascending: bool | Sequence[bool] = ...,
inplace: Literal[True],
kind: SortKind = ...,
na_position: NaPosition = ...,
ignore_index: bool = ...,
key: ValueKeyFunc = ...,
) -> None: ...
@overload
def sort_values(
self,
*,
axis: Axis = ...,
ascending: bool | Sequence[bool] = ...,
inplace: bool = ...,
kind: SortKind = ...,
na_position: NaPosition = ...,
ignore_index: bool = ...,
key: ValueKeyFunc = ...,
) -> Self | None: ...
def sort_values(
self,
*,
axis: Axis = 0,
ascending: bool | Sequence[bool] = True,
inplace: bool = False,
kind: SortKind = "quicksort",
na_position: NaPosition = "last",
ignore_index: bool = False,
key: ValueKeyFunc | None = None,
) -> Self | None:
"""
Sort by the values along either axis.
Parameters
----------%(optional_by)s
axis : %(axes_single_arg)s, default 0
Axis to be sorted.
ascending : bool or list of bool, default True
Sort ascending vs. descending. Specify list for multiple sort
orders. If this is a list of bools, must match the length of
the by.
inplace : bool, default False
If True, perform operation in-place.
kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
Choice of sorting algorithm. See also :func:`numpy.sort` for more
information. `mergesort` and `stable` are the only stable algorithms. For
DataFrames, this option is only applied when sorting on a single
column or label.
na_position : {'first', 'last'}, default 'last'
Puts NaNs at the beginning if `first`; `last` puts NaNs at the
end.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
key : callable, optional
Apply the key function to the values
before sorting. This is similar to the `key` argument in the
builtin :meth:`sorted` function, with the notable difference that
this `key` function should be *vectorized*. It should expect a
``Series`` and return a Series with the same shape as the input.
It will be applied to each column in `by` independently. The values in the
returned Series will be used as the keys for sorting.
Returns
-------
DataFrame or None
DataFrame with sorted values or None if ``inplace=True``.
See Also
--------
DataFrame.sort_index : Sort a DataFrame by the index.
Series.sort_values : Similar method for a Series.
Examples
--------
>>> df = pd.DataFrame(
... {
... "col1": ["A", "A", "B", np.nan, "D", "C"],
... "col2": [2, 1, 9, 8, 7, 4],
... "col3": [0, 1, 9, 4, 2, 3],
... "col4": ["a", "B", "c", "D", "e", "F"],
... }
... )
>>> df
col1 col2 col3 col4
0 A 2 0 a
1 A 1 1 B
2 B 9 9 c
3 NaN 8 4 D
4 D 7 2 e
5 C 4 3 F
Sort by col1
>>> df.sort_values(by=["col1"])
col1 col2 col3 col4
0 A 2 0 a
1 A 1 1 B
2 B 9 9 c
5 C 4 3 F
4 D 7 2 e
3 NaN 8 4 D
Sort by multiple columns
>>> df.sort_values(by=["col1", "col2"])
col1 col2 col3 col4
1 A 1 1 B
0 A 2 0 a
2 B 9 9 c
5 C 4 3 F
4 D 7 2 e
3 NaN 8 4 D
Sort Descending
>>> df.sort_values(by="col1", ascending=False)
col1 col2 col3 col4
4 D 7 2 e
5 C 4 3 F
2 B 9 9 c
0 A 2 0 a
1 A 1 1 B
3 NaN 8 4 D
Putting NAs first
>>> df.sort_values(by="col1", ascending=False, na_position="first")
col1 col2 col3 col4
3 NaN 8 4 D
4 D 7 2 e
5 C 4 3 F
2 B 9 9 c
0 A 2 0 a
1 A 1 1 B
Sorting with a key function
>>> df.sort_values(by="col4", key=lambda col: col.str.lower())
col1 col2 col3 col4
0 A 2 0 a
1 A 1 1 B
2 B 9 9 c
3 NaN 8 4 D
4 D 7 2 e
5 C 4 3 F
Natural sort with the key argument,
using the `natsort <https://github.com/SethMMorton/natsort>` package.
>>> df = pd.DataFrame(
... {
... "hours": ["0hr", "128hr", "0hr", "64hr", "64hr", "128hr"],
... "mins": [
... "10mins",
... "40mins",
... "40mins",
... "40mins",
... "10mins",
... "10mins",
... ],
... "value": [10, 20, 30, 40, 50, 60],
... }
... )
>>> df
hours mins value
0 0hr 10mins 10
1 128hr 40mins 20
2 0hr 40mins 30
3 64hr 40mins 40
4 64hr 10mins 50
5 128hr 10mins 60
>>> from natsort import natsort_keygen
>>> df.sort_values(
... by=["hours", "mins"],
... key=natsort_keygen(),
... )
hours mins value
0 0hr 10mins 10
2 0hr 40mins 30
4 64hr 10mins 50
3 64hr 40mins 40
5 128hr 10mins 60
1 128hr 40mins 20
"""
raise AbstractMethodError(self)
@overload
def sort_index(
self,
*,
axis: Axis = ...,
level: IndexLabel = ...,
ascending: bool | Sequence[bool] = ...,
inplace: Literal[True],
kind: SortKind = ...,
na_position: NaPosition = ...,
sort_remaining: bool = ...,
ignore_index: bool = ...,
key: IndexKeyFunc = ...,
) -> None: ...
@overload
def sort_index(
self,
*,
axis: Axis = ...,
level: IndexLabel = ...,
ascending: bool | Sequence[bool] = ...,
inplace: Literal[False] = ...,
kind: SortKind = ...,
na_position: NaPosition = ...,
sort_remaining: bool = ...,
ignore_index: bool = ...,
key: IndexKeyFunc = ...,
) -> Self: ...
@overload
def sort_index(
self,
*,
axis: Axis = ...,
level: IndexLabel = ...,
ascending: bool | Sequence[bool] = ...,
inplace: bool = ...,
kind: SortKind = ...,
na_position: NaPosition = ...,
sort_remaining: bool = ...,
ignore_index: bool = ...,
key: IndexKeyFunc = ...,
) -> Self | None: ...
def sort_index(
self,
*,
axis: Axis = 0,
level: IndexLabel | None = None,
ascending: bool | Sequence[bool] = True,
inplace: bool = False,
kind: SortKind = "quicksort",
na_position: NaPosition = "last",
sort_remaining: bool = True,
ignore_index: bool = False,
key: IndexKeyFunc | None = None,
) -> Self | None:
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
ascending = validate_ascending(ascending)
target = self._get_axis(axis)
indexer = get_indexer_indexer(
target, level, ascending, kind, na_position, sort_remaining, key
)
if indexer is None:
if inplace:
result = self
else:
result = self.copy(deep=False)
if ignore_index:
if axis == 1:
result.columns = default_index(len(self.columns))
else:
result.index = default_index(len(self))
if inplace:
return None
else:
return result
baxis = self._get_block_manager_axis(axis)
new_data = self._mgr.take(indexer, axis=baxis, verify=False)
# reconstruct axis if needed
if not ignore_index:
new_axis = new_data.axes[baxis]._sort_levels_monotonic()
else:
new_axis = default_index(len(indexer))
new_data.set_axis(baxis, new_axis)
result = self._constructor_from_mgr(new_data, axes=new_data.axes)
if inplace:
return self._update_inplace(result)
else:
return result.__finalize__(self, method="sort_index")
@doc(
klass=_shared_doc_kwargs["klass"],
optional_reindex="",
)
def reindex(
self,
labels=None,
*,
index=None,
columns=None,
axis: Axis | None = None,
method: ReindexMethod | None = None,
copy: bool | lib.NoDefault = lib.no_default,
level: Level | None = None,
fill_value: Scalar | None = np.nan,
limit: int | None = None,
tolerance=None,
) -> Self:
"""
Conform {klass} to new index with optional filling logic.
Places NA/NaN in locations having no value in the previous index. A new object
is produced unless the new index is equivalent to the current one and
``copy=False``.
Parameters
----------
{optional_reindex}
method : {{None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}}
Method to use for filling holes in reindexed DataFrame.
Please note: this is only applicable to DataFrames/Series with a
monotonically increasing/decreasing index.
* None (default): don't fill gaps
* pad / ffill: Propagate last valid observation forward to next
valid.
* backfill / bfill: Use next valid observation to fill gap.
* nearest: Use nearest valid observations to fill gap.
copy : bool, default False
Return a new object, even if the passed indexes are the same.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
level : int or name
Broadcast across a level, matching Index values on the
passed MultiIndex level.
fill_value : scalar, default np.nan
Value to use for missing values. Defaults to NaN, but can be any
"compatible" value.
limit : int, default None
Maximum number of consecutive elements to forward or backward fill.
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations most
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
Tolerance may be a scalar value, which applies the same tolerance
to all values, or list-like, which applies variable tolerance per
element. List-like includes list, tuple, array, Series, and must be
the same size as the index and its dtype must exactly match the
index's type.
Returns
-------
{klass}
{klass} with changed index.
See Also
--------
DataFrame.set_index : Set row labels.
DataFrame.reset_index : Remove row labels or move them to new columns.
DataFrame.reindex_like : Change to same indices as other DataFrame.
Examples
--------
``DataFrame.reindex`` supports two calling conventions
* ``(index=index_labels, columns=column_labels, ...)``
* ``(labels, axis={{'index', 'columns'}}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
Create a DataFrame with some fictional data.
>>> index = ["Firefox", "Chrome", "Safari", "IE10", "Konqueror"]
>>> columns = ["http_status", "response_time"]
>>> df = pd.DataFrame(
... [[200, 0.04], [200, 0.02], [404, 0.07], [404, 0.08], [301, 1.0]],
... columns=columns,
... index=index,
... )
>>> df
http_status response_time
Firefox 200 0.04
Chrome 200 0.02
Safari 404 0.07
IE10 404 0.08
Konqueror 301 1.00
Create a new index and reindex the DataFrame. By default
values in the new index that do not have corresponding
records in the DataFrame are assigned ``NaN``.
>>> new_index = ["Safari", "Iceweasel", "Comodo Dragon", "IE10", "Chrome"]
>>> df.reindex(new_index)
http_status response_time
Safari 404.0 0.07
Iceweasel NaN NaN
Comodo Dragon NaN NaN
IE10 404.0 0.08
Chrome 200.0 0.02
We can fill in the missing values by passing a value to
the keyword ``fill_value``. Because the index is not monotonically
increasing or decreasing, we cannot use arguments to the keyword
``method`` to fill the ``NaN`` values.
>>> df.reindex(new_index, fill_value=0)
http_status response_time
Safari 404 0.07
Iceweasel 0 0.00
Comodo Dragon 0 0.00
IE10 404 0.08
Chrome 200 0.02
>>> df.reindex(new_index, fill_value="missing")
http_status response_time
Safari 404 0.07
Iceweasel missing missing
Comodo Dragon missing missing
IE10 404 0.08
Chrome 200 0.02
We can also reindex the columns.
>>> df.reindex(columns=["http_status", "user_agent"])
http_status user_agent
Firefox 200 NaN
Chrome 200 NaN
Safari 404 NaN
IE10 404 NaN
Konqueror 301 NaN
Or we can use "axis-style" keyword arguments
>>> df.reindex(["http_status", "user_agent"], axis="columns")
http_status user_agent
Firefox 200 NaN
Chrome 200 NaN
Safari 404 NaN
IE10 404 NaN
Konqueror 301 NaN
To further illustrate the filling functionality in
``reindex``, we will create a DataFrame with a
monotonically increasing index (for example, a sequence
of dates).
>>> date_index = pd.date_range("1/1/2010", periods=6, freq="D")
>>> df2 = pd.DataFrame(
... {{"prices": [100, 101, np.nan, 100, 89, 88]}}, index=date_index
... )
>>> df2
prices
2010-01-01 100.0
2010-01-02 101.0
2010-01-03 NaN
2010-01-04 100.0
2010-01-05 89.0
2010-01-06 88.0
Suppose we decide to expand the DataFrame to cover a wider
date range.
>>> date_index2 = pd.date_range("12/29/2009", periods=10, freq="D")
>>> df2.reindex(date_index2)
prices
2009-12-29 NaN
2009-12-30 NaN
2009-12-31 NaN
2010-01-01 100.0
2010-01-02 101.0
2010-01-03 NaN
2010-01-04 100.0
2010-01-05 89.0
2010-01-06 88.0
2010-01-07 NaN
The index entries that did not have a value in the original data frame
(for example, '2009-12-29') are by default filled with ``NaN``.
If desired, we can fill in the missing values using one of several
options.
For example, to back-propagate the last valid value to fill the ``NaN``
values, pass ``bfill`` as an argument to the ``method`` keyword.
>>> df2.reindex(date_index2, method="bfill")
prices
2009-12-29 100.0
2009-12-30 100.0
2009-12-31 100.0
2010-01-01 100.0
2010-01-02 101.0
2010-01-03 NaN
2010-01-04 100.0
2010-01-05 89.0
2010-01-06 88.0
2010-01-07 NaN
Please note that the ``NaN`` value present in the original DataFrame
(at index value 2010-01-03) will not be filled by any of the
value propagation schemes. This is because filling while reindexing
does not look at DataFrame values, but only compares the original and
desired indexes. If you do want to fill in the ``NaN`` values present
in the original DataFrame, use the ``fillna()`` method.
See the :ref:`user guide <basics.reindexing>` for more.
"""
# TODO: Decide if we care about having different examples for different
# kinds
# Automatically detect matching level when reindexing from Index to MultiIndex.
# This prevents values from being incorrectly set to NaN when the source index
# name matches a index name in the target MultiIndex
if (
level is None
and index is not None
and isinstance(index, MultiIndex)
and not isinstance(self.index, MultiIndex)
and self.index.name in index.names
):
level = self.index.name
self._check_copy_deprecation(copy)
if index is not None and columns is not None and labels is not None:
raise TypeError("Cannot specify all of 'labels', 'index', 'columns'.")
elif index is not None or columns is not None:
if axis is not None:
raise TypeError(
"Cannot specify both 'axis' and any of 'index' or 'columns'"
)
if labels is not None:
if index is not None:
columns = labels
else:
index = labels
else:
if axis and self._get_axis_number(axis) == 1:
columns = labels
else:
index = labels
axes: dict[Literal["index", "columns"], Any] = {
"index": index,
"columns": columns,
}
method = clean_reindex_fill_method(method)
# if all axes that are requested to reindex are equal, then only copy
# if indicated must have index names equal here as well as values
if all(
self._get_axis(axis_name).identical(ax)
for axis_name, ax in axes.items()
if ax is not None
):
return self.copy(deep=False)
# check if we are a multi reindex
if self._needs_reindex_multi(axes, method, level):
return self._reindex_multi(axes, fill_value)
# perform the reindex on the axes
return self._reindex_axes(
axes, level, limit, tolerance, method, fill_value
).__finalize__(self, method="reindex")
@final
def _reindex_axes(
self,
axes,
level: Level | None,
limit: int | None,
tolerance,
method,
fill_value: Scalar | None,
) -> Self:
"""Perform the reindex for all the axes."""
obj = self
for a in self._AXIS_ORDERS:
labels = axes[a]
if labels is None:
continue
ax = self._get_axis(a)
new_index, indexer = ax.reindex(
labels, level=level, limit=limit, tolerance=tolerance, method=method
)
axis = self._get_axis_number(a)
obj = obj._reindex_with_indexers(
{axis: [new_index, indexer]},
fill_value=fill_value,
allow_dups=False,
)
return obj
def _needs_reindex_multi(self, axes, method, level: Level | None) -> bool:
"""Check if we do need a multi reindex."""
return (
(common.count_not_none(*axes.values()) == self._AXIS_LEN)
and method is None
and level is None
# reindex_multi calls self.values, so we only want to go
# down that path when doing so is cheap.
and self._can_fast_transpose
)
def _reindex_multi(self, axes, fill_value):
raise AbstractMethodError(self)
@final
def _reindex_with_indexers(
self,
reindexers,
fill_value=None,
allow_dups: bool = False,
) -> Self:
"""allow_dups indicates an internal call here"""
# reindex doing multiple operations on different axes if indicated
new_data = self._mgr
for axis in sorted(reindexers.keys()):
index, indexer = reindexers[axis]
baxis = self._get_block_manager_axis(axis)
if index is None:
continue
index = ensure_index(index)
if indexer is not None:
indexer = ensure_platform_int(indexer)
# TODO: speed up on homogeneous DataFrame objects (see _reindex_multi)
new_data = new_data.reindex_indexer(
index,
indexer,
axis=baxis,
fill_value=fill_value,
allow_dups=allow_dups,
)
if new_data is self._mgr:
new_data = new_data.copy(deep=False)
return self._constructor_from_mgr(new_data, axes=new_data.axes).__finalize__(
self
)
def filter(
self,
items=None,
like: str | None = None,
regex: str | None = None,
axis: Axis | None = None,
) -> Self:
"""
Subset the DataFrame or Series according to the specified index labels.
For DataFrame, filter rows or columns depending on ``axis`` argument.
Note that this routine does not filter based on content.
The filter is applied to the labels of the index.
Parameters
----------
items : list-like
Keep labels from axis which are in items.
like : str
Keep labels from axis for which "like in label == True".
regex : str (regular expression)
Keep labels from axis for which re.search(regex, label) == True.
axis : {0 or 'index', 1 or 'columns', None}, default None
The axis to filter on, expressed either as an index (int)
or axis name (str). By default this is the info axis, 'columns' for
``DataFrame``. For ``Series`` this parameter is unused and defaults to
``None``.
Returns
-------
Same type as caller
The filtered subset of the DataFrame or Series.
See Also
--------
DataFrame.loc : Access a group of rows and columns
by label(s) or a boolean array.
Notes
-----
The ``items``, ``like``, and ``regex`` parameters are
enforced to be mutually exclusive.
``axis`` defaults to the info axis that is used when indexing
with ``[]``.
Examples
--------
>>> df = pd.DataFrame(
... np.array(([1, 2, 3], [4, 5, 6])),
... index=["mouse", "rabbit"],
... columns=["one", "two", "three"],
... )
>>> df
one two three
mouse 1 2 3
rabbit 4 5 6
>>> # select columns by name
>>> df.filter(items=["one", "three"])
one three
mouse 1 3
rabbit 4 6
>>> # select columns by regular expression
>>> df.filter(regex="e$", axis=1)
one three
mouse 1 3
rabbit 4 6
>>> # select rows containing 'bbi'
>>> df.filter(like="bbi", axis=0)
one two three
rabbit 4 5 6
"""
nkw = common.count_not_none(items, like, regex)
if nkw > 1:
raise TypeError(
"Keyword arguments `items`, `like`, or `regex` are mutually exclusive"
)
if axis is None:
axis = self._info_axis_name
labels = self._get_axis(axis)
if items is not None:
name = self._get_axis_name(axis)
items = Index(items).intersection(labels)
if len(items) == 0:
# Keep the dtype of labels when we are empty
items = items.astype(labels.dtype)
# error: Keywords must be strings
return self.reindex(**{name: items}) # type: ignore[misc]
elif like:
def f(x) -> bool:
assert like is not None # needed for mypy
return like in ensure_str(x)
values = labels.map(f)
return self.loc(axis=axis)[values]
elif regex:
def f(x) -> bool:
return matcher.search(ensure_str(x)) is not None
matcher = re.compile(regex)
values = labels.map(f)
return self.loc(axis=axis)[values]
else:
raise TypeError("Must pass either `items`, `like`, or `regex`")
@final
def head(self, n: int = 5) -> Self:
"""
Return the first `n` rows.
This function exhibits the same behavior as ``df[:n]``, returning the
first ``n`` rows based on position. It is useful for quickly checking
if your object has the right type of data in it.
When ``n`` is positive, it returns the first ``n`` rows. For ``n`` equal to 0,
it returns an empty object. When ``n`` is negative, it returns
all rows except the last ``|n|`` rows, mirroring the behavior of ``df[:n]``.
If ``n`` is larger than the number of rows, this function returns all rows.
Parameters
----------
n : int, default 5
Number of rows to select.
Returns
-------
same type as caller
The first `n` rows of the caller object.
See Also
--------
DataFrame.tail: Returns the last `n` rows.
Examples
--------
>>> df = pd.DataFrame(
... {
... "animal": [
... "alligator",
... "bee",
... "falcon",
... "lion",
... "monkey",
... "parrot",
... "shark",
... "whale",
... "zebra",
... ]
... }
... )
>>> df
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
5 parrot
6 shark
7 whale
8 zebra
Viewing the first 5 lines
>>> df.head()
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
Viewing the first `n` lines (three in this case)
>>> df.head(3)
animal
0 alligator
1 bee
2 falcon
For negative values of `n`
>>> df.head(-3)
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
5 parrot
"""
return self.iloc[:n].copy()
@final
def tail(self, n: int = 5) -> Self:
"""
Return the last `n` rows.
This function returns last `n` rows from the object based on
position. It is useful for quickly verifying data, for example,
after sorting or appending rows.
For negative values of `n`, this function returns all rows except
the first `|n|` rows, equivalent to ``df[|n|:]``.
If ``n`` is larger than the number of rows, this function returns all rows.
Parameters
----------
n : int, default 5
Number of rows to select.
Returns
-------
type of caller
The last `n` rows of the caller object.
See Also
--------
DataFrame.head : The first `n` rows of the caller object.
Examples
--------
>>> df = pd.DataFrame(
... {
... "animal": [
... "alligator",
... "bee",
... "falcon",
... "lion",
... "monkey",
... "parrot",
... "shark",
... "whale",
... "zebra",
... ]
... }
... )
>>> df
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
5 parrot
6 shark
7 whale
8 zebra
Viewing the last 5 lines
>>> df.tail()
animal
4 monkey
5 parrot
6 shark
7 whale
8 zebra
Viewing the last `n` lines (three in this case)
>>> df.tail(3)
animal
6 shark
7 whale
8 zebra
For negative values of `n`
>>> df.tail(-3)
animal
3 lion
4 monkey
5 parrot
6 shark
7 whale
8 zebra
"""
if n == 0:
return self.iloc[0:0].copy()
return self.iloc[-n:].copy()
@final
def sample(
self,
n: int | None = None,
frac: float | None = None,
replace: bool = False,
weights=None,
random_state: RandomState | None = None,
axis: Axis | None = None,
ignore_index: bool = False,
) -> Self:
"""
Return a random sample of items from an axis of object.
You can use `random_state` for reproducibility.
Parameters
----------
n : int, optional
Number of items from axis to return. Cannot be used with `frac`.
Default = 1 if `frac` = None.
frac : float, optional
Fraction of axis items to return. Cannot be used with `n`.
replace : bool, default False
Allow or disallow sampling of the same row more than once.
weights : str or ndarray-like, optional
Default ``None`` results in equal probability weighting.
If passed a Series, will align with target object on index. Index
values in weights not found in sampled object will be ignored and
index values in sampled object not in weights will be assigned
weights of zero.
If called on a DataFrame, will accept the name of a column
when axis = 0.
Unless weights are a Series, weights must be same length as axis
being sampled.
If weights do not sum to 1, they will be normalized to sum to 1.
Missing values in the weights column will be treated as zero.
Infinite values not allowed.
When replace = False will not allow ``(n * max(weights) / sum(weights)) > 1``
in order to avoid biased results. See the Notes below for more details.
random_state : int, array-like, BitGenerator, np.random.RandomState, np.random.Generator, optional
If int, array-like, or BitGenerator, seed for random number generator.
If np.random.RandomState or np.random.Generator, use as given.
Default ``None`` results in sampling with the current state of np.random.
axis : {0 or 'index', 1 or 'columns', None}, default None
Axis to sample. Accepts axis number or name. Default is stat axis
for given data type. For `Series` this parameter is unused and defaults to `None`.
ignore_index : bool, default False
If True, the resulting index will be labeled 0, 1, …, n - 1.
Returns
-------
Series or DataFrame
A new object of same type as caller containing `n` items randomly
sampled from the caller object.
See Also
--------
DataFrameGroupBy.sample: Generates random samples from each group of a
DataFrame object.
SeriesGroupBy.sample: Generates random samples from each group of a
Series object.
numpy.random.choice: Generates a random sample from a given 1-D numpy
array.
Notes
-----
If `frac` > 1, `replacement` should be set to `True`.
When replace = False will not allow ``(n * max(weights) / sum(weights)) > 1``,
since that would cause results to be biased. E.g. sampling 2 items without replacement
with weights [100, 1, 1] would yield two last items in 1/2 of cases, instead of 1/102.
This is similar to specifying `n=4` without replacement on a Series with 3 elements.
Examples
--------
>>> df = pd.DataFrame(
... {
... "num_legs": [2, 4, 8, 0],
... "num_wings": [2, 0, 0, 0],
... "num_specimen_seen": [10, 2, 1, 8],
... },
... index=["falcon", "dog", "spider", "fish"],
... )
>>> df
num_legs num_wings num_specimen_seen
falcon 2 2 10
dog 4 0 2
spider 8 0 1
fish 0 0 8
Extract 3 random elements from the ``Series`` ``df['num_legs']``:
Note that we use `random_state` to ensure the reproducibility of
the examples.
>>> df["num_legs"].sample(n=3, random_state=1)
fish 0
spider 8
falcon 2
Name: num_legs, dtype: int64
A random 50% sample of the ``DataFrame`` with replacement:
>>> df.sample(frac=0.5, replace=True, random_state=1)
num_legs num_wings num_specimen_seen
dog 4 0 2
fish 0 0 8
An upsample sample of the ``DataFrame`` with replacement:
Note that `replace` parameter has to be `True` for `frac` parameter > 1.
>>> df.sample(frac=2, replace=True, random_state=1)
num_legs num_wings num_specimen_seen
dog 4 0 2
fish 0 0 8
falcon 2 2 10
falcon 2 2 10
fish 0 0 8
dog 4 0 2
fish 0 0 8
dog 4 0 2
Using a DataFrame column as weights. Rows with larger value in the
`num_specimen_seen` column are more likely to be sampled.
>>> df.sample(n=2, weights="num_specimen_seen", random_state=1)
num_legs num_wings num_specimen_seen
falcon 2 2 10
fish 0 0 8
""" # noqa: E501
if axis is None:
axis = 0
axis = self._get_axis_number(axis)
obj_len = self.shape[axis]
# Process random_state argument
rs = common.random_state(random_state)
size = sample.process_sampling_size(n, frac, replace)
if size is None:
assert frac is not None
size = round(frac * obj_len)
if weights is not None:
weights = sample.preprocess_weights(self, weights, axis)
sampled_indices = sample.sample(obj_len, size, replace, weights, rs)
result = self.take(sampled_indices, axis=axis)
if ignore_index:
result.index = default_index(len(result))
return result
@overload
def pipe(
self,
func: Callable[Concatenate[Self, P], T],
*args: P.args,
**kwargs: P.kwargs,
) -> T: ...
@overload
def pipe(
self,
func: tuple[Callable[..., T], str],
*args: Any,
**kwargs: Any,
) -> T: ...
@final
@doc(klass=_shared_doc_kwargs["klass"])
def pipe(
self,
func: Callable[Concatenate[Self, P], T] | tuple[Callable[..., T], str],
*args: Any,
**kwargs: Any,
) -> T:
r"""
Apply chainable functions that expect Series or DataFrames.
Parameters
----------
func : function
Function to apply to the {klass}.
``args``, and ``kwargs`` are passed into ``func``.
Alternatively a ``(callable, data_keyword)`` tuple where
``data_keyword`` is a string indicating the keyword of
``callable`` that expects the {klass}.
*args : iterable, optional
Positional arguments passed into ``func``.
**kwargs : mapping, optional
A dictionary of keyword arguments passed into ``func``.
Returns
-------
The return type of ``func``.
The result of applying ``func`` to the Series or DataFrame.
See Also
--------
DataFrame.apply : Apply a function along input axis of DataFrame.
DataFrame.map : Apply a function elementwise on a whole DataFrame.
Series.map : Apply a mapping correspondence on a
:class:`~pandas.Series`.
Notes
-----
Use ``.pipe`` when chaining together functions that expect
Series, DataFrames or GroupBy objects.
Examples
--------
Constructing an income DataFrame from a dictionary.
>>> data = [[8000, 1000], [9500, np.nan], [5000, 2000]]
>>> df = pd.DataFrame(data, columns=["Salary", "Others"])
>>> df
Salary Others
0 8000 1000.0
1 9500 NaN
2 5000 2000.0
Functions that perform tax reductions on an income DataFrame.
>>> def subtract_federal_tax(df):
... return df * 0.9
>>> def subtract_state_tax(df, rate):
... return df * (1 - rate)
>>> def subtract_national_insurance(df, rate, rate_increase):
... new_rate = rate + rate_increase
... return df * (1 - new_rate)
Instead of writing
>>> subtract_national_insurance(
... subtract_state_tax(subtract_federal_tax(df), rate=0.12),
... rate=0.05,
... rate_increase=0.02,
... ) # doctest: +SKIP
You can write
>>> (
... df.pipe(subtract_federal_tax)
... .pipe(subtract_state_tax, rate=0.12)
... .pipe(subtract_national_insurance, rate=0.05, rate_increase=0.02)
... )
Salary Others
0 5892.48 736.56
1 6997.32 NaN
2 3682.80 1473.12
If you have a function that takes the data as (say) the second
argument, pass a tuple indicating which keyword expects the
data. For example, suppose ``national_insurance`` takes its data as ``df``
in the second argument:
>>> def subtract_national_insurance(rate, df, rate_increase):
... new_rate = rate + rate_increase
... return df * (1 - new_rate)
>>> (
... df.pipe(subtract_federal_tax)
... .pipe(subtract_state_tax, rate=0.12)
... .pipe(
... (subtract_national_insurance, "df"), rate=0.05, rate_increase=0.02
... )
... )
Salary Others
0 5892.48 736.56
1 6997.32 NaN
2 3682.80 1473.12
"""
return common.pipe(self.copy(deep=False), func, *args, **kwargs)
# ----------------------------------------------------------------------
# Attribute access
@final
def __finalize__(self, other, method: str | None = None, **kwargs) -> Self:
"""
Propagate metadata from other to self.
This is the default implementation. Subclasses may override this method to
implement their own metadata handling.
Parameters
----------
other : the object from which to get the attributes that we are going
to propagate. If ``other`` has an ``input_objs`` attribute, then
this attribute must contain an iterable of objects, each with an
``attrs`` attribute.
method : str, optional
A passed method name providing context on where ``__finalize__``
was called.
.. warning::
The value passed as `method` are not currently considered
stable across pandas releases.
Notes
-----
In case ``other`` has an ``input_objs`` attribute, this method only
propagates its metadata if each object in ``input_objs`` has the exact
same metadata as the others.
"""
if isinstance(other, NDFrame):
if other.attrs:
# We want attrs propagation to have minimal performance
# impact if attrs are not used; i.e. attrs is an empty dict.
# One could make the deepcopy unconditionally, but a deepcopy
# of an empty dict is 50x more expensive than the empty check.
self.attrs = deepcopy(other.attrs)
self.flags.allows_duplicate_labels = (
self.flags.allows_duplicate_labels
and other.flags.allows_duplicate_labels
)
# For subclasses using _metadata.
for name in set(self._metadata) & set(other._metadata):
assert isinstance(name, str)
object.__setattr__(self, name, getattr(other, name, None))
elif hasattr(other, "input_objs"):
objs = other.input_objs
# propagate attrs only if all inputs have the same attrs
if all(bool(obj.attrs) for obj in objs):
# all inputs have non-empty attrs
attrs = objs[0].attrs
have_same_attrs = all(obj.attrs == attrs for obj in objs[1:])
if have_same_attrs:
self.attrs = deepcopy(attrs)
allows_duplicate_labels = all(x.flags.allows_duplicate_labels for x in objs)
self.flags.allows_duplicate_labels = allows_duplicate_labels
return self
@final
def __getattr__(self, name: str):
"""
After regular attribute access, try looking up the name
This allows simpler access to columns for interactive use.
"""
# Note: obj.x will always call obj.__getattribute__('x') prior to
# calling obj.__getattr__('x').
if (
name not in self._internal_names_set
and name not in self._metadata
and name not in self._accessors
and self._info_axis._can_hold_identifiers_and_holds_name(name)
):
return self[name]
return object.__getattribute__(self, name)
@final
def __setattr__(self, name: str, value) -> None:
"""
After regular attribute access, try setting the name
This allows simpler access to columns for interactive use.
"""
# first try regular attribute access via __getattribute__, so that
# e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify
# the same attribute.
try:
object.__getattribute__(self, name)
return object.__setattr__(self, name, value)
except AttributeError:
pass
# if this fails, go on to more involved attribute setting
# (note that this matches __getattr__, above).
if name in self._internal_names_set:
object.__setattr__(self, name, value)
elif name in self._metadata:
object.__setattr__(self, name, value)
else:
try:
existing = getattr(self, name)
if isinstance(existing, Index):
object.__setattr__(self, name, value)
elif name in self._info_axis:
self[name] = value
else:
object.__setattr__(self, name, value)
except (AttributeError, TypeError):
if isinstance(self, ABCDataFrame) and (is_list_like(value)):
warnings.warn(
"Pandas doesn't allow columns to be "
"created via a new attribute name - see "
"https://pandas.pydata.org/pandas-docs/"
"stable/indexing.html#attribute-access",
stacklevel=find_stack_level(),
)
object.__setattr__(self, name, value)
@final
def _dir_additions(self) -> set[str]:
"""
add the string-like attributes from the info_axis.
If info_axis is a MultiIndex, its first level values are used.
"""
additions = super()._dir_additions()
if self._info_axis._can_hold_strings:
additions.update(self._info_axis._dir_additions_for_owner)
return additions
# ----------------------------------------------------------------------
# Consolidation of internals
@final
def _consolidate_inplace(self) -> None:
"""Consolidate data in place and return None"""
self._mgr = self._mgr.consolidate()
@final
def _consolidate(self):
"""
Compute NDFrame with "consolidated" internals (data of each dtype
grouped together in a single ndarray).
Returns
-------
consolidated : same type as caller
"""
cons_data = self._mgr.consolidate()
return self._constructor_from_mgr(cons_data, axes=cons_data.axes).__finalize__(
self
)
@final
@property
def _is_mixed_type(self) -> bool:
if self._mgr.is_single_block:
# Includes all Series cases
return False
if self._mgr.any_extension_types:
# Even if they have the same dtype, we can't consolidate them,
# so we pretend this is "mixed'"
return True
return self.dtypes.nunique() > 1
@final
def _get_numeric_data(self) -> Self:
new_mgr = self._mgr.get_numeric_data()
return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__(self)
@final
def _get_bool_data(self):
new_mgr = self._mgr.get_bool_data()
return self._constructor_from_mgr(new_mgr, axes=new_mgr.axes).__finalize__(self)
# ----------------------------------------------------------------------
# Internal Interface Methods
@property
def values(self):
raise AbstractMethodError(self)
@property
def _values(self) -> ArrayLike:
"""internal implementation"""
raise AbstractMethodError(self)
@property
def dtypes(self):
"""
Return the dtypes in the DataFrame.
This returns a Series with the data type of each column.
The result's index is the original DataFrame's columns. Columns
with mixed types are stored with the ``object`` dtype. See
:ref:`the User Guide <basics.dtypes>` for more.
Returns
-------
pandas.Series
The data type of each column.
See Also
--------
Series.dtypes : Return the dtype object of the underlying data.
Examples
--------
>>> df = pd.DataFrame(
... {
... "float": [1.0],
... "int": [1],
... "datetime": [pd.Timestamp("20180310")],
... "string": ["foo"],
... }
... )
>>> df.dtypes
float float64
int int64
datetime datetime64[us]
string str
dtype: object
"""
data = self._mgr.get_dtypes()
return self._constructor_sliced(data, index=self._info_axis, dtype=np.object_)
@final
def astype(
self,
dtype,
copy: bool | lib.NoDefault = lib.no_default,
errors: IgnoreRaise = "raise",
) -> Self:
"""
Cast a pandas object to a specified dtype ``dtype``.
This method allows the conversion of the data types of pandas objects,
including DataFrames and Series, to the specified dtype. It supports casting
entire objects to a single data type or applying different data types to
individual columns using a mapping.
Parameters
----------
dtype : str, data type, Series or Mapping of column name -> data type
Use a str, numpy.dtype, pandas.ExtensionDtype or Python type to
cast entire pandas object to the same type. Alternatively, use a
mapping, e.g. {col: dtype, ...}, where col is a column label and dtype is
a numpy.dtype or Python type to cast one or more of the DataFrame's
columns to column-specific types.
copy : bool, default False
Return a copy when ``copy=True`` (be very careful setting
``copy=False`` as changes to values then may propagate to other
pandas objects).
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
errors : {'raise', 'ignore'}, default 'raise'
Control raising of exceptions on invalid data for provided dtype.
- ``raise`` : allow exceptions to be raised
- ``ignore`` : suppress exceptions. On error return original object.
Returns
-------
same type as caller
The pandas object casted to the specified ``dtype``.
See Also
--------
to_datetime : Convert argument to datetime.
to_timedelta : Convert argument to timedelta.
to_numeric : Convert argument to a numeric type.
numpy.ndarray.astype : Cast a numpy array to a specified type.
Notes
-----
.. versionchanged:: 2.0.0
Using ``astype`` to convert from timezone-naive dtype to
timezone-aware dtype will raise an exception.
Use :meth:`Series.dt.tz_localize` instead.
Examples
--------
Create a DataFrame:
>>> d = {"col1": [1, 2], "col2": [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df.dtypes
col1 int64
col2 int64
dtype: object
Cast all columns to int32:
>>> df.astype("int32").dtypes
col1 int32
col2 int32
dtype: object
Cast col1 to int32 using a dictionary:
>>> df.astype({"col1": "int32"}).dtypes
col1 int32
col2 int64
dtype: object
Create a series:
>>> ser = pd.Series([1, 2], dtype="int32")
>>> ser
0 1
1 2
dtype: int32
>>> ser.astype("int64")
0 1
1 2
dtype: int64
Convert to categorical type:
>>> ser.astype("category")
0 1
1 2
dtype: category
Categories (2, int32): [1, 2]
Convert to ordered categorical type with custom ordering:
>>> from pandas.api.types import CategoricalDtype
>>> cat_dtype = CategoricalDtype(categories=[2, 1], ordered=True)
>>> ser.astype(cat_dtype)
0 1
1 2
dtype: category
Categories (2, int64): [2 < 1]
Create a series of dates:
>>> ser_date = pd.Series(pd.date_range("20200101", periods=3))
>>> ser_date
0 2020-01-01
1 2020-01-02
2 2020-01-03
dtype: datetime64[us]
"""
self._check_copy_deprecation(copy)
if is_dict_like(dtype):
if self.ndim == 1: # i.e. Series
if len(dtype) > 1 or self.name not in dtype:
raise KeyError(
"Only the Series name can be used for "
"the key in Series dtype mappings."
)
new_type = dtype[self.name]
return self.astype(new_type, errors=errors)
# GH#44417 cast to Series so we can use .iat below, which will be
# robust in case we
from pandas import Series
dtype_ser = Series(dtype, dtype=object)
for col_name in dtype_ser.index:
if col_name not in self:
raise KeyError(
"Only a column name can be used for the "
"key in a dtype mappings argument. "
f"'{col_name}' not found in columns."
)
dtype_ser = dtype_ser.reindex(self.columns, fill_value=None)
results = []
for i, (col_name, col) in enumerate(self.items()):
cdt = dtype_ser.iat[i]
if isna(cdt):
res_col = col.copy(deep=False)
else:
try:
res_col = col.astype(dtype=cdt, errors=errors)
except ValueError as ex:
ex.args = (
f"{ex}: Error while type casting for column '{col_name}'",
)
raise
results.append(res_col)
elif is_extension_array_dtype(dtype) and self.ndim > 1:
# TODO(EA2D): special case not needed with 2D EAs
dtype = pandas_dtype(dtype)
if isinstance(dtype, ExtensionDtype) and all(
block.values.dtype == dtype for block in self._mgr.blocks
):
return self.copy(deep=False)
# GH 18099/22869: columnwise conversion to extension dtype
# GH 24704: self.items handles duplicate column names
results = [ser.astype(dtype, errors=errors) for _, ser in self.items()]
else:
# else, only a single dtype is given
new_data = self._mgr.astype(dtype=dtype, errors=errors)
res = self._constructor_from_mgr(new_data, axes=new_data.axes)
return res.__finalize__(self, method="astype")
# GH 33113: handle empty frame or series
if not results:
return self.copy(deep=False)
# GH 19920: retain column metadata after concat
result = concat(results, axis=1)
# GH#40810 retain subclass
# error: Incompatible types in assignment
# (expression has type "Self", variable has type "DataFrame")
result = self._constructor(result) # type: ignore[assignment]
result.columns = self.columns
result = result.__finalize__(self, method="astype")
# https://github.com/python/mypy/issues/8354
return cast(Self, result)
@final
def copy(self, deep: bool = True) -> Self:
"""
Make a copy of this object's indices and data.
When ``deep=True`` (default), a new object will be created with a
copy of the calling object's data and indices. Modifications to
the data or indices of the copy will not be reflected in the
original object (see notes below).
When ``deep=False``, a new object will be created without copying
the calling object's data or index (only references to the data
and index are copied). Any changes to the data of the original
will be reflected in the shallow copy (and vice versa).
.. note::
The ``deep=False`` behaviour as described above will change
in pandas 3.0. `Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that the "shallow" copy
is that is returned with ``deep=False`` will still avoid making
an eager copy, but changes to the data of the original will *no*
longer be reflected in the shallow copy (or vice versa). Instead,
it makes use of a lazy (deferred) copy mechanism that will copy
the data only when any changes to the original or shallow copy is
made.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
Parameters
----------
deep : bool, default True
Make a deep copy, including a copy of the data and the indices.
With ``deep=False`` neither the indices nor the data are copied.
Returns
-------
Series or DataFrame
Object type matches caller.
See Also
--------
copy.copy : Return a shallow copy of an object.
copy.deepcopy : Return a deep copy of an object.
Notes
-----
When ``deep=True``, data is copied but actual Python objects
will not be copied recursively, only the reference to the object.
This is in contrast to `copy.deepcopy` in the Standard Library,
which recursively copies object data (see examples below).
While ``Index`` objects are copied when ``deep=True``, the underlying
numpy array is not copied for performance reasons. Since ``Index`` is
immutable, the underlying data can be safely shared and a copy
is not needed.
Since pandas is not thread safe, see the
:ref:`gotchas <gotchas.thread-safety>` when copying in a threading
environment.
Copy-on-Write protects shallow copies against accidental modifications.
This means that any changes to the copied data would make a new copy
of the data upon write (and vice versa). Changes made to either the
original or copied variable would not be reflected in the counterpart.
See :ref:`Copy_on_Write <copy_on_write>` for more information.
Examples
--------
>>> s = pd.Series([1, 2], index=["a", "b"])
>>> s
a 1
b 2
dtype: int64
>>> s_copy = s.copy()
>>> s_copy
a 1
b 2
dtype: int64
**Shallow copy versus default (deep) copy:**
>>> s = pd.Series([1, 2], index=["a", "b"])
>>> deep = s.copy()
>>> shallow = s.copy(deep=False)
Shallow copy shares index with original, the data is a
view of the original.
>>> s is shallow
False
>>> s.values is shallow.values
False
>>> s.index is shallow.index
False
Deep copy has own copy of data and index.
>>> s is deep
False
>>> s.values is deep.values or s.index is deep.index
False
The shallow copy is protected against updating the original object
as well. Thus, updates will only reflect in one of both objects.
>>> s.iloc[0] = 3
>>> shallow.iloc[1] = 4
>>> s
a 3
b 2
dtype: int64
>>> shallow
a 1
b 4
dtype: int64
>>> deep
a 1
b 2
dtype: int64
Note that when copying an object containing Python objects, a deep copy
will copy the data, but will not do so recursively. Updating a nested
data object will be reflected in the deep copy.
>>> s = pd.Series([[1, 2], [3, 4]])
>>> deep = s.copy()
>>> s[0][0] = 10
>>> s
0 [10, 2]
1 [3, 4]
dtype: object
>>> deep
0 [10, 2]
1 [3, 4]
dtype: object
"""
data = self._mgr.copy(deep=deep)
return self._constructor_from_mgr(data, axes=data.axes).__finalize__(
self, method="copy"
)
@final
def __copy__(self) -> Self:
return self.copy(deep=False)
@final
def __deepcopy__(self, memo=None) -> Self:
"""
Parameters
----------
memo, default None
Standard signature. Unused
"""
return self.copy(deep=True)
@final
def infer_objects(self, copy: bool | lib.NoDefault = lib.no_default) -> Self:
"""
Attempt to infer better dtypes for object columns.
Attempts soft conversion of object-dtyped
columns, leaving non-object and unconvertible
columns unchanged. The inference rules are the
same as during normal Series/DataFrame construction.
Parameters
----------
copy : bool, default False
Whether to make a copy for non-object or non-inferable columns
or Series.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
Returns
-------
same type as input object
Returns an object of the same type as the input object.
See Also
--------
to_datetime : Convert argument to datetime.
to_timedelta : Convert argument to timedelta.
to_numeric : Convert argument to numeric type.
convert_dtypes : Convert argument to best possible dtype.
Examples
--------
>>> df = pd.DataFrame({"A": ["a", 1, 2, 3]})
>>> df = df.iloc[1:]
>>> df
A
1 1
2 2
3 3
>>> df.dtypes
A object
dtype: object
>>> df.infer_objects().dtypes
A int64
dtype: object
"""
self._check_copy_deprecation(copy)
new_mgr = self._mgr.convert()
res = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
return res.__finalize__(self, method="infer_objects")
@final
def convert_dtypes(
self,
infer_objects: bool = True,
convert_string: bool = True,
convert_integer: bool = True,
convert_boolean: bool = True,
convert_floating: bool = True,
dtype_backend: DtypeBackend = "numpy_nullable",
) -> Self:
"""
Convert columns from numpy dtypes to the best dtypes that support ``pd.NA``.
Parameters
----------
infer_objects : bool, default True
Whether object dtypes should be converted to the best possible types.
convert_string : bool, default True
Whether object dtypes should be converted to ``StringDtype()``.
convert_integer : bool, default True
Whether, if possible, conversion can be done to integer extension types.
convert_boolean : bool, defaults True
Whether object dtypes should be converted to ``BooleanDtypes()``.
convert_floating : bool, defaults True
Whether, if possible, conversion can be done to floating extension types.
If `convert_integer` is also True, preference will be give to integer
dtypes if the floats can be faithfully casted to integers.
dtype_backend : {'numpy_nullable', 'pyarrow'}, default 'numpy_nullable'
Back-end data type applied to the resultant :class:`DataFrame` or
:class:`Series` (still experimental). Behaviour is as follows:
* ``"numpy_nullable"``: returns nullable-dtype-backed
:class:`DataFrame` or :class:`Serires`.
* ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype`
:class:`DataFrame` or :class:`Series`.
.. versionadded:: 2.0
Returns
-------
Series or DataFrame
Copy of input object with new dtype.
See Also
--------
infer_objects : Infer dtypes of objects.
to_datetime : Convert argument to datetime.
to_timedelta : Convert argument to timedelta.
to_numeric : Convert argument to a numeric type.
Notes
-----
By default, ``convert_dtypes`` will attempt to convert a Series (or each
Series in a DataFrame) to dtypes that support ``pd.NA``. By using the options
``convert_string``, ``convert_integer``, ``convert_boolean`` and
``convert_floating``, it is possible to turn off individual conversions
to ``StringDtype``, the integer extension types, ``BooleanDtype``
or floating extension types, respectively.
For object-dtyped columns, if ``infer_objects`` is ``True``, use the inference
rules as during normal Series/DataFrame construction. Then, if possible,
convert to ``StringDtype``, ``BooleanDtype`` or an appropriate integer
or floating extension type, otherwise leave as ``object``.
If the dtype is integer, convert to an appropriate integer extension type.
If the dtype is numeric, and consists of all integers, convert to an
appropriate integer extension type. Otherwise, convert to an
appropriate floating extension type.
In the future, as new dtypes are added that support ``pd.NA``, the results
of this method will change to support those new dtypes.
Examples
--------
>>> df = pd.DataFrame(
... {
... "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
... "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
... "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
... "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
... "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
... "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
... }
... )
Start with a DataFrame with default dtypes.
>>> df
a b c d e f
0 1 x True h 10.0 NaN
1 2 y False i NaN 100.5
2 3 z NaN NaN 20.0 200.0
>>> df.dtypes
a int32
b object
c object
d object
e float64
f float64
dtype: object
Convert the DataFrame to use best possible dtypes.
>>> dfn = df.convert_dtypes()
>>> dfn
a b c d e f
0 1 x True h 10 <NA>
1 2 y False i <NA> 100.5
2 3 z <NA> <NA> 20 200.0
>>> dfn.dtypes
a Int32
b string
c boolean
d string
e Int64
f Float64
dtype: object
Start with a Series of strings and missing data represented by ``np.nan``.
>>> s = pd.Series(["a", "b", np.nan])
>>> s
0 a
1 b
2 NaN
dtype: str
Obtain a Series with dtype ``StringDtype``.
>>> s.convert_dtypes()
0 a
1 b
2 <NA>
dtype: string
"""
check_dtype_backend(dtype_backend)
new_mgr = self._mgr.convert_dtypes(
infer_objects=infer_objects,
convert_string=convert_string,
convert_integer=convert_integer,
convert_boolean=convert_boolean,
convert_floating=convert_floating,
dtype_backend=dtype_backend,
)
res = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
return res.__finalize__(self, method="convert_dtypes")
# ----------------------------------------------------------------------
# Filling NA's
@final
def _pad_or_backfill(
self,
method: Literal["ffill", "bfill", "pad", "backfill"],
*,
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
limit_area: Literal["inside", "outside"] | None = None,
):
if axis is None:
axis = 0
axis = self._get_axis_number(axis)
method = clean_fill_method(method)
if axis == 1:
if not self._mgr.is_single_block and inplace:
raise NotImplementedError
# e.g. test_align_fill_method
result = self.T._pad_or_backfill(
method=method, limit=limit, limit_area=limit_area
).T
return result
new_mgr = self._mgr.pad_or_backfill(
method=method,
limit=limit,
limit_area=limit_area,
inplace=inplace,
)
result = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
if inplace:
self._update_inplace(result)
return self
else:
return result.__finalize__(self, method="fillna")
@final
@doc(
klass=_shared_doc_kwargs["klass"],
axes_single_arg=_shared_doc_kwargs["axes_single_arg"],
)
def fillna(
self,
value: Hashable | Mapping | Series | DataFrame,
*,
axis: Axis | None = None,
inplace: bool = False,
limit: int | None = None,
) -> Self:
"""
Fill NA/NaN values with `value`.
Parameters
----------
value : scalar, dict, Series, or DataFrame
Value to use to fill holes (e.g. 0), alternately a
dict/Series/DataFrame of values specifying which value to use for
each index (for a Series) or column (for a DataFrame). Values not
in the dict/Series/DataFrame will not be filled. This value cannot
be a list.
axis : {axes_single_arg}
Axis along which to fill missing values. For `Series`
this parameter is unused and defaults to 0.
inplace : bool, default False
If True, fill in-place. Note: this will modify any
other views on this object (e.g., a no-copy slice for a column in a
DataFrame).
limit : int, default None
This is the maximum number of entries along the entire axis
where NaNs will be filled. Must be greater than 0 if not None.
Returns
-------
{klass}
Object with missing values filled.
See Also
--------
ffill : Fill values by propagating the last valid observation to next valid.
bfill : Fill values by using the next valid observation to fill the gap.
interpolate : Fill NaN values using interpolation.
reindex : Conform object to new index.
asfreq : Convert TimeSeries to specified frequency.
Notes
-----
For non-object dtype, ``value=None`` will use the NA value of the dtype.
See more details in the :ref:`Filling missing data<missing_data.fillna>`
section.
Examples
--------
>>> df = pd.DataFrame(
... [
... [np.nan, 2, np.nan, 0],
... [3, 4, np.nan, 1],
... [np.nan, np.nan, np.nan, np.nan],
... [np.nan, 3, np.nan, 4],
... ],
... columns=list("ABCD"),
... )
>>> df
A B C D
0 NaN 2.0 NaN 0.0
1 3.0 4.0 NaN 1.0
2 NaN NaN NaN NaN
3 NaN 3.0 NaN 4.0
Replace all NaN elements with 0s.
>>> df.fillna(0)
A B C D
0 0.0 2.0 0.0 0.0
1 3.0 4.0 0.0 1.0
2 0.0 0.0 0.0 0.0
3 0.0 3.0 0.0 4.0
Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,
2, and 3 respectively.
>>> values = {{"A": 0, "B": 1, "C": 2, "D": 3}}
>>> df.fillna(value=values)
A B C D
0 0.0 2.0 2.0 0.0
1 3.0 4.0 2.0 1.0
2 0.0 1.0 2.0 3.0
3 0.0 3.0 2.0 4.0
Only replace the first NaN element.
>>> df.fillna(value=values, limit=1)
A B C D
0 0.0 2.0 2.0 0.0
1 3.0 4.0 NaN 1.0
2 NaN 1.0 NaN 3.0
3 NaN 3.0 NaN 4.0
When filling using a DataFrame, replacement happens along
the same column names and same indices
>>> df2 = pd.DataFrame(np.zeros((4, 4)), columns=list("ABCE"))
>>> df.fillna(df2)
A B C D
0 0.0 2.0 0.0 0.0
1 3.0 4.0 0.0 1.0
2 0.0 0.0 0.0 NaN
3 0.0 3.0 0.0 4.0
Note that column D is not affected since it is not present in df2.
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
if isinstance(value, (list, tuple)):
raise TypeError(
'"value" parameter must be a scalar or dict, but '
f'you passed a "{type(value).__name__}"'
)
# set the default here, so functions examining the signature
# can detect if something was set (e.g. in groupby) (GH9221)
if axis is None:
axis = 0
axis = self._get_axis_number(axis)
if self.ndim == 1:
if isinstance(value, (dict, ABCSeries)):
if not len(value):
# test_fillna_nonscalar
return self if inplace else self.copy(deep=False)
from pandas import Series
value = Series(value)
value = value.reindex(self.index)
value = value._values
elif not is_list_like(value):
pass
else:
raise TypeError(
'"value" parameter must be a scalar, dict '
"or Series, but you passed a "
f'"{type(value).__name__}"'
)
new_data = self._mgr.fillna(value=value, limit=limit, inplace=inplace)
elif isinstance(value, (dict, ABCSeries)):
result = self if inplace else self.copy(deep=False)
if axis == 1:
# Check that all columns in result have the same dtype
# otherwise don't bother with fillna and losing accurate dtypes
unique_dtypes = algos.unique(self._mgr.get_dtypes())
if len(unique_dtypes) > 1:
raise ValueError(
"All columns must have the same dtype, but got dtypes: "
f"{list(unique_dtypes)}"
)
# Use the first column, which we have already validated has the
# same dtypes as the other columns.
if not can_hold_element(result.iloc[:, 0], value):
frame_dtype = unique_dtypes.item()
raise ValueError(
f"{value} not a suitable type to fill into {frame_dtype}"
)
result = result.T.fillna(value=value).T
if inplace:
self._update_inplace(result)
result = self
else:
for k, v in value.items():
if k not in result:
continue
res_k = result[k].fillna(v, limit=limit)
if not inplace:
result[k] = res_k
else:
# We can write into our existing column(s) iff dtype
# was preserved.
if isinstance(res_k, ABCSeries):
# i.e. 'k' only shows up once in self.columns
if res_k.dtype == result[k].dtype:
result.loc[:, k] = res_k
else:
# Different dtype -> no way to do inplace.
result[k] = res_k
else:
# see test_fillna_dict_inplace_nonunique_columns
locs = result.columns.get_loc(k)
if isinstance(locs, slice):
locs = range(self.shape[1])[locs]
elif (
isinstance(locs, np.ndarray) and locs.dtype.kind == "b"
):
locs = locs.nonzero()[0]
elif not (
isinstance(locs, np.ndarray) and locs.dtype.kind == "i"
):
# Should never be reached, but let's cover our bases
raise NotImplementedError(
"Unexpected get_loc result, please report a bug at "
"https://github.com/pandas-dev/pandas"
)
for i, loc in enumerate(locs):
res_loc = res_k.iloc[:, i]
target = self.iloc[:, loc]
if res_loc.dtype == target.dtype:
result.iloc[:, loc] = res_loc
else:
result.isetitem(loc, res_loc)
return result
elif not is_list_like(value):
if axis == 1:
result = self.T.fillna(value=value, limit=limit).T
new_data = result._mgr
else:
new_data = self._mgr.fillna(value=value, limit=limit, inplace=inplace)
elif isinstance(value, ABCDataFrame) and self.ndim == 2:
new_data = self.where(self.notna(), value)._mgr
else:
raise ValueError(f"invalid fill value with a {type(value)}")
result = self._constructor_from_mgr(new_data, axes=new_data.axes)
if inplace:
self._update_inplace(result)
return self
else:
return result.__finalize__(self, method="fillna")
@final
@doc(
klass=_shared_doc_kwargs["klass"],
axes_single_arg=_shared_doc_kwargs["axes_single_arg"],
)
def ffill(
self,
*,
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
limit_area: Literal["inside", "outside"] | None = None,
) -> Self:
"""
Fill NA/NaN values by propagating the last valid observation to next valid.
Parameters
----------
axis : {axes_single_arg}
Axis along which to fill missing values. For `Series`
this parameter is unused and defaults to 0.
inplace : bool, default False
If True, fill in-place. Note: this will modify any
other views on this object (e.g., a no-copy slice for a column in a
DataFrame).
limit : int, default None
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill. In other words, if there is
a gap with more than this number of consecutive NaNs, it will only
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled. Must be greater than 0 if not None.
limit_area : {{`None`, 'inside', 'outside'}}, default None
If limit is specified, consecutive NaNs will be filled with this
restriction.
* ``None``: No fill restriction.
* 'inside': Only fill NaNs surrounded by valid values
(interpolate).
* 'outside': Only fill NaNs outside valid values (extrapolate).
.. versionadded:: 2.2.0
Returns
-------
{klass}
Object with missing values filled.
See Also
--------
DataFrame.bfill : Fill NA/NaN values by using the next valid observation
to fill the gap.
Examples
--------
>>> df = pd.DataFrame(
... [
... [np.nan, 2, np.nan, 0],
... [3, 4, np.nan, 1],
... [np.nan, np.nan, np.nan, np.nan],
... [np.nan, 3, np.nan, 4],
... ],
... columns=list("ABCD"),
... )
>>> df
A B C D
0 NaN 2.0 NaN 0.0
1 3.0 4.0 NaN 1.0
2 NaN NaN NaN NaN
3 NaN 3.0 NaN 4.0
>>> df.ffill()
A B C D
0 NaN 2.0 NaN 0.0
1 3.0 4.0 NaN 1.0
2 3.0 4.0 NaN 1.0
3 3.0 3.0 NaN 4.0
>>> ser = pd.Series([1, np.nan, 2, 3])
>>> ser.ffill()
0 1.0
1 1.0
2 2.0
3 3.0
dtype: float64
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
return self._pad_or_backfill(
"ffill",
axis=axis,
inplace=inplace,
limit=limit,
limit_area=limit_area,
)
@final
@doc(
klass=_shared_doc_kwargs["klass"],
axes_single_arg=_shared_doc_kwargs["axes_single_arg"],
)
def bfill(
self,
*,
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
limit_area: Literal["inside", "outside"] | None = None,
) -> Self:
"""
Fill NA/NaN values by using the next valid observation to fill the gap.
Parameters
----------
axis : {axes_single_arg}
Axis along which to fill missing values. For `Series`
this parameter is unused and defaults to 0.
inplace : bool, default False
If True, fill in-place. Note: this will modify any
other views on this object (e.g., a no-copy slice for a column in a
DataFrame).
limit : int, default None
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill. In other words, if there is
a gap with more than this number of consecutive NaNs, it will only
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled. Must be greater than 0 if not None.
limit_area : {{`None`, 'inside', 'outside'}}, default None
If limit is specified, consecutive NaNs will be filled with this
restriction.
* ``None``: No fill restriction.
* 'inside': Only fill NaNs surrounded by valid values
(interpolate).
* 'outside': Only fill NaNs outside valid values (extrapolate).
.. versionadded:: 2.2.0
Returns
-------
{klass}
Object with missing values filled.
See Also
--------
DataFrame.ffill : Fill NA/NaN values by propagating the last valid
observation to next valid.
Examples
--------
For Series:
>>> s = pd.Series([1, None, None, 2])
>>> s.bfill()
0 1.0
1 2.0
2 2.0
3 2.0
dtype: float64
>>> s.bfill(limit=1)
0 1.0
1 NaN
2 2.0
3 2.0
dtype: float64
With DataFrame:
>>> df = pd.DataFrame({{"A": [1, None, None, 4], "B": [None, 5, None, 7]}})
>>> df
A B
0 1.0 NaN
1 NaN 5.0
2 NaN NaN
3 4.0 7.0
>>> df.bfill()
A B
0 1.0 5.0
1 4.0 5.0
2 4.0 7.0
3 4.0 7.0
>>> df.bfill(limit=1)
A B
0 1.0 5.0
1 NaN 5.0
2 4.0 7.0
3 4.0 7.0
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
return self._pad_or_backfill(
"bfill",
axis=axis,
inplace=inplace,
limit=limit,
limit_area=limit_area,
)
@final
@doc(
_shared_docs["replace"],
klass=_shared_doc_kwargs["klass"],
inplace=_shared_doc_kwargs["inplace"],
)
def replace(
self,
to_replace=None,
value=lib.no_default,
*,
inplace: bool = False,
regex: bool = False,
) -> Self:
if not is_bool(regex) and to_replace is not None:
raise ValueError("'to_replace' must be 'None' if 'regex' is not a bool")
if not (
is_scalar(to_replace)
or is_re_compilable(to_replace)
or is_list_like(to_replace)
):
raise TypeError(
"Expecting 'to_replace' to be either a scalar, array-like, "
"dict or None, got invalid type "
f"{type(to_replace).__name__!r}"
)
if value is lib.no_default and not (
is_dict_like(to_replace) or is_dict_like(regex)
):
raise ValueError(
# GH#33302
f"{type(self).__name__}.replace must specify either 'value', "
"a dict-like 'to_replace', or dict-like 'regex'."
)
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
if value is lib.no_default:
if not is_dict_like(to_replace):
# In this case we have checked above that
# 1) regex is dict-like and 2) to_replace is None
to_replace = regex
regex = True
items = list(to_replace.items())
if items:
keys, values = zip(*items, strict=True)
else:
keys, values = ([], []) # type: ignore[assignment]
are_mappings = [is_dict_like(v) for v in values]
if any(are_mappings):
if not all(are_mappings):
raise TypeError(
"If a nested mapping is passed, all values "
"of the top level mapping must be mappings"
)
# passed a nested dict/Series
to_rep_dict = {}
value_dict = {}
for k, v in items:
# error: Incompatible types in assignment (expression has type
# "list[Never]", variable has type "tuple[Any, ...]")
keys, values = list(zip(*v.items(), strict=True)) or ( # type: ignore[assignment]
[],
[],
)
to_rep_dict[k] = list(keys)
value_dict[k] = list(values)
to_replace, value = to_rep_dict, value_dict
else:
to_replace, value = keys, values
return self.replace(to_replace, value, inplace=inplace, regex=regex)
else:
# need a non-zero len on all axes
if not self.size:
return self if inplace else self.copy(deep=False)
if is_dict_like(to_replace):
if is_dict_like(value): # {'A' : NA} -> {'A' : 0}
if isinstance(self, ABCSeries):
raise ValueError(
"to_replace and value cannot be dict-like for "
"Series.replace"
)
# Note: Checking below for `in foo.keys()` instead of
# `in foo` is needed for when we have a Series and not dict
mapping = {
col: (to_replace[col], value[col])
for col in to_replace.keys()
if col in value.keys() and col in self
}
return self._replace_columnwise(mapping, inplace, regex)
# {'A': NA} -> 0
elif not is_list_like(value):
# Operate column-wise
if self.ndim == 1:
raise ValueError(
"Series.replace cannot specify both a dict-like "
"'to_replace' and a 'value'"
)
mapping = {
col: (to_rep, value) for col, to_rep in to_replace.items()
}
return self._replace_columnwise(mapping, inplace, regex)
else:
raise TypeError("value argument must be scalar, dict, or Series")
elif is_list_like(to_replace):
if not is_list_like(value):
# e.g. to_replace = [NA, ''] and value is 0,
# so we replace NA with 0 and then replace '' with 0
value = [value] * len(to_replace)
# e.g. we have to_replace = [NA, ''] and value = [0, 'missing']
if len(to_replace) != len(value):
raise ValueError(
f"Replacement lists must match in length. "
f"Expecting {len(to_replace)} got {len(value)} "
)
new_data = self._mgr.replace_list(
src_list=to_replace,
dest_list=value,
inplace=inplace,
regex=regex,
)
elif to_replace is None:
if not (
is_re_compilable(regex)
or is_list_like(regex)
or is_dict_like(regex)
):
raise TypeError(
f"'regex' must be a string or a compiled regular expression "
f"or a list or dict of strings or regular expressions, "
f"you passed a {type(regex).__name__!r}"
)
return self.replace(regex, value, inplace=inplace, regex=True)
else:
# dest iterable dict-like
if is_dict_like(value): # NA -> {'A' : 0, 'B' : -1}
# Operate column-wise
if self.ndim == 1:
raise ValueError(
"Series.replace cannot use dict-value and "
"non-None to_replace"
)
mapping = {col: (to_replace, val) for col, val in value.items()}
return self._replace_columnwise(mapping, inplace, regex)
elif not is_list_like(value): # NA -> 0
regex = should_use_regex(regex, to_replace)
if regex:
new_data = self._mgr.replace_regex(
to_replace=to_replace,
value=value,
inplace=inplace,
)
else:
new_data = self._mgr.replace(
to_replace=to_replace, value=value, inplace=inplace
)
else:
raise TypeError(
f'Invalid "to_replace" type: {type(to_replace).__name__!r}'
)
result = self._constructor_from_mgr(new_data, axes=new_data.axes)
if inplace:
self._update_inplace(result)
return self
else:
return result.__finalize__(self, method="replace")
@final
def interpolate(
self,
method: InterpolateOptions = "linear",
*,
axis: Axis = 0,
limit: int | None = None,
inplace: bool = False,
limit_direction: Literal["forward", "backward", "both"] | None = None,
limit_area: Literal["inside", "outside"] | None = None,
**kwargs,
) -> Self:
"""
Fill NaN values using an interpolation method.
Please note that only ``method='linear'`` is supported for
DataFrame/Series with a MultiIndex.
Parameters
----------
method : str, default 'linear'
Interpolation technique to use. One of:
* 'linear': Ignore the index and treat the values as equally
spaced. This is the only method supported on MultiIndexes.
* 'time': Works on daily and higher resolution data to interpolate
given length of interval. This interpolates values based on
time interval between observations.
* 'index': The interpolation uses the numerical values
of the DataFrame's index to linearly calculate missing values.
* 'values': Interpolation based on the numerical values
in the DataFrame, treating them as equally spaced along the index.
* 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
'barycentric', 'polynomial': Passed to
`scipy.interpolate.interp1d`, whereas 'spline' is passed to
`scipy.interpolate.UnivariateSpline`. These methods use the numerical
values of the index. Both 'polynomial' and 'spline' require that
you also specify an `order` (int), e.g.
``df.interpolate(method='polynomial', order=5)``. Note that,
`slinear` method in Pandas refers to the Scipy first order `spline`
instead of Pandas first order `spline`.
* 'krogh', 'piecewise_polynomial', 'spline', 'pchip', 'akima',
'cubicspline': Wrappers around the SciPy interpolation methods of
similar names. See `Notes`.
* 'from_derivatives': Refers to
`scipy.interpolate.BPoly.from_derivatives`.
axis : {{0 or 'index', 1 or 'columns', None}}, default None
Axis to interpolate along. For `Series` this parameter is unused
and defaults to 0.
limit : int, optional
Maximum number of consecutive NaNs to fill. Must be greater than
0.
inplace : bool, default False
Update the data in place if possible.
limit_direction : {{'forward', 'backward', 'both'}}, optional, default 'forward'
Consecutive NaNs will be filled in this direction.
limit_area : {{`None`, 'inside', 'outside'}}, default None
If limit is specified, consecutive NaNs will be filled with this
restriction.
* ``None``: No fill restriction.
* 'inside': Only fill NaNs surrounded by valid values
(interpolate).
* 'outside': Only fill NaNs outside valid values (extrapolate).
**kwargs : optional
Keyword arguments to pass on to the interpolating function.
Returns
-------
Series or DataFrame
Returns the same object type as the caller, interpolated at
some or all ``NaN`` values.
See Also
--------
fillna : Fill missing values using different methods.
scipy.interpolate.Akima1DInterpolator : Piecewise cubic polynomials
(Akima interpolator).
scipy.interpolate.BPoly.from_derivatives : Piecewise polynomial in the
Bernstein basis.
scipy.interpolate.interp1d : Interpolate a 1-D function.
scipy.interpolate.KroghInterpolator : Interpolate polynomial (Krogh
interpolator).
scipy.interpolate.PchipInterpolator : PCHIP 1-d monotonic cubic
interpolation.
scipy.interpolate.CubicSpline : Cubic spline data interpolator.
Notes
-----
The 'krogh', 'piecewise_polynomial', 'spline', 'pchip' and 'akima'
methods are wrappers around the respective SciPy implementations of
similar names. These use the actual numerical values of the index.
For more information on their behavior, see the
`SciPy documentation
<https://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation>`__.
Examples
--------
Filling in ``NaN`` in a :class:`~pandas.Series` via linear
interpolation.
>>> s = pd.Series([0, 1, np.nan, 3])
>>> s
0 0.0
1 1.0
2 NaN
3 3.0
dtype: float64
>>> s.interpolate()
0 0.0
1 1.0
2 2.0
3 3.0
dtype: float64
Filling in ``NaN`` in a Series via polynomial interpolation or splines:
Both 'polynomial' and 'spline' methods require that you also specify
an ``order`` (int).
>>> s = pd.Series([0, 2, np.nan, 8])
>>> s.interpolate(method="polynomial", order=2)
0 0.000000
1 2.000000
2 4.666667
3 8.000000
dtype: float64
Fill the DataFrame forward (that is, going down) along each column
using linear interpolation.
Note how the last entry in column 'a' is interpolated differently,
because there is no entry after it to use for interpolation.
Note how the first entry in column 'b' remains ``NaN``, because there
is no entry before it to use for interpolation.
>>> df = pd.DataFrame(
... [
... (0.0, np.nan, -1.0, 1.0),
... (np.nan, 2.0, np.nan, np.nan),
... (2.0, 3.0, np.nan, 9.0),
... (np.nan, 4.0, -4.0, 16.0),
... ],
... columns=list("abcd"),
... )
>>> df
a b c d
0 0.0 NaN -1.0 1.0
1 NaN 2.0 NaN NaN
2 2.0 3.0 NaN 9.0
3 NaN 4.0 -4.0 16.0
>>> df.interpolate(method="linear", limit_direction="forward", axis=0)
a b c d
0 0.0 NaN -1.0 1.0
1 1.0 2.0 -2.0 5.0
2 2.0 3.0 -3.0 9.0
3 2.0 4.0 -4.0 16.0
Using polynomial interpolation.
>>> df["d"].interpolate(method="polynomial", order=2)
0 1.0
1 4.0
2 9.0
3 16.0
Name: d, dtype: float64
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
axis = self._get_axis_number(axis)
if self.empty:
return self if inplace else self.copy()
if not isinstance(method, str):
raise ValueError("'method' should be a string, not None.")
obj, should_transpose = (self.T, True) if axis == 1 else (self, False)
if isinstance(obj.index, MultiIndex) and method != "linear":
raise ValueError(
"Only `method=linear` interpolation is supported on MultiIndexes."
)
limit_direction = missing.infer_limit_direction(limit_direction, method)
index = missing.get_interp_index(method, obj.index)
new_data = obj._mgr.interpolate(
method=method,
index=index,
limit=limit,
limit_direction=limit_direction,
limit_area=limit_area,
inplace=inplace,
**kwargs,
)
result = self._constructor_from_mgr(new_data, axes=new_data.axes)
if should_transpose:
result = result.T
if inplace:
self._update_inplace(result)
return self
else:
return result.__finalize__(self, method="interpolate")
# ----------------------------------------------------------------------
# Timeseries methods Methods
@final
def asof(self, where, subset=None):
"""
Return the last row(s) without any NaNs before `where`.
The last row (for each element in `where`, if list) without any
NaN is taken.
In case of a :class:`~pandas.DataFrame`, the last row without NaN
considering only the subset of columns (if not `None`)
If there is no good value, NaN is returned for a Series or
a Series of NaN values for a DataFrame
Parameters
----------
where : date or array-like of dates
Date(s) before which the last row(s) are returned.
subset : str or array-like of str, default `None`
For DataFrame, if not `None`, only use these columns to
check for NaNs.
Returns
-------
scalar, Series, or DataFrame
The return can be:
* scalar : when `self` is a Series and `where` is a scalar
* Series: when `self` is a Series and `where` is an array-like,
or when `self` is a DataFrame and `where` is a scalar
* DataFrame : when `self` is a DataFrame and `where` is an
array-like
See Also
--------
merge_asof : Perform an asof merge. Similar to left join.
Notes
-----
Dates are assumed to be sorted. Raises if this is not the case.
Examples
--------
A Series and a scalar `where`.
>>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])
>>> s
10 1.0
20 2.0
30 NaN
40 4.0
dtype: float64
>>> s.asof(20)
np.float64(2.0)
For a sequence `where`, a Series is returned. The first value is
NaN, because the first element of `where` is before the first
index value.
>>> s.asof([5, 20])
5 NaN
20 2.0
dtype: float64
Missing values are not considered. The following is ``2.0``, not
NaN, even though NaN is at the index location for ``30``.
>>> s.asof(30)
np.float64(2.0)
Take all columns into consideration
>>> df = pd.DataFrame(
... {
... "a": [10.0, 20.0, 30.0, 40.0, 50.0],
... "b": [None, None, None, None, 500],
... },
... index=pd.DatetimeIndex(
... [
... "2018-02-27 09:01:00",
... "2018-02-27 09:02:00",
... "2018-02-27 09:03:00",
... "2018-02-27 09:04:00",
... "2018-02-27 09:05:00",
... ]
... ),
... )
>>> df.asof(pd.DatetimeIndex(["2018-02-27 09:03:30", "2018-02-27 09:04:30"]))
a b
2018-02-27 09:03:30 NaN NaN
2018-02-27 09:04:30 NaN NaN
Take a single column into consideration
>>> df.asof(
... pd.DatetimeIndex(["2018-02-27 09:03:30", "2018-02-27 09:04:30"]),
... subset=["a"],
... )
a b
2018-02-27 09:03:30 30.0 NaN
2018-02-27 09:04:30 40.0 NaN
"""
if isinstance(where, str):
where = Timestamp(where)
if not self.index.is_monotonic_increasing:
raise ValueError("asof requires a sorted index")
is_series = isinstance(self, ABCSeries)
if is_series:
if subset is not None:
raise ValueError("subset is not valid for Series")
else:
if subset is None:
subset = self.columns
if not is_list_like(subset):
subset = [subset]
is_list = is_list_like(where)
if not is_list:
start = self.index[0]
if isinstance(self.index, PeriodIndex):
where = Period(where, freq=self.index.freq)
if where < start:
if not is_series:
return self._constructor_sliced(
index=self.columns, name=where, dtype=np.float64
)
return np.nan
# It's always much faster to use a *while* loop here for
# Series than pre-computing all the NAs. However a
# *while* loop is extremely expensive for DataFrame
# so we later pre-compute all the NAs and use the same
# code path whether *where* is a scalar or list.
# See PR: https://github.com/pandas-dev/pandas/pull/14476
if is_series:
loc = self.index.searchsorted(where, side="right")
if loc > 0:
loc -= 1
values = self._values
while loc > 0 and isna(values[loc]):
loc -= 1
return values[loc]
if not isinstance(where, Index):
where = Index(where) if is_list else Index([where])
nulls = self.isna() if is_series else self[subset].isna().any(axis=1)
if nulls.all():
if is_series:
self = cast("Series", self)
return self._constructor(np.nan, index=where, name=self.name)
elif is_list:
self = cast("DataFrame", self)
return self._constructor(np.nan, index=where, columns=self.columns)
else:
self = cast("DataFrame", self)
return self._constructor_sliced(
np.nan, index=self.columns, name=where[0]
)
# error: Unsupported operand type for
# ~ ("ExtensionArray | ndarray[Any, Any] | Any")
locs = self.index.asof_locs(where, ~nulls._values) # type: ignore[operator]
# mask the missing
mask = locs == -1
data = self.take(locs)
data.index = where
if mask.any():
# GH#16063 only do this setting when necessary, otherwise
# we'd cast e.g. bools to floats
data.loc[mask] = np.nan
return data if is_list else data.iloc[-1]
# ----------------------------------------------------------------------
# Action Methods
def isna(self) -> Self:
"""
Detect missing values.
Return a boolean same-sized object indicating if the values are NA.
NA values, such as None or :attr:`numpy.NaN`, gets mapped to True
values.
Everything else gets mapped to False values. Characters such as empty
strings ``''`` or :attr:`numpy.inf` are not considered NA values.
Returns
-------
Series/DataFrame
Mask of bool values for each element in Series/DataFrame
that indicates whether an element is an NA value.
See Also
--------
Series.isnull : Alias of isna.
DataFrame.isnull : Alias of isna.
Series.notna : Boolean inverse of isna.
DataFrame.notna : Boolean inverse of isna.
Series.dropna : Omit axes labels with missing values.
DataFrame.dropna : Omit axes labels with missing values.
isna : Top-level isna.
Examples
--------
Show which entries in a DataFrame are NA.
>>> df = pd.DataFrame(
... dict(
... age=[5, 6, np.nan],
... born=[
... pd.NaT,
... pd.Timestamp("1939-05-27"),
... pd.Timestamp("1940-04-25"),
... ],
... name=["Alfred", "Batman", ""],
... toy=[None, "Batmobile", "Joker"],
... )
... )
>>> df
age born name toy
0 5.0 NaT Alfred NaN
1 6.0 1939-05-27 Batman Batmobile
2 NaN 1940-04-25 Joker
>>> df.isna()
age born name toy
0 False True False True
1 False False False False
2 True False False False
Show which entries in a Series are NA.
>>> ser = pd.Series([5, 6, np.nan])
>>> ser
0 5.0
1 6.0
2 NaN
dtype: float64
>>> ser.isna()
0 False
1 False
2 True
dtype: bool
"""
return isna(self).__finalize__(self, method="isna")
def isnull(self) -> Self:
"""
Detect missing values.
Return a boolean same-sized object indicating if the values are NA.
NA values, such as None or :attr:`numpy.NaN`, gets mapped to True
values.
Everything else gets mapped to False values. Characters such as empty
strings ``''`` or :attr:`numpy.inf` are not considered NA values.
Returns
-------
Series/DataFrame
Mask of bool values for each element in Series/DataFrame
that indicates whether an element is an NA value.
See Also
--------
Series.isna : Alias of isnull.
DataFrame.isna : Alias of isnull.
Series.notna : Boolean inverse of isnull.
DataFrame.notna : Boolean inverse of isnull.
Series.dropna : Omit axes labels with missing values.
DataFrame.dropna : Omit axes labels with missing values.
isna : Top-level isna.
Examples
--------
Show which entries in a DataFrame are NA.
>>> df = pd.DataFrame(
... dict(
... age=[5, 6, np.nan],
... born=[
... pd.NaT,
... pd.Timestamp("1939-05-27"),
... pd.Timestamp("1940-04-25"),
... ],
... name=["Alfred", "Batman", ""],
... toy=[None, "Batmobile", "Joker"],
... )
... )
>>> df
age born name toy
0 5.0 NaT Alfred NaN
1 6.0 1939-05-27 Batman Batmobile
2 NaN 1940-04-25 Joker
>>> df.isna()
age born name toy
0 False True False True
1 False False False False
2 True False False False
Show which entries in a Series are NA.
>>> ser = pd.Series([5, 6, np.nan])
>>> ser
0 5.0
1 6.0
2 NaN
dtype: float64
>>> ser.isna()
0 False
1 False
2 True
dtype: bool
"""
return isna(self).__finalize__(self, method="isnull")
def notna(self) -> Self:
"""
Detect existing (non-missing) values.
Return a boolean same-sized object indicating if the values are not NA.
Non-missing values get mapped to True. Characters such as empty
strings ``''`` or :attr:`numpy.inf` are not considered NA values.
NA values, such as None or :attr:`numpy.NaN`, get mapped to False
values.
Returns
-------
Series/DataFrame
Mask of bool values for each element in Series/DataFrame
that indicates whether an element is not an NA value.
See Also
--------
Series.notnull : Alias of notna.
DataFrame.notnull : Alias of notna.
Series.isna : Boolean inverse of notna.
DataFrame.isna : Boolean inverse of notna.
Series.dropna : Omit axes labels with missing values.
DataFrame.dropna : Omit axes labels with missing values.
notna : Top-level notna.
Examples
--------
Show which entries in a DataFrame are not NA.
>>> df = pd.DataFrame(
... dict(
... age=[5, 6, np.nan],
... born=[
... pd.NaT,
... pd.Timestamp("1939-05-27"),
... pd.Timestamp("1940-04-25"),
... ],
... name=["Alfred", "Batman", ""],
... toy=[None, "Batmobile", "Joker"],
... )
... )
>>> df
age born name toy
0 5.0 NaT Alfred NaN
1 6.0 1939-05-27 Batman Batmobile
2 NaN 1940-04-25 Joker
>>> df.notna()
age born name toy
0 True False True False
1 True True True True
2 False True True True
Show which entries in a Series are not NA.
>>> ser = pd.Series([5, 6, np.nan])
>>> ser
0 5.0
1 6.0
2 NaN
dtype: float64
>>> ser.notna()
0 True
1 True
2 False
dtype: bool
"""
return notna(self).__finalize__(self, method="notna")
@doc(notna, klass=_shared_doc_kwargs["klass"])
def notnull(self) -> Self:
return notna(self).__finalize__(self, method="notnull")
@final
def _clip_with_scalar(self, lower, upper, inplace: bool = False):
if (lower is not None and np.any(isna(lower))) or (
upper is not None and np.any(isna(upper))
):
raise ValueError("Cannot use an NA value as a clip threshold")
result = self
mask = self.isna()
if lower is not None:
cond = mask | (self >= lower)
result = result.where(cond, lower, inplace=inplace)
if upper is not None:
cond = mask | (self <= upper)
result = result.where(cond, upper, inplace=inplace)
return result
@final
def _clip_with_one_bound(self, threshold, method, axis, inplace):
if axis is not None:
axis = self._get_axis_number(axis)
# method is self.le for upper bound and self.ge for lower bound
if is_scalar(threshold) and is_number(threshold):
if method.__name__ == "le":
return self._clip_with_scalar(None, threshold, inplace=inplace)
return self._clip_with_scalar(threshold, None, inplace=inplace)
# GH #15390
# In order for where method to work, the threshold must
# be transformed to NDFrame from other array like structure.
if (not isinstance(threshold, ABCSeries)) and is_list_like(threshold):
if isinstance(self, ABCSeries):
threshold = self._constructor(threshold, index=self.index)
else:
threshold = self._align_for_op(threshold, axis, flex=None)[1]
# GH 40420
# Treat missing thresholds as no bounds, not clipping the values
if is_list_like(threshold):
fill_value = np.inf if method.__name__ == "le" else -np.inf
threshold_inf = threshold.fillna(fill_value)
else:
threshold_inf = threshold
subset = method(threshold_inf, axis=axis) | isna(self)
# GH 40420
return self.where(subset, threshold, axis=axis, inplace=inplace)
@final
def clip(
self,
lower=None,
upper=None,
*,
axis: Axis | None = None,
inplace: bool = False,
**kwargs,
) -> Self:
"""
Trim values at input threshold(s).
Assigns values outside boundary to boundary values. Thresholds
can be singular values or array like, and in the latter case
the clipping is performed element-wise in the specified axis.
Parameters
----------
lower : float or array-like, default None
Minimum threshold value. All values below this
threshold will be set to it. A missing
threshold (e.g `NA`) will not clip the value.
upper : float or array-like, default None
Maximum threshold value. All values above this
threshold will be set to it. A missing
threshold (e.g `NA`) will not clip the value.
axis : {{0 or 'index', 1 or 'columns', None}}, default None
Align object with lower and upper along the given axis.
For `Series` this parameter is unused and defaults to `None`.
inplace : bool, default False
Whether to perform the operation in place on the data.
**kwargs
Additional keywords have no effect but might be accepted
for compatibility with numpy.
Returns
-------
Series or DataFrame
Same type as calling object with the values outside the
clip boundaries replaced.
See Also
--------
Series.clip : Trim values at input threshold in series.
DataFrame.clip : Trim values at input threshold in DataFrame.
numpy.clip : Clip (limit) the values in an array.
Examples
--------
>>> data = {"col_0": [9, -3, 0, -1, 5], "col_1": [-2, -7, 6, 8, -5]}
>>> df = pd.DataFrame(data)
>>> df
col_0 col_1
0 9 -2
1 -3 -7
2 0 6
3 -1 8
4 5 -5
Clips per column using lower and upper thresholds:
>>> df.clip(-4, 6)
col_0 col_1
0 6 -2
1 -3 -4
2 0 6
3 -1 6
4 5 -4
Clips using specific lower and upper thresholds per column:
>>> df.clip([-2, -1], [4, 5])
col_0 col_1
0 4 -1
1 -2 -1
2 0 5
3 -1 5
4 4 -1
Clips using specific lower and upper thresholds per column element:
>>> t = pd.Series([2, -4, -1, 6, 3])
>>> t
0 2
1 -4
2 -1
3 6
4 3
dtype: int64
>>> df.clip(t, t + 4, axis=0)
col_0 col_1
0 6 2
1 -3 -4
2 0 3
3 6 8
4 5 3
Clips using specific lower threshold per column element, with missing values:
>>> t = pd.Series([2, -4, np.nan, 6, 3])
>>> t
0 2.0
1 -4.0
2 NaN
3 6.0
4 3.0
dtype: float64
>>> df.clip(t, axis=0)
col_0 col_1
0 9.0 2.0
1 -3.0 -4.0
2 0.0 6.0
3 6.0 8.0
4 5.0 3.0
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
axis = nv.validate_clip_with_axis(axis, (), kwargs)
if axis is not None:
axis = self._get_axis_number(axis)
# GH 17276
# numpy doesn't like NaN as a clip value
# so ignore
# GH 19992
# numpy doesn't drop a list-like bound containing NaN
isna_lower = isna(lower)
if not is_list_like(lower):
if np.any(isna_lower):
lower = None
elif np.all(isna_lower):
lower = None
isna_upper = isna(upper)
if not is_list_like(upper):
if np.any(isna_upper):
upper = None
elif np.all(isna_upper):
upper = None
# GH 2747 (arguments were reversed)
if (
lower is not None
and upper is not None
and is_scalar(lower)
and is_scalar(upper)
):
lower, upper = min(lower, upper), max(lower, upper)
# fast-path for scalars
if (lower is None or is_number(lower)) and (upper is None or is_number(upper)):
return self._clip_with_scalar(lower, upper, inplace=inplace)
result = self
if lower is not None:
result = result._clip_with_one_bound(
lower, method=self.ge, axis=axis, inplace=inplace
)
if upper is not None:
if inplace:
result = self
result = result._clip_with_one_bound(
upper, method=self.le, axis=axis, inplace=inplace
)
return result
@final
@doc(klass=_shared_doc_kwargs["klass"])
def asfreq(
self,
freq: Frequency,
method: FillnaOptions | None = None,
how: Literal["start", "end"] | None = None,
normalize: bool = False,
fill_value: Hashable | None = None,
) -> Self:
"""
Convert time series to specified frequency.
Returns the original data conformed to a new index with the specified
frequency.
If the index of this {klass} is a :class:`~pandas.PeriodIndex`, the new index
is the result of transforming the original index with
:meth:`PeriodIndex.asfreq <pandas.PeriodIndex.asfreq>` (so the original index
will map one-to-one to the new index).
Otherwise, the new index will be equivalent to ``pd.date_range(start, end,
freq=freq)`` where ``start`` and ``end`` are, respectively, the min and
max entries in the original index (see :func:`pandas.date_range`). The
values corresponding to any timesteps in the new index which were not present
in the original index will be null (``NaN``), unless a method for filling
such unknowns is provided (see the ``method`` parameter below).
The :meth:`resample` method is more appropriate if an operation on each group of
timesteps (such as an aggregate) is necessary to represent the data at the new
frequency.
Parameters
----------
freq : DateOffset or str
Frequency DateOffset or string.
method : {{'backfill'/'bfill', 'pad'/'ffill'}}, default None
Method to use for filling holes in reindexed Series (note this
does not fill NaNs that already were present):
* 'pad' / 'ffill': propagate last valid observation forward to next
valid based on the order of the index
* 'backfill' / 'bfill': use NEXT valid observation to fill.
how : {{'start', 'end'}}, default end
For PeriodIndex only (see PeriodIndex.asfreq).
normalize : bool, default False
Whether to reset output index to midnight.
fill_value : scalar, optional
Value to use for missing values, applied during upsampling (note
this does not fill NaNs that already were present).
Returns
-------
{klass}
{klass} object reindexed to the specified frequency.
See Also
--------
reindex : Conform DataFrame to new index with optional filling logic.
Notes
-----
To learn more about the frequency strings, please see
:ref:`this link<timeseries.offset_aliases>`.
Examples
--------
Start by creating a series with 4 one minute timestamps.
>>> index = pd.date_range("1/1/2000", periods=4, freq="min")
>>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)
>>> df = pd.DataFrame({{"s": series}})
>>> df
s
2000-01-01 00:00:00 0.0
2000-01-01 00:01:00 NaN
2000-01-01 00:02:00 2.0
2000-01-01 00:03:00 3.0
Upsample the series into 30 second bins.
>>> df.asfreq(freq="30s")
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 NaN
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 NaN
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 NaN
2000-01-01 00:03:00 3.0
Upsample again, providing a ``fill value``.
>>> df.asfreq(freq="30s", fill_value=9.0)
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 9.0
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 9.0
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 9.0
2000-01-01 00:03:00 3.0
Upsample again, providing a ``method``.
>>> df.asfreq(freq="30s", method="bfill")
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 NaN
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 2.0
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 3.0
2000-01-01 00:03:00 3.0
"""
from pandas.core.resample import asfreq
return asfreq(
self,
freq,
method=method,
how=how,
normalize=normalize,
fill_value=fill_value,
)
@final
def at_time(self, time, asof: bool = False, axis: Axis | None = None) -> Self:
"""
Select values at particular time of day (e.g., 9:30AM).
Parameters
----------
time : datetime.time or str
The values to select.
asof : bool, default False
This parameter is currently not supported.
axis : {0 or 'index', 1 or 'columns'}, default 0
For `Series` this parameter is unused and defaults to 0.
Returns
-------
Series or DataFrame
The values with the specified time.
Raises
------
TypeError
If the index is not a :class:`DatetimeIndex`
See Also
--------
between_time : Select values between particular times of the day.
first : Select initial periods of time series based on a date offset.
last : Select final periods of time series based on a date offset.
DatetimeIndex.indexer_at_time : Get just the index locations for
values at particular time of the day.
Examples
--------
>>> i = pd.date_range("2018-04-09", periods=4, freq="12h")
>>> ts = pd.DataFrame({"A": [1, 2, 3, 4]}, index=i)
>>> ts
A
2018-04-09 00:00:00 1
2018-04-09 12:00:00 2
2018-04-10 00:00:00 3
2018-04-10 12:00:00 4
>>> ts.at_time("12:00")
A
2018-04-09 12:00:00 2
2018-04-10 12:00:00 4
"""
if axis is None:
axis = 0
axis = self._get_axis_number(axis)
index = self._get_axis(axis)
if not isinstance(index, DatetimeIndex):
raise TypeError("Index must be DatetimeIndex")
indexer = index.indexer_at_time(time, asof=asof)
return self.take(indexer, axis=axis)
@final
def between_time(
self,
start_time,
end_time,
inclusive: IntervalClosedType = "both",
axis: Axis | None = None,
) -> Self:
"""
Select values between particular times of the day (e.g., 9:00-9:30 AM).
By setting ``start_time`` to be later than ``end_time``,
you can get the times that are *not* between the two times.
Parameters
----------
start_time : datetime.time or str
Initial time as a time filter limit.
end_time : datetime.time or str
End time as a time filter limit.
inclusive : {"both", "neither", "left", "right"}, default "both"
Include boundaries; whether to set each bound as closed or open.
axis : {0 or 'index', 1 or 'columns'}, default 0
Determine range time on index or columns value.
For `Series` this parameter is unused and defaults to 0.
Returns
-------
Series or DataFrame
Data from the original object filtered to the specified dates range.
Raises
------
TypeError
If the index is not a :class:`DatetimeIndex`
See Also
--------
at_time : Select values at a particular time of the day.
first : Select initial periods of time series based on a date offset.
last : Select final periods of time series based on a date offset.
DatetimeIndex.indexer_between_time : Get just the index locations for
values between particular times of the day.
Examples
--------
>>> i = pd.date_range("2018-04-09", periods=4, freq="1D20min")
>>> ts = pd.DataFrame({"A": [1, 2, 3, 4]}, index=i)
>>> ts
A
2018-04-09 00:00:00 1
2018-04-10 00:20:00 2
2018-04-11 00:40:00 3
2018-04-12 01:00:00 4
>>> ts.between_time("0:15", "0:45")
A
2018-04-10 00:20:00 2
2018-04-11 00:40:00 3
You get the times that are *not* between two times by setting
``start_time`` later than ``end_time``:
>>> ts.between_time("0:45", "0:15")
A
2018-04-09 00:00:00 1
2018-04-12 01:00:00 4
"""
if axis is None:
axis = 0
axis = self._get_axis_number(axis)
index = self._get_axis(axis)
if not isinstance(index, DatetimeIndex):
raise TypeError("Index must be DatetimeIndex")
left_inclusive, right_inclusive = validate_inclusive(inclusive)
indexer = index.indexer_between_time(
start_time,
end_time,
include_start=left_inclusive,
include_end=right_inclusive,
)
return self.take(indexer, axis=axis)
@final
@doc(klass=_shared_doc_kwargs["klass"])
def resample(
self,
rule,
closed: Literal["right", "left"] | None = None,
label: Literal["right", "left"] | None = None,
convention: Literal["start", "end", "s", "e"] = "start",
on: Level | None = None,
level: Level | None = None,
origin: str | TimestampConvertibleTypes = "start_day",
offset: TimedeltaConvertibleTypes | None = None,
group_keys: bool = False,
) -> Resampler:
"""
Resample time-series data.
Convenience method for frequency conversion and resampling of time series.
The object must have a datetime-like index (`DatetimeIndex`, `PeriodIndex`,
or `TimedeltaIndex`), or the caller must pass the label of a datetime-like
series/index to the ``on``/``level`` keyword parameter.
Parameters
----------
rule : DateOffset, Timedelta or str
The offset string or object representing target conversion.
closed : {{'right', 'left'}}, default None
Which side of bin interval is closed. The default is 'left'
for all frequency offsets except for 'ME', 'YE', 'QE', 'BME',
'BA', 'BQE', and 'W' which all have a default of 'right'.
label : {{'right', 'left'}}, default None
Which bin edge label to label bucket with. The default is 'left'
for all frequency offsets except for 'ME', 'YE', 'QE', 'BME',
'BA', 'BQE', and 'W' which all have a default of 'right'.
convention : {{'start', 'end', 's', 'e'}}, default 'start'
For `PeriodIndex` only, controls whether to use the start or
end of `rule`.
on : str, optional
For a DataFrame, column to use instead of index for resampling.
Column must be datetime-like.
level : str or int, optional
For a MultiIndex, level (name or number) to use for
resampling. `level` must be datetime-like.
origin : Timestamp or str, default 'start_day'
The timestamp on which to adjust the grouping. The timezone of origin
must match the timezone of the index.
If string, must be Timestamp convertible or one of the following:
- 'epoch': `origin` is 1970-01-01
- 'start': `origin` is the first value of the timeseries
- 'start_day': `origin` is the first day at midnight of the timeseries
- 'end': `origin` is the last value of the timeseries
- 'end_day': `origin` is the ceiling midnight of the last day
.. note::
Only takes effect for Tick-frequencies (i.e. fixed frequencies like
days, hours, and minutes, rather than months or quarters).
offset : Timedelta or str, default is None
An offset timedelta added to the origin.
group_keys : bool, default False
Whether to include the group keys in the result index when using
``.apply()`` on the resampled object.
.. versionchanged:: 2.0.0
``group_keys`` now defaults to ``False``.
Returns
-------
pandas.api.typing.Resampler
:class:`~pandas.core.Resampler` object.
See Also
--------
Series.resample : Resample a Series.
DataFrame.resample : Resample a DataFrame.
groupby : Group {klass} by mapping, function, label, or list of labels.
asfreq : Reindex a {klass} with the given frequency without grouping.
Notes
-----
See the `user guide
<https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling>`__
for more.
To learn more about the offset strings, please see `this link
<https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects>`__.
Examples
--------
Start by creating a series with 9 one minute timestamps.
>>> index = pd.date_range("1/1/2000", periods=9, freq="min")
>>> series = pd.Series(range(9), index=index)
>>> series
2000-01-01 00:00:00 0
2000-01-01 00:01:00 1
2000-01-01 00:02:00 2
2000-01-01 00:03:00 3
2000-01-01 00:04:00 4
2000-01-01 00:05:00 5
2000-01-01 00:06:00 6
2000-01-01 00:07:00 7
2000-01-01 00:08:00 8
Freq: min, dtype: int64
Downsample the series into 3 minute bins and sum the values
of the timestamps falling into a bin.
>>> series.resample("3min").sum()
2000-01-01 00:00:00 3
2000-01-01 00:03:00 12
2000-01-01 00:06:00 21
Freq: 3min, dtype: int64
Downsample the series into 3 minute bins as above, but label each
bin using the right edge instead of the left. Please note that the
value in the bucket used as the label is not included in the bucket,
which it labels. For example, in the original series the
bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed
value in the resampled bucket with the label ``2000-01-01 00:03:00``
does not include 3 (if it did, the summed value would be 6, not 3).
>>> series.resample("3min", label="right").sum()
2000-01-01 00:03:00 3
2000-01-01 00:06:00 12
2000-01-01 00:09:00 21
Freq: 3min, dtype: int64
To include this value close the right side of the bin interval,
as shown below.
>>> series.resample("3min", label="right", closed="right").sum()
2000-01-01 00:00:00 0
2000-01-01 00:03:00 6
2000-01-01 00:06:00 15
2000-01-01 00:09:00 15
Freq: 3min, dtype: int64
Upsample the series into 30 second bins.
>>> series.resample("30s").asfreq()[0:5] # Select first 5 rows
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 NaN
2000-01-01 00:01:00 1.0
2000-01-01 00:01:30 NaN
2000-01-01 00:02:00 2.0
Freq: 30s, dtype: float64
Upsample the series into 30 second bins and fill the ``NaN``
values using the ``ffill`` method.
>>> series.resample("30s").ffill()[0:5]
2000-01-01 00:00:00 0
2000-01-01 00:00:30 0
2000-01-01 00:01:00 1
2000-01-01 00:01:30 1
2000-01-01 00:02:00 2
Freq: 30s, dtype: int64
Upsample the series into 30 second bins and fill the
``NaN`` values using the ``bfill`` method.
>>> series.resample("30s").bfill()[0:5]
2000-01-01 00:00:00 0
2000-01-01 00:00:30 1
2000-01-01 00:01:00 1
2000-01-01 00:01:30 2
2000-01-01 00:02:00 2
Freq: 30s, dtype: int64
Pass a custom function via ``apply``
>>> def custom_resampler(arraylike):
... return np.sum(arraylike) + 5
>>> series.resample("3min").apply(custom_resampler)
2000-01-01 00:00:00 8
2000-01-01 00:03:00 17
2000-01-01 00:06:00 26
Freq: 3min, dtype: int64
For a Series with a PeriodIndex, the keyword `convention` can be
used to control whether to use the start or end of `rule`.
Resample a year by quarter using 'start' `convention`. Values are
assigned to the first quarter of the period.
>>> s = pd.Series(
... [1, 2], index=pd.period_range("2012-01-01", freq="Y", periods=2)
... )
>>> s
2012 1
2013 2
Freq: Y-DEC, dtype: int64
>>> s.resample("Q", convention="start").asfreq()
2012Q1 1.0
2012Q2 NaN
2012Q3 NaN
2012Q4 NaN
2013Q1 2.0
2013Q2 NaN
2013Q3 NaN
2013Q4 NaN
Freq: Q-DEC, dtype: float64
Resample quarters by month using 'end' `convention`. Values are
assigned to the last month of the period.
>>> q = pd.Series(
... [1, 2, 3, 4], index=pd.period_range("2018-01-01", freq="Q", periods=4)
... )
>>> q
2018Q1 1
2018Q2 2
2018Q3 3
2018Q4 4
Freq: Q-DEC, dtype: int64
>>> q.resample("M", convention="end").asfreq()
2018-03 1.0
2018-04 NaN
2018-05 NaN
2018-06 2.0
2018-07 NaN
2018-08 NaN
2018-09 3.0
2018-10 NaN
2018-11 NaN
2018-12 4.0
Freq: M, dtype: float64
For DataFrame objects, the keyword `on` can be used to specify the
column instead of the index for resampling.
>>> df = pd.DataFrame([10, 11, 9, 13, 14, 18, 17, 19], columns=["price"])
>>> df["volume"] = [50, 60, 40, 100, 50, 100, 40, 50]
>>> df["week_starting"] = pd.date_range("01/01/2018", periods=8, freq="W")
>>> df
price volume week_starting
0 10 50 2018-01-07
1 11 60 2018-01-14
2 9 40 2018-01-21
3 13 100 2018-01-28
4 14 50 2018-02-04
5 18 100 2018-02-11
6 17 40 2018-02-18
7 19 50 2018-02-25
>>> df.resample("ME", on="week_starting").mean()
price volume
week_starting
2018-01-31 10.75 62.5
2018-02-28 17.00 60.0
For a DataFrame with MultiIndex, the keyword `level` can be used to
specify on which level the resampling needs to take place.
>>> days = pd.date_range("1/1/2000", periods=4, freq="D")
>>> df2 = pd.DataFrame(
... [
... [10, 50],
... [11, 60],
... [9, 40],
... [13, 100],
... [14, 50],
... [18, 100],
... [17, 40],
... [19, 50],
... ],
... columns=["price", "volume"],
... index=pd.MultiIndex.from_product([days, ["morning", "afternoon"]]),
... )
>>> df2
price volume
2000-01-01 morning 10 50
afternoon 11 60
2000-01-02 morning 9 40
afternoon 13 100
2000-01-03 morning 14 50
afternoon 18 100
2000-01-04 morning 17 40
afternoon 19 50
>>> df2.resample("D", level=0).sum()
price volume
2000-01-01 21 110
2000-01-02 22 140
2000-01-03 32 150
2000-01-04 36 90
If you want to adjust the start of the bins based on a fixed timestamp:
>>> start, end = "2000-10-01 23:30:00", "2000-10-02 00:30:00"
>>> rng = pd.date_range(start, end, freq="7min")
>>> ts = pd.Series(np.arange(len(rng)) * 3, index=rng)
>>> ts
2000-10-01 23:30:00 0
2000-10-01 23:37:00 3
2000-10-01 23:44:00 6
2000-10-01 23:51:00 9
2000-10-01 23:58:00 12
2000-10-02 00:05:00 15
2000-10-02 00:12:00 18
2000-10-02 00:19:00 21
2000-10-02 00:26:00 24
Freq: 7min, dtype: int64
>>> ts.resample("17min").sum()
2000-10-01 23:14:00 0
2000-10-01 23:31:00 9
2000-10-01 23:48:00 21
2000-10-02 00:05:00 54
2000-10-02 00:22:00 24
Freq: 17min, dtype: int64
>>> ts.resample("17min", origin="epoch").sum()
2000-10-01 23:18:00 0
2000-10-01 23:35:00 18
2000-10-01 23:52:00 27
2000-10-02 00:09:00 39
2000-10-02 00:26:00 24
Freq: 17min, dtype: int64
>>> ts.resample("17min", origin="2000-01-01").sum()
2000-10-01 23:24:00 3
2000-10-01 23:41:00 15
2000-10-01 23:58:00 45
2000-10-02 00:15:00 45
Freq: 17min, dtype: int64
If you want to adjust the start of the bins with an `offset` Timedelta, the two
following lines are equivalent:
>>> ts.resample("17min", origin="start").sum()
2000-10-01 23:30:00 9
2000-10-01 23:47:00 21
2000-10-02 00:04:00 54
2000-10-02 00:21:00 24
Freq: 17min, dtype: int64
>>> ts.resample("17min", offset="23h30min").sum()
2000-10-01 23:30:00 9
2000-10-01 23:47:00 21
2000-10-02 00:04:00 54
2000-10-02 00:21:00 24
Freq: 17min, dtype: int64
If you want to take the largest Timestamp as the end of the bins:
>>> ts.resample("17min", origin="end").sum()
2000-10-01 23:35:00 0
2000-10-01 23:52:00 18
2000-10-02 00:09:00 27
2000-10-02 00:26:00 63
Freq: 17min, dtype: int64
In contrast with the `start_day`, you can use `end_day` to take the ceiling
midnight of the largest Timestamp as the end of the bins and drop the bins
not containing data:
>>> ts.resample("17min", origin="end_day").sum()
2000-10-01 23:38:00 3
2000-10-01 23:55:00 15
2000-10-02 00:12:00 45
2000-10-02 00:29:00 45
Freq: 17min, dtype: int64
"""
from pandas.core.resample import get_resampler
return get_resampler(
cast("Series | DataFrame", self),
freq=rule,
label=label,
closed=closed,
convention=convention,
key=on,
level=level,
origin=origin,
offset=offset,
group_keys=group_keys,
)
@final
def rank(
self,
axis: Axis = 0,
method: Literal["average", "min", "max", "first", "dense"] = "average",
numeric_only: bool = False,
na_option: Literal["keep", "top", "bottom"] = "keep",
ascending: bool = True,
pct: bool = False,
) -> Self:
"""
Compute numerical data ranks (1 through n) along axis.
By default, equal values are assigned a rank that is the average of the
ranks of those values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
Index to direct ranking.
For `Series` this parameter is unused and defaults to 0.
method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'
How to rank the group of records that have the same value (i.e. ties):
* average: average rank of the group
* min: lowest rank in the group
* max: highest rank in the group
* first: ranks assigned in order they appear in the array
* dense: like 'min', but rank always increases by 1 between groups.
numeric_only : bool, default False
For DataFrame objects, rank only numeric columns if set to True.
.. versionchanged:: 2.0.0
The default value of ``numeric_only`` is now ``False``.
na_option : {'keep', 'top', 'bottom'}, default 'keep'
How to rank NaN values:
* keep: assign NaN rank to NaN values
* top: assign lowest rank to NaN values
* bottom: assign highest rank to NaN values
ascending : bool, default True
Whether or not the elements should be ranked in ascending order.
pct : bool, default False
Whether or not to display the returned rankings in percentile
form.
Returns
-------
same type as caller
Return a Series or DataFrame with data ranks as values.
See Also
--------
core.groupby.DataFrameGroupBy.rank : Rank of values within each group.
core.groupby.SeriesGroupBy.rank : Rank of values within each group.
Examples
--------
>>> df = pd.DataFrame(
... data={
... "Animal": ["cat", "penguin", "dog", "spider", "snake"],
... "Number_legs": [4, 2, 4, 8, np.nan],
... }
... )
>>> df
Animal Number_legs
0 cat 4.0
1 penguin 2.0
2 dog 4.0
3 spider 8.0
4 snake NaN
Ties are assigned the mean of the ranks (by default) for the group.
>>> s = pd.Series(range(5), index=list("abcde"))
>>> s["d"] = s["b"]
>>> s.rank()
a 1.0
b 2.5
c 4.0
d 2.5
e 5.0
dtype: float64
The following example shows how the method behaves with the above
parameters:
* default_rank: this is the default behaviour obtained without using
any parameter.
* max_rank: setting ``method = 'max'`` the records that have the
same values are ranked using the highest rank (e.g.: since 'cat'
and 'dog' are both in the 2nd and 3rd position, rank 3 is assigned.)
* NA_bottom: choosing ``na_option = 'bottom'``, if there are records
with NaN values they are placed at the bottom of the ranking.
* pct_rank: when setting ``pct = True``, the ranking is expressed as
percentile rank.
>>> df["default_rank"] = df["Number_legs"].rank()
>>> df["max_rank"] = df["Number_legs"].rank(method="max")
>>> df["NA_bottom"] = df["Number_legs"].rank(na_option="bottom")
>>> df["pct_rank"] = df["Number_legs"].rank(pct=True)
>>> df
Animal Number_legs default_rank max_rank NA_bottom pct_rank
0 cat 4.0 2.5 3.0 2.5 0.625
1 penguin 2.0 1.0 1.0 1.0 0.250
2 dog 4.0 2.5 3.0 2.5 0.625
3 spider 8.0 4.0 4.0 4.0 1.000
4 snake NaN NaN NaN 5.0 NaN
"""
axis_int = self._get_axis_number(axis)
if na_option not in {"keep", "top", "bottom"}:
msg = "na_option must be one of 'keep', 'top', or 'bottom'"
raise ValueError(msg)
def ranker(data):
if data.ndim == 2:
# i.e. DataFrame, we cast to ndarray
values = data.values
else:
# i.e. Series, can dispatch to EA
values = data._values
if isinstance(values, ExtensionArray):
ranks = values._rank(
axis=axis_int,
method=method,
ascending=ascending,
na_option=na_option,
pct=pct,
)
else:
ranks = algos.rank(
values,
axis=axis_int,
method=method,
ascending=ascending,
na_option=na_option,
pct=pct,
)
ranks_obj = self._constructor(ranks, **data._construct_axes_dict())
return ranks_obj.__finalize__(self, method="rank")
if numeric_only:
if self.ndim == 1 and not is_numeric_dtype(self.dtype):
# GH#47500
raise TypeError(
"Series.rank does not allow numeric_only=True with "
"non-numeric dtype."
)
data = self._get_numeric_data()
else:
data = self
return ranker(data)
@doc(_shared_docs["compare"], klass=_shared_doc_kwargs["klass"])
def compare(
self,
other: Self,
align_axis: Axis = 1,
keep_shape: bool = False,
keep_equal: bool = False,
result_names: Suffixes = ("self", "other"),
):
if type(self) is not type(other):
cls_self, cls_other = type(self).__name__, type(other).__name__
raise TypeError(
f"can only compare '{cls_self}' (not '{cls_other}') with '{cls_self}'"
)
# error: Unsupported left operand type for & ("Self")
mask = ~((self == other) | (self.isna() & other.isna())) # type: ignore[operator]
mask.fillna(True, inplace=True)
if not keep_equal:
self = self.where(mask)
other = other.where(mask)
if not keep_shape:
if isinstance(self, ABCDataFrame):
cmask = mask.any()
rmask = mask.any(axis=1)
self = self.loc[rmask, cmask]
other = other.loc[rmask, cmask]
else:
self = self[mask]
other = other[mask]
if not isinstance(result_names, tuple):
raise TypeError(
f"Passing 'result_names' as a {type(result_names)} is not "
"supported. Provide 'result_names' as a tuple instead."
)
if align_axis in (1, "columns"): # This is needed for Series
axis = 1
else:
axis = self._get_axis_number(align_axis)
# error: List item 0 has incompatible type "NDFrame"; expected
# "Union[Series, DataFrame]"
diff = concat(
[self, other], # type: ignore[list-item]
axis=axis,
keys=result_names,
)
if axis >= self.ndim:
# No need to reorganize data if stacking on new axis
# This currently applies for stacking two Series on columns
return diff
ax = diff._get_axis(axis)
ax_names = np.array(ax.names)
# set index names to positions to avoid confusion
ax.names = np.arange(len(ax_names))
# bring self-other to inner level
order = list(range(1, ax.nlevels)) + [0]
if isinstance(diff, ABCDataFrame):
diff = diff.reorder_levels(order, axis=axis)
else:
diff = diff.reorder_levels(order)
# restore the index names in order
diff._get_axis(axis=axis).names = ax_names[order]
# reorder axis to keep things organized
indices = (
np.arange(diff.shape[axis])
.reshape([2, diff.shape[axis] // 2])
.T.reshape(-1)
)
diff = diff.take(indices, axis=axis)
return diff
@final
@doc(
klass=_shared_doc_kwargs["klass"],
axes_single_arg=_shared_doc_kwargs["axes_single_arg"],
)
def align(
self,
other: NDFrameT,
join: AlignJoin = "outer",
axis: Axis | None = None,
level: Level | None = None,
copy: bool | lib.NoDefault = lib.no_default,
fill_value: Hashable | None = None,
) -> tuple[Self, NDFrameT]:
"""
Align two objects on their axes with the specified join method.
Join method is specified for each axis Index.
Parameters
----------
other : DataFrame or Series
The object to align with.
join : {{'outer', 'inner', 'left', 'right'}}, default 'outer'
Type of alignment to be performed.
* left: use only keys from left frame, preserve key order.
* right: use only keys from right frame, preserve key order.
* outer: use union of keys from both frames, sort keys lexicographically.
* inner: use intersection of keys from both frames,
preserve the order of the left keys.
axis : allowed axis of the other object, default None
Align on index (0), columns (1), or both (None).
level : int or level name, default None
Broadcast across a level, matching Index values on the
passed MultiIndex level.
copy : bool, default False
Always returns new objects. If copy=False and no reindexing is
required then original objects are returned.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
fill_value : scalar, default np.nan
Value to use for missing values. Defaults to NaN, but can be any
"compatible" value.
Returns
-------
tuple of ({klass}, type of other)
Aligned objects.
See Also
--------
Series.align : Align two objects on their axes with specified join method.
DataFrame.align : Align two objects on their axes with specified join method.
Examples
--------
>>> df = pd.DataFrame(
... [[1, 2, 3, 4], [6, 7, 8, 9]], columns=["D", "B", "E", "A"], index=[1, 2]
... )
>>> other = pd.DataFrame(
... [[10, 20, 30, 40], [60, 70, 80, 90], [600, 700, 800, 900]],
... columns=["A", "B", "C", "D"],
... index=[2, 3, 4],
... )
>>> df
D B E A
1 1 2 3 4
2 6 7 8 9
>>> other
A B C D
2 10 20 30 40
3 60 70 80 90
4 600 700 800 900
Align on columns:
>>> left, right = df.align(other, join="outer", axis=1)
>>> left
A B C D E
1 4 2 NaN 1 3
2 9 7 NaN 6 8
>>> right
A B C D E
2 10 20 30 40 NaN
3 60 70 80 90 NaN
4 600 700 800 900 NaN
We can also align on the index:
>>> left, right = df.align(other, join="outer", axis=0)
>>> left
D B E A
1 1.0 2.0 3.0 4.0
2 6.0 7.0 8.0 9.0
3 NaN NaN NaN NaN
4 NaN NaN NaN NaN
>>> right
A B C D
1 NaN NaN NaN NaN
2 10.0 20.0 30.0 40.0
3 60.0 70.0 80.0 90.0
4 600.0 700.0 800.0 900.0
Finally, the default `axis=None` will align on both index and columns:
>>> left, right = df.align(other, join="outer", axis=None)
>>> left
A B C D E
1 4.0 2.0 NaN 1.0 3.0
2 9.0 7.0 NaN 6.0 8.0
3 NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN
>>> right
A B C D E
1 NaN NaN NaN NaN NaN
2 10.0 20.0 30.0 40.0 NaN
3 60.0 70.0 80.0 90.0 NaN
4 600.0 700.0 800.0 900.0 NaN
"""
self._check_copy_deprecation(copy)
_right: DataFrame | Series
if axis is not None:
axis = self._get_axis_number(axis)
if isinstance(other, ABCDataFrame):
left, _right, join_index = self._align_frame(
other,
join=join,
axis=axis,
level=level,
fill_value=fill_value,
)
elif isinstance(other, ABCSeries):
left, _right, join_index = self._align_series(
other,
join=join,
axis=axis,
level=level,
fill_value=fill_value,
)
else: # pragma: no cover
raise TypeError(f"unsupported type: {type(other)}")
right = cast(NDFrameT, _right)
if self.ndim == 1 or axis == 0:
# If we are aligning timezone-aware DatetimeIndexes and the timezones
# do not match, convert both to UTC.
if isinstance(left.index.dtype, DatetimeTZDtype):
if left.index.tz != right.index.tz:
if join_index is not None:
# GH#33671 copy to ensure we don't change the index on
# our original Series
left = left.copy(deep=False)
right = right.copy(deep=False)
left.index = join_index
right.index = join_index
left = left.__finalize__(self)
right = right.__finalize__(other)
return left, right
@final
def _align_frame(
self,
other: DataFrame,
join: AlignJoin = "outer",
axis: Axis | None = None,
level=None,
fill_value=None,
) -> tuple[Self, DataFrame, Index | None]:
# defaults
join_index, join_columns = None, None
ilidx, iridx = None, None
clidx, cridx = None, None
is_series = isinstance(self, ABCSeries)
if (axis is None or axis == 0) and not self.index.equals(other.index):
join_index, ilidx, iridx = self.index.join(
other.index, how=join, level=level, return_indexers=True
)
if (
(axis is None or axis == 1)
and not is_series
and not self.columns.equals(other.columns)
):
join_columns, clidx, cridx = self.columns.join(
other.columns, how=join, level=level, return_indexers=True
)
if is_series:
reindexers = {0: [join_index, ilidx]}
else:
reindexers = {0: [join_index, ilidx], 1: [join_columns, clidx]}
left = self._reindex_with_indexers(
reindexers, fill_value=fill_value, allow_dups=True
)
# other must be always DataFrame
right = other._reindex_with_indexers(
{0: [join_index, iridx], 1: [join_columns, cridx]},
fill_value=fill_value,
allow_dups=True,
)
return left, right, join_index
@final
def _align_series(
self,
other: Series,
join: AlignJoin = "outer",
axis: Axis | None = None,
level=None,
fill_value=None,
) -> tuple[Self, Series, Index | None]:
is_series = isinstance(self, ABCSeries)
if (not is_series and axis is None) or axis not in [None, 0, 1]:
raise ValueError("Must specify axis=0 or 1")
if is_series and axis == 1:
raise ValueError("cannot align series to a series other than axis 0")
# series/series compat, other must always be a Series
if not axis:
# equal
if self.index.equals(other.index):
join_index, lidx, ridx = None, None, None
else:
join_index, lidx, ridx = self.index.join(
other.index, how=join, level=level, return_indexers=True
)
if is_series:
left = self._reindex_indexer(join_index, lidx)
elif lidx is None or join_index is None:
left = self.copy(deep=False)
else:
new_mgr = self._mgr.reindex_indexer(join_index, lidx, axis=1)
left = self._constructor_from_mgr(new_mgr, axes=new_mgr.axes)
right = other._reindex_indexer(join_index, ridx)
else:
# one has > 1 ndim
fdata = self._mgr
join_index = self.axes[1]
lidx, ridx = None, None
if not join_index.equals(other.index):
join_index, lidx, ridx = join_index.join(
other.index, how=join, level=level, return_indexers=True
)
if lidx is not None:
bm_axis = self._get_block_manager_axis(1)
fdata = fdata.reindex_indexer(join_index, lidx, axis=bm_axis)
left = self._constructor_from_mgr(fdata, axes=fdata.axes)
right = other._reindex_indexer(join_index, ridx)
# fill
fill_na = notna(fill_value)
if fill_na:
left = left.fillna(fill_value)
right = right.fillna(fill_value)
return left, right, join_index
@final
def _where(
self,
cond,
other=lib.no_default,
*,
inplace: bool = False,
axis: Axis | None = None,
level=None,
) -> Self:
"""
Equivalent to public method `where`, except that `other` is not
applied as a function even if callable. Used in __setitem__.
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if axis is not None:
axis = self._get_axis_number(axis)
# align the cond to same shape as myself
cond = common.apply_if_callable(cond, self)
if isinstance(cond, NDFrame):
# CoW: Make sure reference is not kept alive
if cond.ndim == 1 and self.ndim == 2:
cond = cond._constructor_expanddim(
dict.fromkeys(range(len(self.columns)), cond),
copy=False,
)
cond.columns = self.columns
cond = cond.align(self, join="right")[0]
else:
if not hasattr(cond, "shape"):
cond = np.asanyarray(cond)
if cond.shape != self.shape:
raise ValueError("Array conditional must be same shape as self")
cond = self._constructor(cond, **self._construct_axes_dict(), copy=False)
# make sure we are boolean
fill_value = bool(inplace)
cond = cond.fillna(fill_value)
cond = cond.infer_objects()
msg = "Boolean array expected for the condition, not {dtype}"
if not cond.empty:
if not isinstance(cond, ABCDataFrame):
# This is a single-dimensional object.
if not is_bool_dtype(cond):
raise TypeError(msg.format(dtype=cond.dtype))
else:
for block in cond._mgr.blocks:
if not is_bool_dtype(block.dtype):
raise TypeError(msg.format(dtype=block.dtype))
if cond._mgr.any_extension_types:
# GH51574: avoid object ndarray conversion later on
cond = cond._constructor(
cond.to_numpy(dtype=bool, na_value=fill_value),
**cond._construct_axes_dict(),
)
else:
# GH#21947 we have an empty DataFrame/Series, could be object-dtype
cond = cond.astype(bool)
cond = -cond if inplace else cond
cond = cond.reindex(self._info_axis, axis=self._info_axis_number)
# try to align with other
if isinstance(other, NDFrame):
# align with me
if other.ndim <= self.ndim:
# CoW: Make sure reference is not kept alive
other = self.align(
other,
join="left",
axis=axis,
level=level,
fill_value=None,
)[1]
# if we are NOT aligned, raise as we cannot where index
if axis is None and not other._indexed_same(self):
raise InvalidIndexError
if other.ndim < self.ndim:
other = other._values
if isinstance(other, np.ndarray):
# TODO(EA2D): could also do this for NDArrayBackedEA cases?
if axis == 0:
other = np.reshape(other, (-1, 1))
elif axis == 1:
other = np.reshape(other, (1, -1))
other = np.broadcast_to(other, self.shape)
else:
# GH#38729, GH#62038 avoid lossy casting or object-casting
if axis == 0:
res_cols = [
self.iloc[:, i]._where(
cond.iloc[:, i],
other,
)
for i in range(self.shape[1])
]
elif axis == 1:
# TODO: can we use a zero-copy alternative to "repeat"?
res_cols = [
self.iloc[:, i]._where(
cond.iloc[:, i],
other[i : i + 1].repeat(len(self)),
)
for i in range(self.shape[1])
]
res = self._constructor(dict(enumerate(res_cols)))
res.index = self.index
res.columns = self.columns
if inplace:
self._update_inplace(res)
return self
return res.__finalize__(self)
# slice me out of the other
else:
raise NotImplementedError(
"cannot align with a higher dimensional NDFrame"
)
elif not isinstance(other, (MultiIndex, NDFrame)):
# mainly just catching Index here
other = extract_array(other, extract_numpy=True)
if isinstance(other, (np.ndarray, ExtensionArray)):
if other.shape != self.shape:
if self.ndim != 1:
# In the ndim == 1 case we may have
# other length 1, which we treat as scalar (GH#2745, GH#4192)
# or len(other) == icond.sum(), which we treat like
# __setitem__ (GH#3235)
raise ValueError(
"other must be the same shape as self when an ndarray"
)
# we are the same shape, so create an actual object for alignment
else:
other = self._constructor(
other, **self._construct_axes_dict(), copy=False
)
if axis is None:
axis = 0
if self.ndim == getattr(other, "ndim", 0):
align = True
else:
align = self._get_axis_number(axis) == 1
if inplace:
# we may have different type blocks come out of putmask, so
# reconstruct the block manager
new_data = self._mgr.putmask(mask=cond, new=other, align=align)
result = self._constructor_from_mgr(new_data, axes=new_data.axes)
self._update_inplace(result)
return self
else:
new_data = self._mgr.where(
other=other,
cond=cond,
align=align,
)
result = self._constructor_from_mgr(new_data, axes=new_data.axes)
return result.__finalize__(self)
@final
@doc(
klass=_shared_doc_kwargs["klass"],
cond="True",
cond_rev="False",
name="where",
name_other="mask",
)
def where(
self,
cond,
other=lib.no_default,
*,
inplace: bool = False,
axis: Axis | None = None,
level: Level | None = None,
) -> Self:
"""
Replace values where the condition is {cond_rev}.
Parameters
----------
cond : bool {klass}, array-like, or callable
Where `cond` is {cond}, keep the original value. Where
{cond_rev}, replace with corresponding value from `other`.
If `cond` is callable, it is computed on the {klass} and
should return boolean {klass} or array. The callable must
not change input {klass} (though pandas doesn't check it).
other : scalar, {klass}, or callable
Entries where `cond` is {cond_rev} are replaced with
corresponding value from `other`.
If other is callable, it is computed on the {klass} and
should return scalar or {klass}. The callable must not
change input {klass} (though pandas doesn't check it).
If not specified, entries will be filled with the corresponding
NULL value (``np.nan`` for numpy dtypes, ``pd.NA`` for extension
dtypes).
inplace : bool, default False
Whether to perform the operation in place on the data.
axis : int, default None
Alignment axis if needed. For `Series` this parameter is
unused and defaults to 0.
level : int, default None
Alignment level if needed.
Returns
-------
Series or DataFrame
When applied to a Series, the function will return a Series,
and when applied to a DataFrame, it will return a DataFrame.
See Also
--------
:func:`DataFrame.{name_other}` : Return an object of same shape as
caller.
:func:`Series.{name_other}` : Return an object of same shape as
caller.
Notes
-----
The {name} method is an application of the if-then idiom. For each
element in the caller, if ``cond`` is ``{cond}`` the
element is used; otherwise the corresponding element from
``other`` is used. If the axis of ``other`` does not align with axis of
``cond`` {klass}, the values of ``cond`` on misaligned index positions
will be filled with {cond_rev}.
The signature for :func:`Series.where` or
:func:`DataFrame.where` differs from :func:`numpy.where`.
Roughly ``df1.where(m, df2)`` is equivalent to ``np.where(m, df1, df2)``.
For further details and examples see the ``{name}`` documentation in
:ref:`indexing <indexing.where_mask>`.
The dtype of the object takes precedence. The fill value is casted to
the object's dtype, if this can be done losslessly.
Examples
--------
>>> s = pd.Series(range(5))
>>> s.where(s > 0)
0 NaN
1 1.0
2 2.0
3 3.0
4 4.0
dtype: float64
>>> s.mask(s > 0)
0 0.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
>>> s = pd.Series(range(5))
>>> t = pd.Series([True, False])
>>> s.where(t, 99)
0 0
1 99
2 99
3 99
4 99
dtype: int64
>>> s.mask(t, 99)
0 99
1 1
2 99
3 99
4 99
dtype: int64
>>> s.where(s > 1, 10)
0 10
1 10
2 2
3 3
4 4
dtype: int64
>>> s.mask(s > 1, 10)
0 0
1 1
2 10
3 10
4 10
dtype: int64
>>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=["A", "B"])
>>> df
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
>>> m = df % 3 == 0
>>> df.where(m, -df)
A B
0 0 -1
1 -2 3
2 -4 -5
3 6 -7
4 -8 9
>>> df.where(m, -df) == np.where(m, df, -df)
A B
0 True True
1 True True
2 True True
3 True True
4 True True
>>> df.where(m, -df) == df.mask(~m, -df)
A B
0 True True
1 True True
2 True True
3 True True
4 True True
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
other = common.apply_if_callable(other, self)
return self._where(cond, other, inplace=inplace, axis=axis, level=level)
@final
@doc(
where,
klass=_shared_doc_kwargs["klass"],
cond="False",
cond_rev="True",
name="mask",
name_other="where",
)
def mask(
self,
cond,
other=lib.no_default,
*,
inplace: bool = False,
axis: Axis | None = None,
level: Level | None = None,
) -> Self:
inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not common.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
cond = common.apply_if_callable(cond, self)
other = common.apply_if_callable(other, self)
# see gh-21891
if not hasattr(cond, "__invert__"):
cond = np.array(cond)
return self._where(
~cond,
other=other,
inplace=inplace,
axis=axis,
level=level,
)
@doc(klass=_shared_doc_kwargs["klass"])
def shift(
self,
periods: int | Sequence[int] = 1,
freq=None,
axis: Axis = 0,
fill_value: Hashable = lib.no_default,
suffix: str | None = None,
) -> Self | DataFrame:
"""
Shift index by desired number of periods with an optional time `freq`.
When `freq` is not passed, shift the index without realigning the data.
If `freq` is passed (in this case, the index must be date or datetime,
or it will raise a `NotImplementedError`), the index will be
increased using the periods and the `freq`. `freq` can be inferred
when specified as "infer" as long as either freq or inferred_freq
attribute is set in the index.
Parameters
----------
periods : int or Sequence
Number of periods to shift. Can be positive or negative.
If an iterable of ints, the data will be shifted once by each int.
This is equivalent to shifting by one value at a time and
concatenating all resulting frames. The resulting columns will have
the shift suffixed to their column names. For multiple periods,
axis must not be 1.
freq : DateOffset, tseries.offsets, timedelta, or str, optional
Offset to use from the tseries module or time rule (e.g. 'EOM').
If `freq` is specified then the index values are shifted but the
data is not realigned. That is, use `freq` if you would like to
extend the index when shifting and preserve the original data.
If `freq` is specified as "infer" then it will be inferred from
the freq or inferred_freq attributes of the index. If neither of
those attributes exist, a ValueError is thrown.
axis : {{0 or 'index', 1 or 'columns', None}}, default None
Shift direction. For `Series` this parameter is unused and defaults to 0.
fill_value : object, optional
The scalar value to use for newly introduced missing values.
the default depends on the dtype of `self`.
For Boolean and numeric NumPy data types, ``np.nan`` is used.
For datetime, timedelta, or period data, etc. :attr:`NaT` is used.
For extension dtypes, ``self.dtype.na_value`` is used.
suffix : str, optional
If str and periods is an iterable, this is added after the column
name and before the shift value for each shifted column name.
For `Series` this parameter is unused and defaults to `None`.
Returns
-------
{klass}
Copy of input object, shifted.
See Also
--------
Index.shift : Shift values of Index.
DatetimeIndex.shift : Shift values of DatetimeIndex.
PeriodIndex.shift : Shift values of PeriodIndex.
Examples
--------
>>> df = pd.DataFrame(
... [[10, 13, 17], [20, 23, 27], [15, 18, 22], [30, 33, 37], [45, 48, 52]],
... columns=["Col1", "Col2", "Col3"],
... index=pd.date_range("2020-01-01", "2020-01-05"),
... )
>>> df
Col1 Col2 Col3
2020-01-01 10 13 17
2020-01-02 20 23 27
2020-01-03 15 18 22
2020-01-04 30 33 37
2020-01-05 45 48 52
>>> df.shift(periods=3)
Col1 Col2 Col3
2020-01-01 NaN NaN NaN
2020-01-02 NaN NaN NaN
2020-01-03 NaN NaN NaN
2020-01-04 10.0 13.0 17.0
2020-01-05 20.0 23.0 27.0
>>> df.shift(periods=1, axis="columns")
Col1 Col2 Col3
2020-01-01 NaN 10 13
2020-01-02 NaN 20 23
2020-01-03 NaN 15 18
2020-01-04 NaN 30 33
2020-01-05 NaN 45 48
>>> df.shift(periods=3, fill_value=0)
Col1 Col2 Col3
2020-01-01 0 0 0
2020-01-02 0 0 0
2020-01-03 0 0 0
2020-01-04 10 13 17
2020-01-05 20 23 27
>>> df.shift(periods=3, freq="D")
Col1 Col2 Col3
2020-01-04 10 13 17
2020-01-05 20 23 27
2020-01-06 15 18 22
2020-01-07 30 33 37
2020-01-08 45 48 52
>>> df.shift(periods=3, freq="infer")
Col1 Col2 Col3
2020-01-04 10 13 17
2020-01-05 20 23 27
2020-01-06 15 18 22
2020-01-07 30 33 37
2020-01-08 45 48 52
>>> df["Col1"].shift(periods=[0, 1, 2])
Col1_0 Col1_1 Col1_2
2020-01-01 10 NaN NaN
2020-01-02 20 10.0 NaN
2020-01-03 15 20.0 10.0
2020-01-04 30 15.0 20.0
2020-01-05 45 30.0 15.0
"""
axis = self._get_axis_number(axis)
if freq is not None and fill_value is not lib.no_default:
# GH#53832
raise ValueError(
"Passing a 'freq' together with a 'fill_value' is not allowed."
)
if periods == 0:
return self.copy(deep=False)
if is_list_like(periods) and isinstance(self, ABCSeries):
return self.to_frame().shift(
periods=periods, freq=freq, axis=axis, fill_value=fill_value
)
periods = cast(int, periods)
if freq is None:
# when freq is None, data is shifted, index is not
axis = self._get_axis_number(axis)
assert axis == 0 # axis == 1 cases handled in DataFrame.shift
new_data = self._mgr.shift(periods=periods, fill_value=fill_value)
return self._constructor_from_mgr(
new_data, axes=new_data.axes
).__finalize__(self, method="shift")
return self._shift_with_freq(periods, axis, freq)
@final
def _shift_with_freq(self, periods: int, axis: int, freq) -> Self:
# see shift.__doc__
# when freq is given, index is shifted, data is not
index = self._get_axis(axis)
if freq == "infer":
freq = getattr(index, "freq", None)
if freq is None:
freq = getattr(index, "inferred_freq", None)
if freq is None:
msg = "Freq was not set in the index hence cannot be inferred"
raise ValueError(msg)
elif isinstance(freq, str):
is_period = isinstance(index, PeriodIndex)
freq = to_offset(freq, is_period=is_period)
if isinstance(index, PeriodIndex):
orig_freq = to_offset(index.freq)
if freq != orig_freq:
assert orig_freq is not None # for mypy
raise ValueError(
f"Given freq {PeriodDtype(freq)._freqstr} "
f"does not match PeriodIndex freq "
f"{PeriodDtype(orig_freq)._freqstr}"
)
new_ax: Index = index.shift(periods)
else:
new_ax = index.shift(periods, freq)
result = self.set_axis(new_ax, axis=axis)
return result.__finalize__(self, method="shift")
@final
def truncate(
self,
before=None,
after=None,
axis: Axis | None = None,
copy: bool | lib.NoDefault = lib.no_default,
) -> Self:
"""
Truncate a Series or DataFrame before and after some index value.
This is a useful shorthand for boolean indexing based on index
values above or below certain thresholds.
Parameters
----------
before : date, str, int
Truncate all rows before this index value.
after : date, str, int
Truncate all rows after this index value.
axis : {0 or 'index', 1 or 'columns'}, optional
Axis to truncate. Truncates the index (rows) by default.
For `Series` this parameter is unused and defaults to 0.
copy : bool, default is False,
Return a copy of the truncated section.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
Returns
-------
type of caller
The truncated Series or DataFrame.
See Also
--------
DataFrame.loc : Select a subset of a DataFrame by label.
DataFrame.iloc : Select a subset of a DataFrame by position.
Notes
-----
If the index being truncated contains only datetime values,
`before` and `after` may be specified as strings instead of
Timestamps.
Examples
--------
>>> df = pd.DataFrame(
... {
... "A": ["a", "b", "c", "d", "e"],
... "B": ["f", "g", "h", "i", "j"],
... "C": ["k", "l", "m", "n", "o"],
... },
... index=[1, 2, 3, 4, 5],
... )
>>> df
A B C
1 a f k
2 b g l
3 c h m
4 d i n
5 e j o
>>> df.truncate(before=2, after=4)
A B C
2 b g l
3 c h m
4 d i n
The columns of a DataFrame can be truncated.
>>> df.truncate(before="A", after="B", axis="columns")
A B
1 a f
2 b g
3 c h
4 d i
5 e j
For Series, only rows can be truncated.
>>> df["A"].truncate(before=2, after=4)
2 b
3 c
4 d
Name: A, dtype: str
The index values in ``truncate`` can be datetimes or string
dates.
>>> dates = pd.date_range("2016-01-01", "2016-02-01", freq="s")
>>> df = pd.DataFrame(index=dates, data={"A": 1})
>>> df.tail()
A
2016-01-31 23:59:56 1
2016-01-31 23:59:57 1
2016-01-31 23:59:58 1
2016-01-31 23:59:59 1
2016-02-01 00:00:00 1
>>> df.truncate(
... before=pd.Timestamp("2016-01-05"), after=pd.Timestamp("2016-01-10")
... ).tail()
A
2016-01-09 23:59:56 1
2016-01-09 23:59:57 1
2016-01-09 23:59:58 1
2016-01-09 23:59:59 1
2016-01-10 00:00:00 1
Because the index is a DatetimeIndex containing only dates, we can
specify `before` and `after` as strings. They will be coerced to
Timestamps before truncation.
>>> df.truncate("2016-01-05", "2016-01-10").tail()
A
2016-01-09 23:59:56 1
2016-01-09 23:59:57 1
2016-01-09 23:59:58 1
2016-01-09 23:59:59 1
2016-01-10 00:00:00 1
Note that ``truncate`` assumes a 0 value for any unspecified time
component (midnight). This differs from partial string slicing, which
returns any partially matching dates.
>>> df.loc["2016-01-05":"2016-01-10", :].tail()
A
2016-01-10 23:59:55 1
2016-01-10 23:59:56 1
2016-01-10 23:59:57 1
2016-01-10 23:59:58 1
2016-01-10 23:59:59 1
"""
self._check_copy_deprecation(copy)
if axis is None:
axis = 0
axis = self._get_axis_number(axis)
ax = self._get_axis(axis)
# GH 17935
# Check that index is sorted
if not ax.is_monotonic_increasing and not ax.is_monotonic_decreasing:
raise ValueError("truncate requires a sorted index")
# if we have a date index, convert to dates, otherwise
# treat like a slice
if ax._is_all_dates:
from pandas.core.tools.datetimes import to_datetime
if before is not None:
# Avoid converting to NaT
before = to_datetime(before)
if after is not None:
# Avoid converting to NaT
after = to_datetime(after)
if before is not None and after is not None and before > after:
raise ValueError(f"Truncate: {after} must be after {before}")
if len(ax) > 1 and ax.is_monotonic_decreasing and ax.nunique() > 1:
before, after = after, before
slicer = [slice(None, None)] * self._AXIS_LEN
slicer[axis] = slice(before, after)
result = self.loc[tuple(slicer)]
if isinstance(ax, MultiIndex):
setattr(result, self._get_axis_name(axis), ax.truncate(before, after))
result = result.copy(deep=False)
return result
@final
@doc(klass=_shared_doc_kwargs["klass"])
def tz_convert(
self,
tz,
axis: Axis = 0,
level=None,
copy: bool | lib.NoDefault = lib.no_default,
) -> Self:
"""
Convert tz-aware axis to target time zone.
Parameters
----------
tz : str or tzinfo object or None
Target time zone. Passing ``None`` will convert to
UTC and remove the timezone information.
axis : {{0 or 'index', 1 or 'columns'}}, default 0
The axis to convert
level : int, str, default None
If axis is a MultiIndex, convert a specific level. Otherwise
must be None.
copy : bool, default False
Also make a copy of the underlying data.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
Returns
-------
{klass}
Object with time zone converted axis.
Raises
------
TypeError
If the axis is tz-naive.
See Also
--------
DataFrame.tz_localize: Localize tz-naive index of DataFrame to target time zone.
Series.tz_localize: Localize tz-naive index of Series to target time zone.
Examples
--------
Change to another time zone:
>>> s = pd.Series(
... [1],
... index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]),
... )
>>> s.tz_convert("Asia/Shanghai")
2018-09-15 07:30:00+08:00 1
dtype: int64
Pass None to convert to UTC and get a tz-naive index:
>>> s = pd.Series([1], index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]))
>>> s.tz_convert(None)
2018-09-14 23:30:00 1
dtype: int64
"""
self._check_copy_deprecation(copy)
axis = self._get_axis_number(axis)
ax = self._get_axis(axis)
def _tz_convert(ax, tz):
if not hasattr(ax, "tz_convert"):
if len(ax) > 0:
ax_name = self._get_axis_name(axis)
raise TypeError(
f"{ax_name} is not a valid DatetimeIndex or PeriodIndex"
)
ax = DatetimeIndex([], tz=tz)
else:
ax = ax.tz_convert(tz)
return ax
# if a level is given it must be a MultiIndex level or
# equivalent to the axis name
if isinstance(ax, MultiIndex):
level = ax._get_level_number(level)
new_level = _tz_convert(ax.levels[level], tz)
ax = ax.set_levels(new_level, level=level)
else:
if level not in (None, 0, ax.name):
raise ValueError(f"The level {level} is not valid")
ax = _tz_convert(ax, tz)
result = self.copy(deep=False)
result = result.set_axis(ax, axis=axis)
return result.__finalize__(self, method="tz_convert")
@final
@doc(klass=_shared_doc_kwargs["klass"])
def tz_localize(
self,
tz,
axis: Axis = 0,
level=None,
copy: bool | lib.NoDefault = lib.no_default,
ambiguous: TimeAmbiguous = "raise",
nonexistent: TimeNonexistent = "raise",
) -> Self:
"""
Localize time zone naive index of a Series or DataFrame to target time zone.
This operation localizes the Index. To localize the values in a
time zone naive Series, use :meth:`Series.dt.tz_localize`.
Parameters
----------
tz : str or tzinfo or None
Time zone to localize. Passing ``None`` will remove the
time zone information and preserve local time.
axis : {{0 or 'index', 1 or 'columns'}}, default 0
The axis to localize
level : int, str, default None
If axis ia a MultiIndex, localize a specific level. Otherwise
must be None.
copy : bool, default False
Also make a copy of the underlying data.
.. note::
The `copy` keyword will change behavior in pandas 3.0.
`Copy-on-Write
<https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html>`__
will be enabled by default, which means that all methods with a
`copy` keyword will use a lazy copy mechanism to defer the copy and
ignore the `copy` keyword. The `copy` keyword will be removed in a
future version of pandas.
You can already get the future behavior and improvements through
enabling copy on write ``pd.options.mode.copy_on_write = True``
.. deprecated:: 3.0.0
ambiguous : 'infer', bool, bool-ndarray, 'NaT', default 'raise'
When clocks moved backward due to DST, ambiguous times may arise.
For example in Central European Time (UTC+01), when going from
03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at
00:30:00 UTC and at 01:30:00 UTC. In such a situation, the
`ambiguous` parameter dictates how ambiguous times should be
handled.
- 'infer' will attempt to infer fall dst-transition hours based on
order
- bool (or bool-ndarray) where True signifies a DST time, False designates
a non-DST time (note that this flag is only applicable for
ambiguous times)
- 'NaT' will return NaT where there are ambiguous times
- 'raise' will raise a ValueError if there are ambiguous
times.
nonexistent : str, default 'raise'
A nonexistent time does not exist in a particular timezone
where clocks moved forward due to DST. Valid values are:
- 'shift_forward' will shift the nonexistent time forward to the
closest existing time
- 'shift_backward' will shift the nonexistent time backward to the
closest existing time
- 'NaT' will return NaT where there are nonexistent times
- timedelta objects will shift nonexistent times by the timedelta
- 'raise' will raise a ValueError if there are
nonexistent times.
Returns
-------
{klass}
Same type as the input, with time zone naive or aware index, depending on
``tz``.
Raises
------
TypeError
If the TimeSeries is tz-aware and tz is not None.
See Also
--------
Series.dt.tz_localize: Localize the values in a time zone naive Series.
Timestamp.tz_localize: Localize the Timestamp to a timezone.
Examples
--------
Localize local times:
>>> s = pd.Series(
... [1],
... index=pd.DatetimeIndex(["2018-09-15 01:30:00"]),
... )
>>> s.tz_localize("CET")
2018-09-15 01:30:00+02:00 1
dtype: int64
Pass None to convert to tz-naive index and preserve local time:
>>> s = pd.Series([1], index=pd.DatetimeIndex(["2018-09-15 01:30:00+02:00"]))
>>> s.tz_localize(None)
2018-09-15 01:30:00 1
dtype: int64
Be careful with DST changes. When there is sequential data, pandas
can infer the DST time:
>>> s = pd.Series(
... range(7),
... index=pd.DatetimeIndex(
... [
... "2018-10-28 01:30:00",
... "2018-10-28 02:00:00",
... "2018-10-28 02:30:00",
... "2018-10-28 02:00:00",
... "2018-10-28 02:30:00",
... "2018-10-28 03:00:00",
... "2018-10-28 03:30:00",
... ]
... ),
... )
>>> s.tz_localize("CET", ambiguous="infer")
2018-10-28 01:30:00+02:00 0
2018-10-28 02:00:00+02:00 1
2018-10-28 02:30:00+02:00 2
2018-10-28 02:00:00+01:00 3
2018-10-28 02:30:00+01:00 4
2018-10-28 03:00:00+01:00 5
2018-10-28 03:30:00+01:00 6
dtype: int64
In some cases, inferring the DST is impossible. In such cases, you can
pass an ndarray to the ambiguous parameter to set the DST explicitly
>>> s = pd.Series(
... range(3),
... index=pd.DatetimeIndex(
... [
... "2018-10-28 01:20:00",
... "2018-10-28 02:36:00",
... "2018-10-28 03:46:00",
... ]
... ),
... )
>>> s.tz_localize("CET", ambiguous=np.array([True, True, False]))
2018-10-28 01:20:00+02:00 0
2018-10-28 02:36:00+02:00 1
2018-10-28 03:46:00+01:00 2
dtype: int64
If the DST transition causes nonexistent times, you can shift these
dates forward or backward with a timedelta object or `'shift_forward'`
or `'shift_backward'`.
>>> dti = pd.DatetimeIndex(
... ["2015-03-29 02:30:00", "2015-03-29 03:30:00"], dtype="M8[ns]"
... )
>>> s = pd.Series(range(2), index=dti)
>>> s.tz_localize("Europe/Warsaw", nonexistent="shift_forward")
2015-03-29 03:00:00+02:00 0
2015-03-29 03:30:00+02:00 1
dtype: int64
>>> s.tz_localize("Europe/Warsaw", nonexistent="shift_backward")
2015-03-29 01:59:59.999999999+01:00 0
2015-03-29 03:30:00+02:00 1
dtype: int64
>>> s.tz_localize("Europe/Warsaw", nonexistent=pd.Timedelta("1h"))
2015-03-29 03:30:00+02:00 0
2015-03-29 03:30:00+02:00 1
dtype: int64
"""
self._check_copy_deprecation(copy)
nonexistent_options = ("raise", "NaT", "shift_forward", "shift_backward")
if nonexistent not in nonexistent_options and not isinstance(
nonexistent, dt.timedelta
):
raise ValueError(
"The nonexistent argument must be one of 'raise', "
"'NaT', 'shift_forward', 'shift_backward' or "
"a timedelta object"
)
axis = self._get_axis_number(axis)
ax = self._get_axis(axis)
def _tz_localize(ax, tz, ambiguous, nonexistent):
if not hasattr(ax, "tz_localize"):
if len(ax) > 0:
ax_name = self._get_axis_name(axis)
raise TypeError(
f"{ax_name} is not a valid DatetimeIndex or PeriodIndex"
)
ax = DatetimeIndex([], tz=tz)
else:
ax = ax.tz_localize(tz, ambiguous=ambiguous, nonexistent=nonexistent)
return ax
# if a level is given it must be a MultiIndex level or
# equivalent to the axis name
if isinstance(ax, MultiIndex):
level = ax._get_level_number(level)
new_level = _tz_localize(ax.levels[level], tz, ambiguous, nonexistent)
ax = ax.set_levels(new_level, level=level)
else:
if level not in (None, 0, ax.name):
raise ValueError(f"The level {level} is not valid")
ax = _tz_localize(ax, tz, ambiguous, nonexistent)
result = self.copy(deep=False)
result = result.set_axis(ax, axis=axis)
return result.__finalize__(self, method="tz_localize")
# ----------------------------------------------------------------------
# Numeric Methods
@final
def describe(
self,
percentiles=None,
include=None,
exclude=None,
) -> Self:
"""
Generate descriptive statistics.
Descriptive statistics include those that summarize the central
tendency, dispersion and shape of a
dataset's distribution, excluding ``NaN`` values.
Analyzes both numeric and object series, as well
as ``DataFrame`` column sets of mixed data types. The output
will vary depending on what is provided. Refer to the notes
below for more detail.
Parameters
----------
percentiles : list-like of numbers, optional
The percentiles to include in the output. All should
fall between 0 and 1. The default, ``None``, will automatically
return the 25th, 50th, and 75th percentiles.
include : 'all', list-like of dtypes or None (default), optional
A white list of data types to include in the result. Ignored
for ``Series``. Here are the options:
- 'all' : All columns of the input will be included in the output.
- A list-like of dtypes : Limits the results to the
provided data types.
To limit the result to numeric types submit
``numpy.number``. To limit it instead to object columns submit
the ``numpy.object`` data type. Strings
can also be used in the style of
``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To
select pandas categorical columns, use ``'category'``
- None (default) : The result will include all numeric columns.
exclude : list-like of dtypes or None (default), optional,
A black list of data types to omit from the result. Ignored
for ``Series``. Here are the options:
- A list-like of dtypes : Excludes the provided data types
from the result. To exclude numeric types submit
``numpy.number``. To exclude object columns submit the data
type ``numpy.object``. Strings can also be used in the style of
``select_dtypes`` (e.g. ``df.describe(exclude=['O'])``). To
exclude pandas categorical columns, use ``'category'``
- None (default) : The result will exclude nothing.
Returns
-------
Series or DataFrame
Summary statistics of the Series or Dataframe provided.
See Also
--------
DataFrame.count: Count number of non-NA/null observations.
DataFrame.max: Maximum of the values in the object.
DataFrame.min: Minimum of the values in the object.
DataFrame.mean: Mean of the values.
DataFrame.std: Standard deviation of the observations.
DataFrame.select_dtypes: Subset of a DataFrame including/excluding
columns based on their dtype.
Notes
-----
For numeric data, the result's index will include ``count``,
``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and
upper percentiles. By default the lower percentile is ``25`` and the
upper percentile is ``75``. The ``50`` percentile is the
same as the median.
For object data (e.g. strings), the result's index
will include ``count``, ``unique``, ``top``, and ``freq``. The ``top``
is the most common value. The ``freq`` is the most common value's
frequency.
If multiple object values have the highest count, then the
``count`` and ``top`` results will be arbitrarily chosen from
among those with the highest count.
For mixed data types provided via a ``DataFrame``, the default is to
return only an analysis of numeric columns. If the DataFrame consists
only of object and categorical data without any numeric columns, the
default is to return an analysis of both the object and categorical
columns. If ``include='all'`` is provided as an option, the result
will include a union of attributes of each type.
The `include` and `exclude` parameters can be used to limit
which columns in a ``DataFrame`` are analyzed for the output.
The parameters are ignored when analyzing a ``Series``.
Examples
--------
Describing a numeric ``Series``.
>>> s = pd.Series([1, 2, 3])
>>> s.describe()
count 3.0
mean 2.0
std 1.0
min 1.0
25% 1.5
50% 2.0
75% 2.5
max 3.0
dtype: float64
Describing a categorical ``Series``.
>>> s = pd.Series(["a", "a", "b", "c"])
>>> s.describe()
count 4
unique 3
top a
freq 2
dtype: object
Describing a timestamp ``Series``.
>>> s = pd.Series(
... [
... np.datetime64("2000-01-01"),
... np.datetime64("2010-01-01"),
... np.datetime64("2010-01-01"),
... ]
... )
>>> s.describe()
count 3
mean 2006-09-01 08:00:00
min 2000-01-01 00:00:00
25% 2004-12-31 12:00:00
50% 2010-01-01 00:00:00
75% 2010-01-01 00:00:00
max 2010-01-01 00:00:00
dtype: object
Describing a ``DataFrame``. By default only numeric fields
are returned.
>>> df = pd.DataFrame(
... {
... "categorical": pd.Categorical(["d", "e", "f"]),
... "numeric": [1, 2, 3],
... "object": ["a", "b", "c"],
... }
... )
>>> df.describe()
numeric
count 3.0
mean 2.0
std 1.0
min 1.0
25% 1.5
50% 2.0
75% 2.5
max 3.0
Describing all columns of a ``DataFrame`` regardless of data type.
>>> df.describe(include="all") # doctest: +SKIP
categorical numeric object
count 3 3.0 3
unique 3 NaN 3
top f NaN a
freq 1 NaN 1
mean NaN 2.0 NaN
std NaN 1.0 NaN
min NaN 1.0 NaN
25% NaN 1.5 NaN
50% NaN 2.0 NaN
75% NaN 2.5 NaN
max NaN 3.0 NaN
Describing a column from a ``DataFrame`` by accessing it as
an attribute.
>>> df.numeric.describe()
count 3.0
mean 2.0
std 1.0
min 1.0
25% 1.5
50% 2.0
75% 2.5
max 3.0
Name: numeric, dtype: float64
Including only numeric columns in a ``DataFrame`` description.
>>> df.describe(include=[np.number])
numeric
count 3.0
mean 2.0
std 1.0
min 1.0
25% 1.5
50% 2.0
75% 2.5
max 3.0
Including only string columns in a ``DataFrame`` description.
>>> df.describe(include=[object]) # doctest: +SKIP
object
count 3
unique 3
top a
freq 1
Including only categorical columns from a ``DataFrame`` description.
>>> df.describe(include=["category"])
categorical
count 3
unique 3
top d
freq 1
Excluding numeric columns from a ``DataFrame`` description.
>>> df.describe(exclude=[np.number]) # doctest: +SKIP
categorical object
count 3 3
unique 3 3
top f a
freq 1 1
Excluding object columns from a ``DataFrame`` description.
>>> df.describe(exclude=[object]) # doctest: +SKIP
categorical numeric
count 3 3.0
unique 3 NaN
top f NaN
freq 1 NaN
mean NaN 2.0
std NaN 1.0
min NaN 1.0
25% NaN 1.5
50% NaN 2.0
75% NaN 2.5
max NaN 3.0
"""
return describe_ndframe(
obj=self,
include=include,
exclude=exclude,
percentiles=percentiles,
).__finalize__(self, method="describe")
@final
def pct_change(
self,
periods: int = 1,
fill_method: None = None,
freq=None,
**kwargs,
) -> Self:
"""
Fractional change between the current and a prior element.
Computes the fractional change from the immediately previous row by
default. This is useful in comparing the fraction of change in a time
series of elements.
.. note::
Despite the name of this method, it calculates fractional change
(also known as per unit change or relative change) and not
percentage change. If you need the percentage change, multiply
these values by 100.
Parameters
----------
periods : int, default 1
Periods to shift for forming percent change.
fill_method : None
Must be None. This argument will be removed in a future version of pandas.
.. deprecated:: 2.1
All options of `fill_method` are deprecated except `fill_method=None`.
freq : DateOffset, timedelta, or str, optional
Increment to use from time series API (e.g. 'ME' or BDay()).
**kwargs
Additional keyword arguments are passed into
`DataFrame.shift` or `Series.shift`.
Returns
-------
Series or DataFrame
The same type as the calling object.
See Also
--------
Series.diff : Compute the difference of two elements in a Series.
DataFrame.diff : Compute the difference of two elements in a DataFrame.
Series.shift : Shift the index by some number of periods.
DataFrame.shift : Shift the index by some number of periods.
Examples
--------
**Series**
>>> s = pd.Series([90, 91, 85])
>>> s
0 90
1 91
2 85
dtype: int64
>>> s.pct_change()
0 NaN
1 0.011111
2 -0.065934
dtype: float64
>>> s.pct_change(periods=2)
0 NaN
1 NaN
2 -0.055556
dtype: float64
See the percentage change in a Series where filling NAs with last
valid observation forward to next valid.
>>> s = pd.Series([90, 91, None, 85])
>>> s
0 90.0
1 91.0
2 NaN
3 85.0
dtype: float64
>>> s.ffill().pct_change()
0 NaN
1 0.011111
2 0.000000
3 -0.065934
dtype: float64
**DataFrame**
Percentage change in French franc, Deutsche Mark, and Italian lira from
1980-01-01 to 1980-03-01.
>>> df = pd.DataFrame(
... {
... "FR": [4.0405, 4.0963, 4.3149],
... "GR": [1.7246, 1.7482, 1.8519],
... "IT": [804.74, 810.01, 860.13],
... },
... index=["1980-01-01", "1980-02-01", "1980-03-01"],
... )
>>> df
FR GR IT
1980-01-01 4.0405 1.7246 804.74
1980-02-01 4.0963 1.7482 810.01
1980-03-01 4.3149 1.8519 860.13
>>> df.pct_change()
FR GR IT
1980-01-01 NaN NaN NaN
1980-02-01 0.013810 0.013684 0.006549
1980-03-01 0.053365 0.059318 0.061876
Percentage of change in GOOG and APPL stock volume. Shows computing
the percentage change between columns.
>>> df = pd.DataFrame(
... {
... "2016": [1769950, 30586265],
... "2015": [1500923, 40912316],
... "2014": [1371819, 41403351],
... },
... index=["GOOG", "APPL"],
... )
>>> df
2016 2015 2014
GOOG 1769950 1500923 1371819
APPL 30586265 40912316 41403351
>>> df.pct_change(axis="columns", periods=-1)
2016 2015 2014
GOOG 0.179241 0.094112 NaN
APPL -0.252395 -0.011860 NaN
"""
# GH#53491
if fill_method is not None:
raise ValueError(f"fill_method must be None; got {fill_method=}.")
axis = self._get_axis_number(kwargs.pop("axis", "index"))
shifted = self.shift(periods=periods, freq=freq, axis=axis, **kwargs)
# Unsupported left operand type for / ("Self")
rs = self / shifted - 1 # type: ignore[operator]
if freq is not None:
# Shift method is implemented differently when freq is not None
# We want to restore the original index
rs = rs.loc[~rs.index.duplicated()]
rs = rs.reindex_like(self)
return rs.__finalize__(self, method="pct_change")
@final
def _logical_func(
self,
name: str,
func,
axis: Axis | None = 0,
bool_only: bool = False,
skipna: bool = True,
**kwargs,
) -> Series | bool:
nv.validate_logical_func((), kwargs, fname=name)
validate_bool_kwarg(skipna, "skipna", none_allowed=False)
if self.ndim > 1 and axis is None:
# Reduce along one dimension then the other, to simplify DataFrame._reduce
res = self._logical_func(
name, func, axis=0, bool_only=bool_only, skipna=skipna, **kwargs
)
# error: Item "bool" of "Series | bool" has no attribute "_logical_func"
return res._logical_func( # type: ignore[union-attr]
name, func, skipna=skipna, **kwargs
)
elif axis is None:
axis = 0
if (
self.ndim > 1
and axis == 1
and len(self._mgr.blocks) > 1
# TODO(EA2D): special-case not needed
and all(block.values.ndim == 2 for block in self._mgr.blocks)
and not kwargs
):
# Fastpath avoiding potentially expensive transpose
obj = self
if bool_only:
obj = self._get_bool_data()
return obj._reduce_axis1(name, func, skipna=skipna)
return self._reduce(
func,
name=name,
axis=axis,
skipna=skipna,
numeric_only=bool_only,
filter_type="bool",
)
def any(
self,
*,
axis: Axis | None = 0,
bool_only: bool = False,
skipna: bool = True,
**kwargs,
) -> Series | bool:
return self._logical_func(
"any", nanops.nanany, axis, bool_only, skipna, **kwargs
)
def all(
self,
*,
axis: Axis = 0,
bool_only: bool = False,
skipna: bool = True,
**kwargs,
) -> Series | bool:
return self._logical_func(
"all", nanops.nanall, axis, bool_only, skipna, **kwargs
)
@final
def _accum_func(
self,
name: str,
func,
axis: Axis | None = None,
skipna: bool = True,
*args,
**kwargs,
):
skipna = nv.validate_cum_func_with_skipna(skipna, args, kwargs, name)
if axis is None:
axis = 0
else:
axis = self._get_axis_number(axis)
if axis == 1:
return self.T._accum_func(
name,
func,
axis=0,
skipna=skipna,
*args, # noqa: B026
**kwargs,
).T
def block_accum_func(blk_values):
values = blk_values.T if hasattr(blk_values, "T") else blk_values
result: np.ndarray | ExtensionArray
if isinstance(values, ExtensionArray):
result = values._accumulate(name, skipna=skipna, **kwargs)
else:
result = nanops.na_accum_func(values, func, skipna=skipna)
result = result.T if hasattr(result, "T") else result
return result
result = self._mgr.apply(block_accum_func)
return self._constructor_from_mgr(result, axes=result.axes).__finalize__(
self, method=name
)
def cummax(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self:
return self._accum_func(
"cummax", np.maximum.accumulate, axis, skipna, *args, **kwargs
)
def cummin(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self:
return self._accum_func(
"cummin", np.minimum.accumulate, axis, skipna, *args, **kwargs
)
def cumsum(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self:
return self._accum_func("cumsum", np.cumsum, axis, skipna, *args, **kwargs)
def cumprod(self, axis: Axis = 0, skipna: bool = True, *args, **kwargs) -> Self:
return self._accum_func("cumprod", np.cumprod, axis, skipna, *args, **kwargs)
@final
def _stat_function_ddof(
self,
name: str,
func,
axis: Axis | None = 0,
skipna: bool = True,
ddof: int = 1,
numeric_only: bool = False,
**kwargs,
) -> Series | float:
nv.validate_stat_ddof_func((), kwargs, fname=name)
validate_bool_kwarg(skipna, "skipna", none_allowed=False)
return self._reduce(
func, name, axis=axis, numeric_only=numeric_only, skipna=skipna, ddof=ddof
)
def sem(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
ddof: int = 1,
numeric_only: bool = False,
**kwargs,
) -> Series | float:
return self._stat_function_ddof(
"sem", nanops.nansem, axis, skipna, ddof, numeric_only, **kwargs
)
def var(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
ddof: int = 1,
numeric_only: bool = False,
**kwargs,
) -> Series | float:
return self._stat_function_ddof(
"var", nanops.nanvar, axis, skipna, ddof, numeric_only, **kwargs
)
def std(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
ddof: int = 1,
numeric_only: bool = False,
**kwargs,
) -> Series | float:
return self._stat_function_ddof(
"std", nanops.nanstd, axis, skipna, ddof, numeric_only, **kwargs
)
@final
def _stat_function(
self,
name: str,
func,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
):
assert name in ["median", "mean", "min", "max", "kurt", "skew"], name
nv.validate_func(name, (), kwargs)
validate_bool_kwarg(skipna, "skipna", none_allowed=False)
return self._reduce(
func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only
)
def min(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
):
return self._stat_function(
"min",
nanops.nanmin,
axis,
skipna,
numeric_only,
**kwargs,
)
def max(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
):
return self._stat_function(
"max",
nanops.nanmax,
axis,
skipna,
numeric_only,
**kwargs,
)
def mean(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
) -> Series | float:
return self._stat_function(
"mean", nanops.nanmean, axis, skipna, numeric_only, **kwargs
)
def median(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
) -> Series | float:
return self._stat_function(
"median", nanops.nanmedian, axis, skipna, numeric_only, **kwargs
)
def skew(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
) -> Series | float:
return self._stat_function(
"skew", nanops.nanskew, axis, skipna, numeric_only, **kwargs
)
def kurt(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
**kwargs,
) -> Series | float:
return self._stat_function(
"kurt", nanops.nankurt, axis, skipna, numeric_only, **kwargs
)
kurtosis = kurt
@final
def _min_count_stat_function(
self,
name: str,
func,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
min_count: int = 0,
**kwargs,
):
assert name in ["sum", "prod"], name
nv.validate_func(name, (), kwargs)
validate_bool_kwarg(skipna, "skipna", none_allowed=False)
return self._reduce(
func,
name=name,
axis=axis,
skipna=skipna,
numeric_only=numeric_only,
min_count=min_count,
)
def sum(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
min_count: int = 0,
**kwargs,
):
return self._min_count_stat_function(
"sum", nanops.nansum, axis, skipna, numeric_only, min_count, **kwargs
)
def prod(
self,
*,
axis: Axis | None = 0,
skipna: bool = True,
numeric_only: bool = False,
min_count: int = 0,
**kwargs,
):
return self._min_count_stat_function(
"prod",
nanops.nanprod,
axis,
skipna,
numeric_only,
min_count,
**kwargs,
)
product = prod
@final
@doc(Rolling)
def rolling(
self,
window: int | dt.timedelta | str | BaseOffset | BaseIndexer,
min_periods: int | None = None,
center: bool = False,
win_type: str | None = None,
on: str | None = None,
closed: IntervalClosedType | None = None,
step: int | None = None,
method: str = "single",
) -> Window | Rolling:
if win_type is not None:
return Window(
self,
window=window,
min_periods=min_periods,
center=center,
win_type=win_type,
on=on,
closed=closed,
step=step,
method=method,
)
return Rolling(
self,
window=window,
min_periods=min_periods,
center=center,
win_type=win_type,
on=on,
closed=closed,
step=step,
method=method,
)
@final
@doc(Expanding)
def expanding(
self,
min_periods: int = 1,
method: Literal["single", "table"] = "single",
) -> Expanding:
return Expanding(self, min_periods=min_periods, method=method)
@final
@doc(ExponentialMovingWindow)
def ewm(
self,
com: float | None = None,
span: float | None = None,
halflife: float | TimedeltaConvertibleTypes | None = None,
alpha: float | None = None,
min_periods: int | None = 0,
adjust: bool = True,
ignore_na: bool = False,
times: np.ndarray | DataFrame | Series | None = None,
method: Literal["single", "table"] = "single",
) -> ExponentialMovingWindow:
return ExponentialMovingWindow(
self,
com=com,
span=span,
halflife=halflife,
alpha=alpha,
min_periods=min_periods,
adjust=adjust,
ignore_na=ignore_na,
times=times,
method=method,
)
# ----------------------------------------------------------------------
# Arithmetic Methods
@final
def _inplace_method(self, other, op) -> Self:
"""
Wrap arithmetic method to operate inplace.
"""
result = op(self, other)
# this makes sure that we are aligned like the input
# we are updating inplace
self._update_inplace(result.reindex_like(self))
return self
@final
def __iadd__(self, other) -> Self:
# error: Unsupported left operand type for + ("Type[NDFrame]")
return self._inplace_method(other, type(self).__add__) # type: ignore[operator]
@final
def __isub__(self, other) -> Self:
# error: Unsupported left operand type for - ("Type[NDFrame]")
return self._inplace_method(other, type(self).__sub__) # type: ignore[operator]
@final
def __imul__(self, other) -> Self:
# error: Unsupported left operand type for * ("Type[NDFrame]")
return self._inplace_method(other, type(self).__mul__) # type: ignore[operator]
@final
def __itruediv__(self, other) -> Self:
# error: Unsupported left operand type for / ("Type[NDFrame]")
return self._inplace_method(
other,
type(self).__truediv__, # type: ignore[operator]
)
@final
def __ifloordiv__(self, other) -> Self:
# error: Unsupported left operand type for // ("Type[NDFrame]")
return self._inplace_method(
other,
type(self).__floordiv__, # type: ignore[operator]
)
@final
def __imod__(self, other) -> Self:
# error: Unsupported left operand type for % ("Type[NDFrame]")
return self._inplace_method(other, type(self).__mod__) # type: ignore[operator]
@final
def __ipow__(self, other) -> Self:
# error: Unsupported left operand type for ** ("Type[NDFrame]")
return self._inplace_method(other, type(self).__pow__) # type: ignore[operator]
@final
def __iand__(self, other) -> Self:
# error: Unsupported left operand type for & ("Type[NDFrame]")
return self._inplace_method(other, type(self).__and__) # type: ignore[operator]
@final
def __ior__(self, other) -> Self:
return self._inplace_method(other, type(self).__or__)
@final
def __ixor__(self, other) -> Self:
# error: Unsupported left operand type for ^ ("Type[NDFrame]")
return self._inplace_method(other, type(self).__xor__) # type: ignore[operator]
# ----------------------------------------------------------------------
# Misc methods
@final
def _find_valid_index(self, *, how: str) -> Hashable:
"""
Retrieves the index of the first valid value.
Parameters
----------
how : {'first', 'last'}
Use this parameter to change between the first or last valid index.
Returns
-------
idx_first_valid : type of index
"""
is_valid = self.notna().values
idxpos = find_valid_index(how=how, is_valid=is_valid)
if idxpos is None:
return None
return self.index[idxpos]
@final
@doc(position="first", klass=_shared_doc_kwargs["klass"])
def first_valid_index(self) -> Hashable:
"""
Return index for {position} non-missing value or None, if no value is found.
See the :ref:`User Guide <missing_data>` for more information
on which values are considered missing.
Returns
-------
type of index
Index of {position} non-missing value.
See Also
--------
DataFrame.last_valid_index : Return index for last non-NA value or None, if
no non-NA value is found.
Series.last_valid_index : Return index for last non-NA value or None, if no
non-NA value is found.
DataFrame.isna : Detect missing values.
Examples
--------
For Series:
>>> s = pd.Series([None, 3, 4])
>>> s.first_valid_index()
1
>>> s.last_valid_index()
2
>>> s = pd.Series([None, None])
>>> print(s.first_valid_index())
None
>>> print(s.last_valid_index())
None
If all elements in Series are NA/null, returns None.
>>> s = pd.Series()
>>> print(s.first_valid_index())
None
>>> print(s.last_valid_index())
None
If Series is empty, returns None.
For DataFrame:
>>> df = pd.DataFrame({{"A": [None, None, 2], "B": [None, 3, 4]}})
>>> df
A B
0 NaN NaN
1 NaN 3.0
2 2.0 4.0
>>> df.first_valid_index()
1
>>> df.last_valid_index()
2
>>> df = pd.DataFrame({{"A": [None, None, None], "B": [None, None, None]}})
>>> df
A B
0 None None
1 None None
2 None None
>>> print(df.first_valid_index())
None
>>> print(df.last_valid_index())
None
If all elements in DataFrame are NA/null, returns None.
>>> df = pd.DataFrame()
>>> df
Empty DataFrame
Columns: []
Index: []
>>> print(df.first_valid_index())
None
>>> print(df.last_valid_index())
None
If DataFrame is empty, returns None.
"""
return self._find_valid_index(how="first")
@final
@doc(first_valid_index, position="last", klass=_shared_doc_kwargs["klass"])
def last_valid_index(self) -> Hashable:
return self._find_valid_index(how="last")
_num_doc = """
{desc}
Parameters
----------
axis : {axis_descr}
Axis for the function to be applied on.
For `Series` this parameter is unused and defaults to 0.
For DataFrames, specifying ``axis=None`` will apply the aggregation
across both axes.
.. versionadded:: 2.0.0
skipna : bool, default True
Exclude NA/null values when computing the result.
numeric_only : bool, default False
Include only float, int, boolean columns.
{min_count}\
**kwargs
Additional keyword arguments to be passed to the function.
Returns
-------
{name1} or scalar\
Value containing the calculation referenced in the description.\
{see_also}\
{examples}
"""
_sum_prod_doc = """
{desc}
Parameters
----------
axis : {axis_descr}
Axis for the function to be applied on.
For `Series` this parameter is unused and defaults to 0.
.. warning::
The behavior of DataFrame.{name} with ``axis=None`` is deprecated,
in a future version this will reduce over both axes and return a scalar
To retain the old behavior, pass axis=0 (or do not pass axis).
.. versionadded:: 2.0.0
skipna : bool, default True
Exclude NA/null values when computing the result.
numeric_only : bool, default False
Include only float, int, boolean columns. Not implemented for Series.
{min_count}\
**kwargs
Additional keyword arguments to be passed to the function.
Returns
-------
{name1} or scalar\
Value containing the calculation referenced in the description.\
{see_also}\
{examples}
"""
_num_ddof_doc = """
{desc}
Parameters
----------
axis : {axis_descr}
For `Series` this parameter is unused and defaults to 0.
.. warning::
The behavior of DataFrame.{name} with ``axis=None`` is deprecated,
in a future version this will reduce over both axes and return a scalar
To retain the old behavior, pass axis=0 (or do not pass axis).
skipna : bool, default True
Exclude NA/null values. If an entire row/column is NA, the result
will be NA.
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
numeric_only : bool, default False
Include only float, int, boolean columns. Not implemented for Series.
**kwargs :
Additional keywords have no effect but might be accepted
for compatibility with NumPy.
Returns
-------
{name1} or {name2} (if level specified)
{return_desc}
See Also
--------
{see_also}\
{notes}\
{examples}
"""
_sem_see_also = """\
scipy.stats.sem : Compute standard error of the mean.
{name2}.std : Return sample standard deviation over requested axis.
{name2}.var : Return unbiased variance over requested axis.
{name2}.mean : Return the mean of the values over the requested axis.
{name2}.median : Return the median of the values over the requested axis.
{name2}.mode : Return the mode(s) of the Series."""
_sem_return_desc = """\
Unbiased standard error of the mean over requested axis."""
_std_see_also = """\
numpy.std : Compute the standard deviation along the specified axis.
{name2}.var : Return unbiased variance over requested axis.
{name2}.sem : Return unbiased standard error of the mean over requested axis.
{name2}.mean : Return the mean of the values over the requested axis.
{name2}.median : Return the median of the values over the requested axis.
{name2}.mode : Return the mode(s) of the Series."""
_std_return_desc = """\
Standard deviation over requested axis."""
_std_notes = """
Notes
-----
To have the same behaviour as `numpy.std`, use `ddof=0` (instead of the
default `ddof=1`)"""
_std_examples = """
Examples
--------
>>> df = pd.DataFrame({'person_id': [0, 1, 2, 3],
... 'age': [21, 25, 62, 43],
... 'height': [1.61, 1.87, 1.49, 2.01]}
... ).set_index('person_id')
>>> df
age height
person_id
0 21 1.61
1 25 1.87
2 62 1.49
3 43 2.01
The standard deviation of the columns can be found as follows:
>>> df.std()
age 18.786076
height 0.237417
dtype: float64
Alternatively, `ddof=0` can be set to normalize by N instead of N-1:
>>> df.std(ddof=0)
age 16.269219
height 0.205609
dtype: float64"""
_var_examples = """
Examples
--------
>>> df = pd.DataFrame({'person_id': [0, 1, 2, 3],
... 'age': [21, 25, 62, 43],
... 'height': [1.61, 1.87, 1.49, 2.01]}
... ).set_index('person_id')
>>> df
age height
person_id
0 21 1.61
1 25 1.87
2 62 1.49
3 43 2.01
>>> df.var()
age 352.916667
height 0.056367
dtype: float64
Alternatively, ``ddof=0`` can be set to normalize by N instead of N-1:
>>> df.var(ddof=0)
age 264.687500
height 0.042275
dtype: float64"""
_bool_doc = """
{desc}
Parameters
----------
axis : {{0 or 'index', 1 or 'columns', None}}, default 0
Indicate which axis or axes should be reduced. For `Series` this parameter
is unused and defaults to 0.
* 0 / 'index' : reduce the index, return a Series whose index is the
original column labels.
* 1 / 'columns' : reduce the columns, return a Series whose index is the
original index.
* None : reduce all axes, return a scalar.
bool_only : bool, default False
Include only boolean columns. Not implemented for Series.
skipna : bool, default True
Exclude NA/null values. If the entire row/column is NA and skipna is
True, then the result will be {empty_value}, as for an empty row/column.
If skipna is False, then NA are treated as True, because these are not
equal to zero.
**kwargs : any, default None
Additional keywords have no effect but might be accepted for
compatibility with NumPy.
Returns
-------
{name2} or {name1}
If axis=None, then a scalar boolean is returned.
Otherwise a Series is returned with index matching the index argument.
{see_also}
{examples}"""
_all_desc = """\
Return whether all elements are True, potentially over an axis.
Returns True unless there at least one element within a series or
along a Dataframe axis that is False or equivalent (e.g. zero or
empty)."""
_all_examples = """\
Examples
--------
**Series**
>>> pd.Series([True, True]).all()
True
>>> pd.Series([True, False]).all()
False
>>> pd.Series([], dtype="float64").all()
True
>>> pd.Series([np.nan]).all()
True
>>> pd.Series([np.nan]).all(skipna=False)
True
**DataFrames**
Create a DataFrame from a dictionary.
>>> df = pd.DataFrame({'col1': [True, True], 'col2': [True, False]})
>>> df
col1 col2
0 True True
1 True False
Default behaviour checks if values in each column all return True.
>>> df.all()
col1 True
col2 False
dtype: bool
Specify ``axis='columns'`` to check if values in each row all return True.
>>> df.all(axis='columns')
0 True
1 False
dtype: bool
Or ``axis=None`` for whether every value is True.
>>> df.all(axis=None)
False
"""
_all_see_also = """\
See Also
--------
Series.all : Return True if all elements are True.
DataFrame.any : Return True if one (or more) elements are True.
"""
_cnum_pd_doc = """
Return cumulative {desc} over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative
{desc}.
Parameters
----------
axis : {{0 or 'index', 1 or 'columns'}}, default 0
The index or the name of the axis. 0 is equivalent to None or 'index'.
For `Series` this parameter is unused and defaults to 0.
skipna : bool, default True
Exclude NA/null values. If an entire row/column is NA, the result
will be NA.
numeric_only : bool, default False
Include only float, int, boolean columns.
*args, **kwargs
Additional keywords have no effect but might be accepted for
compatibility with NumPy.
Returns
-------
{name1} or {name2}
Return cumulative {desc} of {name1} or {name2}.
See Also
--------
core.window.expanding.Expanding.{accum_func_name} : Similar functionality
but ignores ``NaN`` values.
{name2}.{accum_func_name} : Return the {desc} over
{name2} axis.
{name2}.cummax : Return cumulative maximum over {name2} axis.
{name2}.cummin : Return cumulative minimum over {name2} axis.
{name2}.cumsum : Return cumulative sum over {name2} axis.
{name2}.cumprod : Return cumulative product over {name2} axis.
{examples}"""
_cnum_series_doc = """
Return cumulative {desc} over a DataFrame or Series axis.
Returns a DataFrame or Series of the same size containing the cumulative
{desc}.
Parameters
----------
axis : {{0 or 'index', 1 or 'columns'}}, default 0
The index or the name of the axis. 0 is equivalent to None or 'index'.
For `Series` this parameter is unused and defaults to 0.
skipna : bool, default True
Exclude NA/null values. If an entire row/column is NA, the result
will be NA.
*args, **kwargs
Additional keywords have no effect but might be accepted for
compatibility with NumPy.
Returns
-------
{name1} or {name2}
Return cumulative {desc} of {name1} or {name2}.
See Also
--------
core.window.expanding.Expanding.{accum_func_name} : Similar functionality
but ignores ``NaN`` values.
{name2}.{accum_func_name} : Return the {desc} over
{name2} axis.
{name2}.cummax : Return cumulative maximum over {name2} axis.
{name2}.cummin : Return cumulative minimum over {name2} axis.
{name2}.cumsum : Return cumulative sum over {name2} axis.
{name2}.cumprod : Return cumulative product over {name2} axis.
{examples}"""
_cummin_examples = """\
Examples
--------
**Series**
>>> s = pd.Series([2, np.nan, 5, -1, 0])
>>> s
0 2.0
1 NaN
2 5.0
3 -1.0
4 0.0
dtype: float64
By default, NA values are ignored.
>>> s.cummin()
0 2.0
1 NaN
2 2.0
3 -1.0
4 -1.0
dtype: float64
To include NA values in the operation, use ``skipna=False``
>>> s.cummin(skipna=False)
0 2.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
**DataFrame**
>>> df = pd.DataFrame([[2.0, 1.0],
... [3.0, np.nan],
... [1.0, 0.0]],
... columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
By default, iterates over rows and finds the minimum
in each column. This is equivalent to ``axis=None`` or ``axis='index'``.
>>> df.cummin()
A B
0 2.0 1.0
1 2.0 NaN
2 1.0 0.0
To iterate over columns and find the minimum in each row,
use ``axis=1``
>>> df.cummin(axis=1)
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
"""
_cumsum_examples = """\
Examples
--------
**Series**
>>> s = pd.Series([2, np.nan, 5, -1, 0])
>>> s
0 2.0
1 NaN
2 5.0
3 -1.0
4 0.0
dtype: float64
By default, NA values are ignored.
>>> s.cumsum()
0 2.0
1 NaN
2 7.0
3 6.0
4 6.0
dtype: float64
To include NA values in the operation, use ``skipna=False``
>>> s.cumsum(skipna=False)
0 2.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
**DataFrame**
>>> df = pd.DataFrame([[2.0, 1.0],
... [3.0, np.nan],
... [1.0, 0.0]],
... columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
By default, iterates over rows and finds the sum
in each column. This is equivalent to ``axis=None`` or ``axis='index'``.
>>> df.cumsum()
A B
0 2.0 1.0
1 5.0 NaN
2 6.0 1.0
To iterate over columns and find the sum in each row,
use ``axis=1``
>>> df.cumsum(axis=1)
A B
0 2.0 3.0
1 3.0 NaN
2 1.0 1.0
"""
_cumprod_examples = """\
Examples
--------
**Series**
>>> s = pd.Series([2, np.nan, 5, -1, 0])
>>> s
0 2.0
1 NaN
2 5.0
3 -1.0
4 0.0
dtype: float64
By default, NA values are ignored.
>>> s.cumprod()
0 2.0
1 NaN
2 10.0
3 -10.0
4 -0.0
dtype: float64
To include NA values in the operation, use ``skipna=False``
>>> s.cumprod(skipna=False)
0 2.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
**DataFrame**
>>> df = pd.DataFrame([[2.0, 1.0],
... [3.0, np.nan],
... [1.0, 0.0]],
... columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
By default, iterates over rows and finds the product
in each column. This is equivalent to ``axis=None`` or ``axis='index'``.
>>> df.cumprod()
A B
0 2.0 1.0
1 6.0 NaN
2 6.0 0.0
To iterate over columns and find the product in each row,
use ``axis=1``
>>> df.cumprod(axis=1)
A B
0 2.0 2.0
1 3.0 NaN
2 1.0 0.0
"""
_cummax_examples = """\
Examples
--------
**Series**
>>> s = pd.Series([2, np.nan, 5, -1, 0])
>>> s
0 2.0
1 NaN
2 5.0
3 -1.0
4 0.0
dtype: float64
By default, NA values are ignored.
>>> s.cummax()
0 2.0
1 NaN
2 5.0
3 5.0
4 5.0
dtype: float64
To include NA values in the operation, use ``skipna=False``
>>> s.cummax(skipna=False)
0 2.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
**DataFrame**
>>> df = pd.DataFrame([[2.0, 1.0],
... [3.0, np.nan],
... [1.0, 0.0]],
... columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
By default, iterates over rows and finds the maximum
in each column. This is equivalent to ``axis=None`` or ``axis='index'``.
>>> df.cummax()
A B
0 2.0 1.0
1 3.0 NaN
2 3.0 1.0
To iterate over columns and find the maximum in each row,
use ``axis=1``
>>> df.cummax(axis=1)
A B
0 2.0 2.0
1 3.0 NaN
2 1.0 1.0
"""
_any_see_also = """\
See Also
--------
numpy.any : Numpy version of this method.
Series.any : Return whether any element is True.
Series.all : Return whether all elements are True.
DataFrame.any : Return whether any element is True over requested axis.
DataFrame.all : Return whether all elements are True over requested axis.
"""
_any_desc = """\
Return whether any element is True, potentially over an axis.
Returns False unless there is at least one element within a series or
along a Dataframe axis that is True or equivalent (e.g. non-zero or
non-empty)."""
_any_examples = """\
Examples
--------
**Series**
For Series input, the output is a scalar indicating whether any element
is True.
>>> pd.Series([False, False]).any()
False
>>> pd.Series([True, False]).any()
True
>>> pd.Series([], dtype="float64").any()
False
>>> pd.Series([np.nan]).any()
False
>>> pd.Series([np.nan]).any(skipna=False)
True
**DataFrame**
Whether each column contains at least one True element (the default).
>>> df = pd.DataFrame({"A": [1, 2], "B": [0, 2], "C": [0, 0]})
>>> df
A B C
0 1 0 0
1 2 2 0
>>> df.any()
A True
B True
C False
dtype: bool
Aggregating over the columns.
>>> df = pd.DataFrame({"A": [True, False], "B": [1, 2]})
>>> df
A B
0 True 1
1 False 2
>>> df.any(axis='columns')
0 True
1 True
dtype: bool
>>> df = pd.DataFrame({"A": [True, False], "B": [1, 0]})
>>> df
A B
0 True 1
1 False 0
>>> df.any(axis='columns')
0 True
1 False
dtype: bool
Aggregating over the entire DataFrame with ``axis=None``.
>>> df.any(axis=None)
True
`any` for an empty DataFrame is an empty Series.
>>> pd.DataFrame([]).any()
Series([], dtype: bool)
"""
_shared_docs["stat_func_example"] = """
Examples
--------
>>> idx = pd.MultiIndex.from_arrays([
... ['warm', 'warm', 'cold', 'cold'],
... ['dog', 'falcon', 'fish', 'spider']],
... names=['blooded', 'animal'])
>>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx)
>>> s
blooded animal
warm dog 4
falcon 2
cold fish 0
spider 8
Name: legs, dtype: int64
>>> s.{stat_func}()
{default_output}"""
_sum_examples = _shared_docs["stat_func_example"].format(
stat_func="sum", verb="Sum", default_output=14, level_output_0=6, level_output_1=8
)
_sum_examples += """
By default, the sum of an empty or all-NA Series is ``0``.
>>> pd.Series([], dtype="float64").sum() # min_count=0 is the default
0.0
This can be controlled with the ``min_count`` parameter. For example, if
you'd like the sum of an empty series to be NaN, pass ``min_count=1``.
>>> pd.Series([], dtype="float64").sum(min_count=1)
nan
Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and
empty series identically.
>>> pd.Series([np.nan]).sum()
0.0
>>> pd.Series([np.nan]).sum(min_count=1)
nan"""
_max_examples: str = _shared_docs["stat_func_example"].format(
stat_func="max", verb="Max", default_output=8, level_output_0=4, level_output_1=8
)
_min_examples: str = _shared_docs["stat_func_example"].format(
stat_func="min", verb="Min", default_output=0, level_output_0=2, level_output_1=0
)
_skew_see_also = """
See Also
--------
Series.skew : Return unbiased skew over requested axis.
Series.var : Return unbiased variance over requested axis.
Series.std : Return unbiased standard deviation over requested axis."""
_stat_func_see_also = """
See Also
--------
Series.sum : Return the sum.
Series.min : Return the minimum.
Series.max : Return the maximum.
Series.idxmin : Return the index of the minimum.
Series.idxmax : Return the index of the maximum.
DataFrame.sum : Return the sum over the requested axis.
DataFrame.min : Return the minimum over the requested axis.
DataFrame.max : Return the maximum over the requested axis.
DataFrame.idxmin : Return the index of the minimum over the requested axis.
DataFrame.idxmax : Return the index of the maximum over the requested axis."""
_prod_examples = """
Examples
--------
By default, the product of an empty or all-NA Series is ``1``
>>> pd.Series([], dtype="float64").prod()
1.0
This can be controlled with the ``min_count`` parameter
>>> pd.Series([], dtype="float64").prod(min_count=1)
nan
Thanks to the ``skipna`` parameter, ``min_count`` handles all-NA and
empty series identically.
>>> pd.Series([np.nan]).prod()
1.0
>>> pd.Series([np.nan]).prod(min_count=1)
nan"""
_min_count_stub = """\
min_count : int, default 0
The required number of valid values to perform the operation. If fewer than
``min_count`` non-NA values are present the result will be NA.
"""
def make_doc(name: str, ndim: int) -> str:
"""
Generate the docstring for a Series/DataFrame reduction.
"""
if ndim == 1:
name1 = "scalar"
name2 = "Series"
axis_descr = "{index (0)}"
else:
name1 = "Series"
name2 = "DataFrame"
axis_descr = "{index (0), columns (1)}"
if name == "any":
base_doc = _bool_doc
desc = _any_desc
see_also = _any_see_also
examples = _any_examples
kwargs = {"empty_value": "False"}
elif name == "all":
base_doc = _bool_doc
desc = _all_desc
see_also = _all_see_also
examples = _all_examples
kwargs = {"empty_value": "True"}
elif name == "min":
base_doc = _num_doc
desc = (
"Return the minimum of the values over the requested axis.\n\n"
"If you want the *index* of the minimum, use ``idxmin``. This is "
"the equivalent of the ``numpy.ndarray`` method ``argmin``."
)
see_also = _stat_func_see_also
examples = _min_examples
kwargs = {"min_count": ""}
elif name == "max":
base_doc = _num_doc
desc = (
"Return the maximum of the values over the requested axis.\n\n"
"If you want the *index* of the maximum, use ``idxmax``. This is "
"the equivalent of the ``numpy.ndarray`` method ``argmax``."
)
see_also = _stat_func_see_also
examples = _max_examples
kwargs = {"min_count": ""}
elif name == "sum":
base_doc = _sum_prod_doc
desc = (
"Return the sum of the values over the requested axis.\n\n"
"This is equivalent to the method ``numpy.sum``."
)
see_also = _stat_func_see_also
examples = _sum_examples
kwargs = {"min_count": _min_count_stub}
elif name == "prod":
base_doc = _sum_prod_doc
desc = "Return the product of the values over the requested axis."
see_also = _stat_func_see_also
examples = _prod_examples
kwargs = {"min_count": _min_count_stub}
elif name == "median":
base_doc = _num_doc
desc = "Return the median of the values over the requested axis."
see_also = _stat_func_see_also
examples = """
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.median()
2.0
With a DataFrame
>>> df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]}, index=['tiger', 'zebra'])
>>> df
a b
tiger 1 2
zebra 2 3
>>> df.median()
a 1.5
b 2.5
dtype: float64
Using axis=1
>>> df.median(axis=1)
tiger 1.5
zebra 2.5
dtype: float64
In this case, `numeric_only` should be set to `True`
to avoid getting an error.
>>> df = pd.DataFrame({'a': [1, 2], 'b': ['T', 'Z']},
... index=['tiger', 'zebra'])
>>> df.median(numeric_only=True)
a 1.5
dtype: float64"""
kwargs = {"min_count": ""}
elif name == "mean":
base_doc = _num_doc
desc = "Return the mean of the values over the requested axis."
see_also = _stat_func_see_also
examples = """
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.mean()
2.0
With a DataFrame
>>> df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]}, index=['tiger', 'zebra'])
>>> df
a b
tiger 1 2
zebra 2 3
>>> df.mean()
a 1.5
b 2.5
dtype: float64
Using axis=1
>>> df.mean(axis=1)
tiger 1.5
zebra 2.5
dtype: float64
In this case, `numeric_only` should be set to `True` to avoid
getting an error.
>>> df = pd.DataFrame({'a': [1, 2], 'b': ['T', 'Z']},
... index=['tiger', 'zebra'])
>>> df.mean(numeric_only=True)
a 1.5
dtype: float64"""
kwargs = {"min_count": ""}
elif name == "var":
base_doc = _num_ddof_doc
desc = (
"Return unbiased variance over requested axis.\n\nNormalized by "
"N-1 by default. This can be changed using the ddof argument."
)
examples = _var_examples
see_also = ""
kwargs = {"notes": ""}
elif name == "std":
base_doc = _num_ddof_doc
desc = (
"Return sample standard deviation over requested axis."
"\n\nNormalized by N-1 by default. This can be changed using the "
"ddof argument."
)
examples = _std_examples
see_also = _std_see_also.format(name2=name2)
kwargs = {"notes": "", "return_desc": _std_return_desc}
elif name == "sem":
base_doc = _num_ddof_doc
desc = (
"Return unbiased standard error of the mean over requested "
"axis.\n\nNormalized by N-1 by default. This can be changed "
"using the ddof argument"
)
examples = """
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.sem().round(6)
0.57735
With a DataFrame
>>> df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]}, index=['tiger', 'zebra'])
>>> df
a b
tiger 1 2
zebra 2 3
>>> df.sem()
a 0.5
b 0.5
dtype: float64
Using axis=1
>>> df.sem(axis=1)
tiger 0.5
zebra 0.5
dtype: float64
In this case, `numeric_only` should be set to `True`
to avoid getting an error.
>>> df = pd.DataFrame({'a': [1, 2], 'b': ['T', 'Z']},
... index=['tiger', 'zebra'])
>>> df.sem(numeric_only=True)
a 0.5
dtype: float64"""
see_also = _sem_see_also.format(name2=name2)
kwargs = {"notes": "", "return_desc": _sem_return_desc}
elif name == "skew":
base_doc = _num_doc
desc = "Return unbiased skew over requested axis.\n\nNormalized by N-1."
see_also = _skew_see_also
examples = """
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.skew()
0.0
With a DataFrame
>>> df = pd.DataFrame({'a': [1, 2, 3], 'b': [2, 3, 4], 'c': [1, 3, 5]},
... index=['tiger', 'zebra', 'cow'])
>>> df
a b c
tiger 1 2 1
zebra 2 3 3
cow 3 4 5
>>> df.skew()
a 0.0
b 0.0
c 0.0
dtype: float64
Using axis=1
>>> df.skew(axis=1)
tiger 1.732051
zebra -1.732051
cow 0.000000
dtype: float64
In this case, `numeric_only` should be set to `True` to avoid
getting an error.
>>> df = pd.DataFrame({'a': [1, 2, 3], 'b': ['T', 'Z', 'X']},
... index=['tiger', 'zebra', 'cow'])
>>> df.skew(numeric_only=True)
a 0.0
dtype: float64"""
kwargs = {"min_count": ""}
elif name == "kurt":
base_doc = _num_doc
desc = (
"Return unbiased kurtosis over requested axis.\n\n"
"Kurtosis obtained using Fisher's definition of\n"
"kurtosis (kurtosis of normal == 0.0). Normalized "
"by N-1."
)
see_also = ""
examples = """
Examples
--------
>>> s = pd.Series([1, 2, 2, 3], index=['cat', 'dog', 'dog', 'mouse'])
>>> s
cat 1
dog 2
dog 2
mouse 3
dtype: int64
>>> s.kurt()
1.5
With a DataFrame
>>> df = pd.DataFrame({'a': [1, 2, 2, 3], 'b': [3, 4, 4, 4]},
... index=['cat', 'dog', 'dog', 'mouse'])
>>> df
a b
cat 1 3
dog 2 4
dog 2 4
mouse 3 4
>>> df.kurt()
a 1.5
b 4.0
dtype: float64
With axis=None
>>> df.kurt(axis=None).round(6)
-0.988693
Using axis=1
>>> df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [3, 4], 'd': [1, 2]},
... index=['cat', 'dog'])
>>> df.kurt(axis=1)
cat -6.0
dog -6.0
dtype: float64"""
kwargs = {"min_count": ""}
elif name == "cumsum":
if ndim == 1:
base_doc = _cnum_series_doc
else:
base_doc = _cnum_pd_doc
desc = "sum"
see_also = ""
examples = _cumsum_examples
kwargs = {"accum_func_name": "sum"}
elif name == "cumprod":
if ndim == 1:
base_doc = _cnum_series_doc
else:
base_doc = _cnum_pd_doc
desc = "product"
see_also = ""
examples = _cumprod_examples
kwargs = {"accum_func_name": "prod"}
elif name == "cummin":
if ndim == 1:
base_doc = _cnum_series_doc
else:
base_doc = _cnum_pd_doc
desc = "minimum"
see_also = ""
examples = _cummin_examples
kwargs = {"accum_func_name": "min"}
elif name == "cummax":
if ndim == 1:
base_doc = _cnum_series_doc
else:
base_doc = _cnum_pd_doc
desc = "maximum"
see_also = ""
examples = _cummax_examples
kwargs = {"accum_func_name": "max"}
else:
raise NotImplementedError
docstr = base_doc.format(
desc=desc,
name=name,
name1=name1,
name2=name2,
axis_descr=axis_descr,
see_also=see_also,
examples=examples,
**kwargs,
)
return docstr
| NDFrame |
python | realpython__materials | queue/src/multiprocess_queue.py | {
"start": 719,
"end": 1106
} | class ____:
combinations: Combinations
start_index: int
stop_index: int
def __call__(self, hash_value):
for index in range(self.start_index, self.stop_index):
text_bytes = self.combinations[index].encode("utf-8")
hashed = md5(text_bytes).hexdigest()
if hashed == hash_value:
return text_bytes.decode("utf-8")
| Job |
python | pennersr__django-allauth | allauth/headless/tokens/response.py | {
"start": 123,
"end": 440
} | class ____(APIResponse):
def __init__(
self, request: HttpRequest, access_token: str, refresh_token: Optional[str]
):
data = {"access_token": access_token}
if refresh_token:
data["refresh_token"] = refresh_token
super().__init__(request, data=data)
| RefreshTokenResponse |
python | explosion__spaCy | spacy/lang/tn/__init__.py | {
"start": 160,
"end": 293
} | class ____(BaseDefaults):
infixes = TOKENIZER_INFIXES
stop_words = STOP_WORDS
lex_attr_getters = LEX_ATTRS
| SetswanaDefaults |
python | PrefectHQ__prefect | src/prefect/server/database/orm_models.py | {
"start": 1643,
"end": 4720
} | class ____(DeclarativeBase):
"""
Base SQLAlchemy model that automatically infers the table name
and provides ID, created, and updated columns
"""
registry: ClassVar[RegistryType] = registry(
metadata=sa.schema.MetaData(
# define naming conventions for our Base class to use
# sqlalchemy will use the following templated strings
# to generate the names of indices, constraints, and keys
#
# we offset the table name with two underscores (__) to
# help differentiate, for example, between "flow_run.state_type"
# and "flow_run_state.type".
#
# more information on this templating and available
# customization can be found here
# https://docs.sqlalchemy.org/en/14/core/metadata.html#sqlalchemy.schema.MetaData
#
# this also allows us to avoid having to specify names explicitly
# when using sa.ForeignKey.use_alter = True
# https://docs.sqlalchemy.org/en/14/core/constraints.html
naming_convention={
"ix": "ix_%(table_name)s__%(column_0_N_name)s",
"uq": "uq_%(table_name)s__%(column_0_N_name)s",
"ck": "ck_%(table_name)s__%(constraint_name)s",
"fk": "fk_%(table_name)s__%(column_0_N_name)s__%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
),
type_annotation_map={
uuid.UUID: UUID,
DateTime: Timestamp,
},
)
# required in order to access columns with server defaults
# or SQL expression defaults, subsequent to a flush, without
# triggering an expired load
#
# this allows us to load attributes with a server default after
# an INSERT, for example
#
# https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#preventing-implicit-io-when-using-asyncsession
__mapper_args__: dict[str, Any] = {"eager_defaults": True}
def __repr__(self) -> str:
return f"{self.__class__.__name__}(id={self.id})"
@declared_attr.directive
def __tablename__(cls) -> str:
"""
By default, turn the model's camel-case class name
into a snake-case table name. Override by providing
an explicit `__tablename__` class property.
"""
return CAMEL_TO_SNAKE.sub("_", cls.__name__).lower()
id: Mapped[uuid.UUID] = mapped_column(
primary_key=True,
server_default=GenerateUUID(),
default=uuid.uuid4,
)
created: Mapped[DateTime] = mapped_column(
server_default=sa.func.now(), default=lambda: now("UTC")
)
# onupdate is only called when statements are actually issued
# against the database. until COMMIT is issued, this column
# will not be updated
updated: Mapped[DateTime] = mapped_column(
index=True,
server_default=sa.func.now(),
default=lambda: now("UTC"),
onupdate=sa.func.now(),
server_onupdate=FetchedValue(),
)
| Base |
python | getsentry__sentry | src/sentry/sentry_apps/token_exchange/grant_exchanger.py | {
"start": 1159,
"end": 6207
} | class ____:
"""
Exchanges a Grant Code for an Access Token
"""
install: SentryAppInstallation
code: str
client_id: str
user: User
def run(self) -> ApiToken:
with SentryAppInteractionEvent(
operation_type=SentryAppInteractionType.AUTHORIZATIONS,
event_type=SentryAppEventType.GRANT_EXCHANGER,
).capture() as lifecycle:
with transaction.atomic(using=router.db_for_write(ApiToken)):
try:
lifecycle.add_extras(
{
"application_id": self.application.id,
"grant_id": self.grant.id,
"installation_id": self.install.id,
"organization_id": self.install.organization_id,
"user_id": self.user.id,
}
)
lock = locks.get(
ApiGrant.get_lock_key(self.grant.id),
duration=10,
name="api_grant",
)
# we use a lock to prevent race conditions when creating the ApiToken
# an attacker could send two requests to create an access/refresh token pair
# at the same time, using the same grant, and get two different tokens
with lock.acquire():
self._validate()
token = self._create_token()
# Once it's exchanged it's no longer valid and should not be
# exchangeable, so we delete it.
self._delete_grant()
except SentryAppIntegratorError as e:
lifecycle.record_halt(halt_reason=e)
raise
self.record_analytics()
return token
def record_analytics(self) -> None:
analytics.record(
SentryAppTokenExchangedEvent(
sentry_app_installation_id=self.install.id,
exchange_type="authorization",
)
)
def _validate(self) -> None:
Validator(install=self.install, client_id=self.client_id, user=self.user).run()
if not self._grant_belongs_to_install() or not self._sentry_app_user_owns_grant():
raise SentryAppIntegratorError(message="Forbidden grant", status_code=401)
if not self._grant_is_active():
raise SentryAppIntegratorError("Grant has already expired", status_code=401)
def _grant_belongs_to_install(self) -> bool:
return self.grant.sentry_app_installation.id == self.install.id
def _sentry_app_user_owns_grant(self) -> bool:
return self.grant.application.owner == self.user
def _grant_is_active(self) -> bool:
return self.grant.expires_at > datetime.now(timezone.utc)
def _delete_grant(self) -> None:
# This will cause a set null to trigger which does not need to cascade an outbox
with unguarded_write(router.db_for_write(ApiGrant)):
self.grant.delete()
def _create_token(self) -> ApiToken:
token = ApiToken.objects.create(
user=self.user,
application=self.application,
scope_list=self.sentry_app.scope_list,
expires_at=token_expiration(),
)
try:
SentryAppInstallation.objects.get(id=self.install.id).update(api_token=token)
except SentryAppInstallation.DoesNotExist:
pass
return token
@cached_property
def grant(self) -> ApiGrant:
try:
return (
ApiGrant.objects.select_related("sentry_app_installation")
.select_related("application")
.select_related("application__sentry_app")
.get(code=self.code)
)
except ApiGrant.DoesNotExist:
raise SentryAppIntegratorError(
"Could not find grant for given code",
webhook_context={"code": self.code, "installation_uuid": self.install.uuid},
status_code=401,
)
@property
def application(self) -> ApiApplication:
try:
return self.grant.application
except ApiApplication.DoesNotExist:
raise SentryAppSentryError(
"Could not find application from grant",
status_code=401,
webhook_context={
"code": self.code[:SENSITIVE_CHARACTER_LIMIT],
"grant_id": self.grant.id,
},
)
@property
def sentry_app(self) -> SentryApp:
try:
return self.application.sentry_app
except SentryApp.DoesNotExist:
raise SentryAppSentryError(
"Could not find integration from application",
status_code=401,
webhook_context={"application_id": self.application.id},
)
| GrantExchanger |
python | pydantic__pydantic | pydantic-core/tests/validators/test_complex.py | {
"start": 6166,
"end": 6370
} | class ____:
"""Object that defines __complex__() method"""
def __init__(self, value):
self.value = value
def __complex__(self):
return complex(self.value, 0)
| ComplexWithComplex |
python | catalyst-team__catalyst | catalyst/contrib/losses/recsys.py | {
"start": 7269,
"end": 10120
} | class ____(Function):
"""Autograd function of WARP loss."""
@staticmethod
def forward(
ctx: nn.Module,
outputs: torch.Tensor,
targets: torch.Tensor,
max_num_trials: Optional[int] = None,
):
batch_size = targets.size()[0]
if max_num_trials is None:
max_num_trials = targets.size()[1] - 1
positive_indices = torch.zeros(outputs.size())
negative_indices = torch.zeros(outputs.size())
L = torch.zeros(outputs.size()[0])
all_labels_idx = torch.arange(targets.size()[1])
Y = float(targets.size()[1])
J = torch.nonzero(targets)
for i in range(batch_size):
msk = torch.ones(targets.size()[1], dtype=bool)
# Find the positive label for this example
j = J[i, 1]
positive_indices[i, j] = 1
msk[j] = False
# initialize the sample_score_margin
sample_score_margin = -1
num_trials = 0
neg_labels_idx = all_labels_idx[msk]
while (sample_score_margin < 0) and (num_trials < max_num_trials): # type: ignore
# randomly sample a negative label, example from here:
# https://github.com/pytorch/pytorch/issues/16897
neg_idx = neg_labels_idx[torch.randint(0, neg_labels_idx.size(0), (1,))]
msk[neg_idx] = False
neg_labels_idx = all_labels_idx[msk]
num_trials += 1
# calculate the score margin
sample_score_margin = 1 + outputs[i, neg_idx] - outputs[i, j]
if sample_score_margin < 0:
# checks if no violating examples have been found
continue
else:
loss_weight = np.log(np.floor((Y - 1) / (num_trials)))
L[i] = loss_weight
negative_indices[i, neg_idx] = 1 # type: ignore
loss = L * (
1
- torch.sum(positive_indices * outputs, dim=1)
+ torch.sum(negative_indices * outputs, dim=1)
)
ctx.save_for_backward(outputs, targets)
ctx.L = L
ctx.positive_indices = positive_indices
ctx.negative_indices = negative_indices
return torch.sum(loss, dim=0, keepdim=True)
# This function has only a single output, so it gets only one gradient
@staticmethod
def backward(ctx, grad_output):
outputs, targets = ctx.saved_variables
L = Variable(torch.unsqueeze(ctx.L, 1), requires_grad=False)
positive_indices = Variable(ctx.positive_indices, requires_grad=False)
negative_indices = Variable(ctx.negative_indices, requires_grad=False)
grad_input = grad_output * L * (negative_indices - positive_indices)
return grad_input, None, None
| WARP |
python | astropy__astropy | astropy/cosmology/_src/tests/io/test_yaml.py | {
"start": 5852,
"end": 6942
} | class ____(ToFromDirectTestBase, ToFromYAMLTestMixin):
"""
Directly test ``to/from_yaml``.
These are not public API and are discouraged from use, in favor of
``Cosmology.to/from_format(..., format="yaml")``, but should be tested
regardless b/c 3rd party packages might use these in their Cosmology I/O.
Also, it's cheap to test.
"""
def setup_class(self):
"""Set up fixtures to use ``to/from_yaml``, not the I/O abstractions."""
self.functions = {"to": to_yaml, "from": from_yaml}
@pytest.fixture(scope="class", autouse=True)
def setup(self):
"""
Setup and teardown for tests.
This overrides from super because `ToFromDirectTestBase` adds a custom
Cosmology ``CosmologyWithKwargs`` that is not registered with YAML.
"""
return # run tests
def test_from_yaml_autoidentify(self, cosmo, to_format, from_format):
"""
If directly calling the function there's no auto-identification.
So this overrides the test from `ToFromYAMLTestMixin`
"""
| TestToFromYAML |
python | has2k1__plotnine | plotnine/scales/scale_stroke.py | {
"start": 1308,
"end": 1657
} | class ____(scale_stroke_ordinal):
"""
Discrete Stroke Scale
"""
_aesthetics = ["stroke"]
def __post_init__(self, range):
warn(
"Using stroke for a ordinal variable is not advised.",
PlotnineWarning,
)
super().__post_init__(
range,
)
@alias
| scale_stroke_discrete |
python | django__django | tests/contenttypes_tests/models.py | {
"start": 2461,
"end": 2776
} | class ____(models.Model):
title = models.CharField(max_length=200)
site = models.ForeignKey(Site, null=True, on_delete=models.CASCADE)
post = models.ForeignKey(Post, null=True, on_delete=models.CASCADE)
def get_absolute_url(self):
return "/title/%s/" % quote(self.title)
| ModelWithNullFKToSite |
python | pytorch__pytorch | torch/utils/data/datapipes/_decorator.py | {
"start": 6515,
"end": 7757
} | class ____:
prev: bool
def __init__(self) -> None:
global _runtime_validation_enabled
self.prev = _runtime_validation_enabled
_runtime_validation_enabled = False
def __enter__(self) -> None:
pass
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
global _runtime_validation_enabled
_runtime_validation_enabled = self.prev
# Runtime checking
# Validate output data is subtype of return hint
def runtime_validation(f):
# TODO:
# Can be extended to validate '__getitem__' and nonblocking
if f.__name__ != "__iter__":
raise TypeError(
f"Can not decorate function {f.__name__} with 'runtime_validation'"
)
@wraps(f)
def wrapper(self):
global _runtime_validation_enabled
if not _runtime_validation_enabled:
yield from f(self)
else:
it = f(self)
for d in it:
if not self.type.issubtype_of_instance(d):
raise RuntimeError(
f"Expected an instance as subtype of {self.type}, but found {d}({type(d)})"
)
yield d
return wrapper
| runtime_validation_disabled |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 23962,
"end": 24930
} | class ____(TestCase):
validator = None
@staticmethod
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
if env['PATH_INFO'] == '/readline':
data = env['wsgi.input'].readline(-1)
return [data]
def test_negative_chunked_readline(self):
data = (b'POST /readline HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n'
b'Transfer-Encoding: chunked\r\n\r\n'
b'2\r\noh\r\n4\r\n hai\r\n0\r\n\r\n')
with self.makefile() as fd:
fd.write(data)
read_http(fd, body='oh hai')
def test_negative_nonchunked_readline(self):
data = (b'POST /readline HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n'
b'Content-Length: 6\r\n\r\n'
b'oh hai')
with self.makefile() as fd:
fd.write(data)
read_http(fd, body='oh hai')
| TestNegativeReadline |
python | wandb__wandb | wandb/integration/xgboost/xgboost.py | {
"start": 1227,
"end": 6495
} | class ____(xgb.callback.TrainingCallback):
"""`WandbCallback` automatically integrates XGBoost with wandb.
Args:
log_model: (boolean) if True save and upload the model to Weights & Biases Artifacts
log_feature_importance: (boolean) if True log a feature importance bar plot
importance_type: (str) one of {weight, gain, cover, total_gain, total_cover} for tree model. weight for linear model.
define_metric: (boolean) if True (default) capture model performance at the best step, instead of the last step, of training in your `wandb.summary`.
Passing `WandbCallback` to XGBoost will:
- log the booster model configuration to Weights & Biases
- log evaluation metrics collected by XGBoost, such as rmse, accuracy etc. to Weights & Biases
- log training metric collected by XGBoost (if you provide training data to eval_set)
- log the best score and the best iteration
- save and upload your trained model to Weights & Biases Artifacts (when `log_model = True`)
- log feature importance plot when `log_feature_importance=True` (default).
- Capture the best eval metric in `wandb.summary` when `define_metric=True` (default).
Example:
```python
bst_params = dict(
objective="reg:squarederror",
colsample_bytree=0.3,
learning_rate=0.1,
max_depth=5,
alpha=10,
n_estimators=10,
tree_method="hist",
callbacks=[WandbCallback()],
)
xg_reg = xgb.XGBRegressor(**bst_params)
xg_reg.fit(
X_train,
y_train,
eval_set=[(X_test, y_test)],
)
```
"""
def __init__(
self,
log_model: bool = False,
log_feature_importance: bool = True,
importance_type: str = "gain",
define_metric: bool = True,
):
self.log_model: bool = log_model
self.log_feature_importance: bool = log_feature_importance
self.importance_type: str = importance_type
self.define_metric: bool = define_metric
if wandb.run is None:
raise wandb.Error("You must call wandb.init() before WandbCallback()")
with wb_telemetry.context() as tel:
tel.feature.xgboost_wandb_callback = True
def before_training(self, model: Booster) -> Booster:
"""Run before training is finished."""
# Update W&B config
config = model.save_config()
wandb.config.update(json.loads(config))
return model
def after_training(self, model: Booster) -> Booster:
"""Run after training is finished."""
# Log the booster model as artifacts
if self.log_model:
self._log_model_as_artifact(model)
# Plot feature importance
if self.log_feature_importance:
self._log_feature_importance(model)
# Log the best score and best iteration
if model.attr("best_score") is not None:
wandb.log(
{
"best_score": float(cast(str, model.attr("best_score"))),
"best_iteration": int(cast(str, model.attr("best_iteration"))),
}
)
return model
def after_iteration(self, model: Booster, epoch: int, evals_log: dict) -> bool:
"""Run after each iteration. Return True when training should stop."""
# Log metrics
for data, metric in evals_log.items():
for metric_name, log in metric.items():
if self.define_metric:
self._define_metric(data, metric_name)
wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False)
else:
wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False)
wandb.log({"epoch": epoch})
self.define_metric = False
return False
def _log_model_as_artifact(self, model: Booster) -> None:
model_name = f"{wandb.run.id}_model.json" # type: ignore
model_path = Path(wandb.run.dir) / model_name # type: ignore
model.save_model(str(model_path))
model_artifact = wandb.Artifact(name=model_name, type="model")
model_artifact.add_file(str(model_path))
wandb.log_artifact(model_artifact)
def _log_feature_importance(self, model: Booster) -> None:
fi = model.get_score(importance_type=self.importance_type)
fi_data = [[k, fi[k]] for k in fi]
table = wandb.Table(data=fi_data, columns=["Feature", "Importance"])
wandb.log(
{
"Feature Importance": wandb.plot.bar(
table, "Feature", "Importance", title="Feature Importance"
)
}
)
def _define_metric(self, data: str, metric_name: str) -> None:
if "loss" in str.lower(metric_name):
wandb.define_metric(f"{data}-{metric_name}", summary="min")
elif str.lower(metric_name) in MINIMIZE_METRICS:
wandb.define_metric(f"{data}-{metric_name}", summary="min")
elif str.lower(metric_name) in MAXIMIZE_METRICS:
wandb.define_metric(f"{data}-{metric_name}", summary="max")
else:
pass
| WandbCallback |
python | Textualize__textual | docs/examples/how-to/layout01.py | {
"start": 211,
"end": 364
} | class ____(Screen):
def compose(self) -> ComposeResult:
yield Header(id="Header") # (3)!
yield Footer(id="Footer") # (4)!
| TweetScreen |
python | pytorch__pytorch | benchmarks/tensorexpr/pooling.py | {
"start": 26,
"end": 1306
} | class ____(benchmark.Benchmark):
def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
super().__init__(mode, device)
self.case = case
self.kernel_size = kernel_size
self.N = N
self.C = C
self.H = H
self.W = W
self.data = self.rand(
[N, C, H, W], device=device, dtype=dtype, requires_grad=self.requires_grad
)
def forward(self):
if self.case == "maxpool":
y = self.max_pool2d(self.data, self.kernel_size, stride=1)
elif self.case == "avgpool":
y = self.avg_pool2d(self.data, self.kernel_size, stride=1)
return y
def config(self):
return [self.kernel_size, self.N, self.C, self.H, self.W]
def memory_workload(self):
if self.mode == "fwd":
sol_count = 1 + 1
algorithmic_count = 1 + 1
else:
sol_count = (1 + 1) + (1 + 1)
algorithmic_count = (1 + 1) + (2 + 1)
buffer_size = self.N * self.C * self.H * self.W
return {
"sol": buffer_size * sol_count,
"algorithmic": buffer_size * algorithmic_count,
}
@staticmethod
def default_configs():
return [[3, 16, 32, 256, 256]]
| PoolingBench |
python | getsentry__sentry | src/sentry/metrics/middleware.py | {
"start": 3529,
"end": 6650
} | class ____(MetricsBackend):
"""
A wrapper around any metrics backend implementing tags denylisting and global tag context.
"""
def __init__(self, inner: MetricsBackend) -> None:
self.inner = inner
def incr(
self,
key: str,
instance: str | None = None,
tags: Tags | None = None,
amount: float | int = 1,
sample_rate: float = 1,
unit: str | None = None,
stacklevel: int = 0,
) -> None:
current_tags = get_current_global_tags()
if tags is not None:
current_tags.update(tags)
current_tags = _filter_tags(key, current_tags)
return self.inner.incr(
key, instance, current_tags, amount, sample_rate, unit, stacklevel + 1
)
def timing(
self,
key: str,
value: float,
instance: str | None = None,
tags: Tags | None = None,
sample_rate: float = 1,
stacklevel: int = 0,
) -> None:
current_tags = get_current_global_tags()
if tags is not None:
current_tags.update(tags)
current_tags = _filter_tags(key, current_tags)
return self.inner.timing(key, value, instance, current_tags, sample_rate, stacklevel + 1)
def gauge(
self,
key: str,
value: float,
instance: str | None = None,
tags: Tags | None = None,
sample_rate: float = 1,
unit: str | None = None,
stacklevel: int = 0,
) -> None:
current_tags = get_current_global_tags()
if tags is not None:
current_tags.update(tags)
current_tags = _filter_tags(key, current_tags)
return self.inner.gauge(
key, value, instance, current_tags, sample_rate, unit, stacklevel + 1
)
def distribution(
self,
key: str,
value: float,
instance: str | None = None,
tags: Tags | None = None,
sample_rate: float = 1,
unit: str | None = None,
stacklevel: int = 0,
) -> None:
current_tags = get_current_global_tags()
if tags is not None:
current_tags.update(tags)
current_tags = _filter_tags(key, current_tags)
return self.inner.distribution(
key, value, instance, current_tags, sample_rate, unit, stacklevel + 1
)
def event(
self,
title: str,
message: str,
alert_type: str | None = None,
aggregation_key: str | None = None,
source_type_name: str | None = None,
priority: str | None = None,
instance: str | None = None,
tags: Tags | None = None,
stacklevel: int = 0,
) -> None:
current_tags = get_current_global_tags()
if tags is not None:
current_tags.update(tags)
return self.inner.event(
title,
message,
alert_type,
aggregation_key,
source_type_name,
priority,
instance,
current_tags,
stacklevel + 1,
)
| MiddlewareWrapper |
python | python__mypy | mypy/stubgen.py | {
"start": 6273,
"end": 7452
} | class ____:
"""A single source for stub: can be a Python or C module.
A simple extension of BuildSource that also carries the AST and
the value of __all__ detected at runtime.
"""
def __init__(
self, module: str, path: str | None = None, runtime_all: list[str] | None = None
) -> None:
self.source = BuildSource(path, module, None)
self.runtime_all = runtime_all
self.ast: MypyFile | None = None
def __repr__(self) -> str:
return f"StubSource({self.source})"
@property
def module(self) -> str:
return self.source.module
@property
def path(self) -> str | None:
return self.source.path
# What was generated previously in the stub file. We keep track of these to generate
# nicely formatted output (add empty line between non-empty classes, for example).
EMPTY: Final = "EMPTY"
FUNC: Final = "FUNC"
CLASS: Final = "CLASS"
EMPTY_CLASS: Final = "EMPTY_CLASS"
VAR: Final = "VAR"
NOT_IN_ALL: Final = "NOT_IN_ALL"
# Indicates that we failed to generate a reasonable output
# for a given node. These should be manually replaced by a user.
ERROR_MARKER: Final = "<ERROR>"
| StubSource |
python | kamyu104__LeetCode-Solutions | Python/pass-the-pillow.py | {
"start": 36,
"end": 232
} | class ____(object):
def passThePillow(self, n, time):
"""
:type n: int
:type time: int
:rtype: int
"""
return n-abs((n-1)-(time%(2*(n-1))))
| Solution |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/qbatchnorm_test.py | {
"start": 353,
"end": 1039
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device, dtype):
self._init(M, N, K, device)
x_scale = 0.1
x_zero_point = 0
self.inputs = {
"q_input_one": torch.quantize_per_tensor(
self.input_one, scale=x_scale, zero_point=x_zero_point, dtype=dtype
),
"mean": torch.rand(N),
"var": torch.rand(N),
"weight": torch.rand(N),
"bias": torch.rand(N),
"eps": 1e-5,
"Y_scale": 0.1,
"Y_zero_point": 0,
}
def _init(self, M, N, K, device):
pass
def forward(self):
pass
| QBatchNormBenchmark |
python | pytorch__pytorch | test/test_opaque_obj_v2.py | {
"start": 1520,
"end": 1637
} | class ____:
def __init__(self, seed):
self.seed = seed
self.rng = random.Random(self.seed)
| RNGState |
python | eventlet__eventlet | tests/hub_test.py | {
"start": 3262,
"end": 4502
} | class ____(tests.LimitedTestCase):
def setUp(self):
super().setUp()
debug.hub_prevent_multiple_readers(False)
debug.hub_exceptions(False)
def tearDown(self):
super().tearDown()
debug.hub_prevent_multiple_readers(True)
debug.hub_exceptions(True)
def test_cleanup(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
fcntl.fcntl(r, fcntl.F_SETFL,
fcntl.fcntl(r, fcntl.F_GETFL) | os.O_NONBLOCK)
def readfd(fd):
while True:
try:
return os.read(fd, 1)
except OSError as e:
if e.errno != errno.EAGAIN:
raise
hubs.trampoline(fd, read=True)
first_listener = eventlet.spawn(readfd, r)
eventlet.sleep()
second_listener = eventlet.spawn(readfd, r)
eventlet.sleep()
hubs.get_hub().schedule_call_global(0, second_listener.throw,
eventlet.Timeout(None))
eventlet.sleep()
os.write(w, b'.')
self.assertEqual(first_listener.wait(), b'.')
| TestMultipleListenersCleanup |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/ci/state.py | {
"start": 886,
"end": 986
} | class ____(Enum):
success = "success"
pending = "pending"
failed = "failed"
| LocationStatus |
python | realpython__materials | build-a-rest-api-frontend/source_code_start/models.py | {
"start": 593,
"end": 1079
} | class ____(db.Model):
__tablename__ = "person"
id = db.Column(db.Integer, primary_key=True)
lname = db.Column(db.String(32), unique=True)
fname = db.Column(db.String(32))
timestamp = db.Column(
db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
)
notes = db.relationship(
Note,
backref="person",
cascade="all, delete, delete-orphan",
single_parent=True,
order_by="desc(Note.timestamp)",
)
| Person |
python | pytorch__pytorch | test/inductor/test_caching.py | {
"start": 8166,
"end": 15261
} | class ____(TestCase):
def isolation_schema_from_forms_of_context_selected(
self,
runtime_forms_of_context_selected: Sequence[str],
compile_forms_of_context_selected: Sequence[str],
) -> context.IsolationSchema:
return context.IsolationSchema(
runtime_context={
form_of_context: form_of_context
in set(runtime_forms_of_context_selected)
for form_of_context in context._RuntimeContext.forms_of_context()
},
compile_context={
form_of_context: form_of_context
in set(compile_forms_of_context_selected)
for form_of_context in context._CompileContext.forms_of_context()
},
)
@parametrize(
"runtime_forms_of_context_selected",
[(), *list(combinations(context._RuntimeContext.forms_of_context(), 2))],
)
@parametrize(
"compile_forms_of_context_selected",
[(), *list(combinations(context._CompileContext.forms_of_context(), 2))],
)
def test_selected_isolation_context(
self,
runtime_forms_of_context_selected: Sequence[str],
compile_forms_of_context_selected: Sequence[str],
) -> None:
"""
Tests that isolation context generation works correctly for specific combinations
of runtime and compile context forms.
Verifies that the _isolation_context function properly creates isolation contexts
based on the selected forms of runtime and compile context, ensuring that only
the specified context forms are included in the resulting isolation context.
"""
ischema: context.IsolationSchema = (
self.isolation_schema_from_forms_of_context_selected(
runtime_forms_of_context_selected, compile_forms_of_context_selected
)
)
self.assertEqual(
context._isolation_context(ischema),
{
"runtime_context": {
form_of_context: getattr(context._RuntimeContext, form_of_context)()
for form_of_context in runtime_forms_of_context_selected
}
or None,
"compile_context": {
form_of_context: getattr(context._CompileContext, form_of_context)()
for form_of_context in compile_forms_of_context_selected
}
or None,
},
)
@parametrize("all_runtime_context", [True, False])
@parametrize("all_compile_context", [True, False])
def test_all_or_none_isolation_context(
self, all_runtime_context: bool, all_compile_context: bool
) -> None:
"""
Tests isolation context generation when using all or no context forms.
Verifies that the isolation context correctly includes all forms of context
when set to True, or excludes all forms when set to False, for both
runtime and compile contexts.
"""
ischema: context.IsolationSchema = context.IsolationSchema(
runtime_context=all_runtime_context, compile_context=all_compile_context
)
self.assertEqual(
context._isolation_context(ischema),
{
"runtime_context": {
form_of_context: getattr(context._RuntimeContext, form_of_context)()
for form_of_context in context._RuntimeContext.forms_of_context()
}
if all_runtime_context
else None,
"compile_context": {
form_of_context: getattr(context._CompileContext, form_of_context)()
for form_of_context in context._CompileContext.forms_of_context()
}
if all_compile_context
else None,
},
)
def test_isolation_key_is_distinct(self) -> None:
"""
Tests that different combinations of runtime and compile context forms
generate unique isolation keys.
Verifies that each possible combination of context forms produces a distinct
isolation key, ensuring no collisions occur between different contexts.
"""
ikeys: set[str] = set()
for num_runtime_forms_of_context_selected in range(
len(context._RuntimeContext.forms_of_context())
):
for num_compile_forms_of_context_selected in range(
len(context._CompileContext.forms_of_context())
):
for runtime_forms_of_context_selected in combinations(
context._RuntimeContext.forms_of_context(),
num_runtime_forms_of_context_selected,
):
for compile_forms_of_context_selected in combinations(
context._CompileContext.forms_of_context(),
num_compile_forms_of_context_selected,
):
ischema: context.IsolationSchema = (
self.isolation_schema_from_forms_of_context_selected(
runtime_forms_of_context_selected,
compile_forms_of_context_selected,
)
)
ikey: str = context._isolation_key(ischema)
self.assertFalse(ikey in ikeys)
ikeys.add(ikey)
def test_isolation_key_is_repeatable(self) -> None:
"""
Tests that calling the isolation key function multiple times with the same
parameters produces the same result.
Verifies that the isolation key generation is deterministic and consistent
across multiple invocations with identical inputs.
"""
self.assertEqual(context._isolation_key(), context._isolation_key())
def test_select_runtime_context_matches_forms_of_context(self) -> None:
"""
Tests that the selected runtime context matches the forms of context.
Verifies that the selected runtime context includes only the forms of context
specified in the isolation schema, ensuring that the isolation context is
properly selected and configured.
"""
self.assertEqual(
set(context.SelectedRuntimeContext.__required_keys__),
set(context._RuntimeContext.forms_of_context()),
)
def test_select_compile_context_matches_forms_of_context(self) -> None:
"""
Tests that the selected compile context matches the forms of context.
Verifies that the selected compile context includes only the forms of context
specified in the isolation schema, ensuring that the isolation context is
properly selected and configured.
"""
self.assertEqual(
set(context.SelectedCompileContext.__required_keys__),
set(context._CompileContext.forms_of_context()),
)
@instantiate_parametrized_tests
| ContextTest |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/agents/test_structured_chat.py | {
"start": 3086,
"end": 7471
} | class ____:
# Test: Output should be a ChatPromptTemplate with sys and human messages.
def test_create_prompt_output(self) -> None:
prompt = StructuredChatAgent.create_prompt(
[Tool(name="foo", description="Test tool FOO", func=lambda x: x)],
)
assert isinstance(prompt, ChatPromptTemplate)
assert len(prompt.messages) == 2
assert isinstance(prompt.messages[0], SystemMessagePromptTemplate)
assert isinstance(prompt.messages[1], HumanMessagePromptTemplate)
# Test: Format with a single tool.
def test_system_message_single_tool(self) -> None:
prompt: Any = StructuredChatAgent.create_prompt(
[Tool(name="foo", description="Test tool FOO", func=lambda x: x)],
)
actual = prompt.messages[0].prompt.format()
expected = dedent(
"""
Respond to the human as helpfully and accurately as possible. You have access to the following tools:
foo: Test tool FOO, args: {'tool_input': {'type': 'string'}}
Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
Valid "action" values: "Final Answer" or foo
Provide only ONE action per $JSON_BLOB, as shown:
```
{
"action": $TOOL_NAME,
"action_input": $INPUT
}
```
Follow this format:
Question: input question to answer
Thought: consider previous and subsequent steps
Action:
```
$JSON_BLOB
```
Observation: action result
... (repeat Thought/Action/Observation N times)
Thought: I know what to respond
Action:
```
{
"action": "Final Answer",
"action_input": "Final response to human"
}
```
Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation:.
Thought:
""", # noqa: E501
).strip()
assert actual == expected
# Test: Format with multiple tools.
#
# Check:
#
# You have access to the following tools:
# ...
#
# and
#
# Valid "action" values: "Final Answer" or ...
#
def test_system_message_multiple_tools(self) -> None:
prompt: Any = StructuredChatAgent.create_prompt(
[
Tool(name="foo", description="Test tool FOO", func=lambda x: x),
Tool(name="bar", description="Test tool BAR", func=lambda x: x),
],
)
actual = prompt.messages[0].prompt.format()
expected = dedent(
"""
Respond to the human as helpfully and accurately as possible. You have access to the following tools:
foo: Test tool FOO, args: {'tool_input': {'type': 'string'}}
bar: Test tool BAR, args: {'tool_input': {'type': 'string'}}
Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
Valid "action" values: "Final Answer" or foo, bar
Provide only ONE action per $JSON_BLOB, as shown:
```
{
"action": $TOOL_NAME,
"action_input": $INPUT
}
```
Follow this format:
Question: input question to answer
Thought: consider previous and subsequent steps
Action:
```
$JSON_BLOB
```
Observation: action result
... (repeat Thought/Action/Observation N times)
Thought: I know what to respond
Action:
```
{
"action": "Final Answer",
"action_input": "Final response to human"
}
```
Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation:.
Thought:
""", # noqa: E501
).strip()
assert actual == expected
| TestCreatePrompt |
python | tensorflow__tensorflow | tensorflow/python/ops/math_grad_test.py | {
"start": 15868,
"end": 17385
} | class ____(test.TestCase):
def _run_gradient_check(self, data, segment_ids):
def _segment_prod(x):
return math_ops.segment_prod(x, segment_ids)
err = gradient_checker_v2.max_error(
*gradient_checker_v2.compute_gradient(_segment_prod, [data]))
self.assertLess(err, 2e-4)
def testSegmentProdGradientWithoutOverlap(self):
data = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1], [5, 6, 7, 8]],
dtype=dtypes.float32)
segment_ids = constant_op.constant([0, 1, 2], dtype=dtypes.int64)
self._run_gradient_check(data, segment_ids)
def testSegmentProdGradientWithoutZeros(self):
data = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1], [5, 6, 7, 8]],
dtype=dtypes.float32)
segment_ids = constant_op.constant([0, 0, 1], dtype=dtypes.int64)
self._run_gradient_check(data, segment_ids)
def testSegmentProdGradientWithZeros(self):
data = constant_op.constant([[0, 2, 3, 4], [0, 0, 2, 0], [5, 0, 7, 0]],
dtype=dtypes.float32)
segment_ids = constant_op.constant([0, 0, 1], dtype=dtypes.int64)
self._run_gradient_check(data, segment_ids)
def testSegmentProdGradientWithEmptySegment(self):
data = constant_op.constant([[1, 2, 3, 4], [4, 3, 2, 1], [5, 6, 7, 8]],
dtype=dtypes.float32)
segment_ids = constant_op.constant([0, 0, 2], dtype=dtypes.int64)
self._run_gradient_check(data, segment_ids)
| SegmentProdGradientTest |
python | django__django | tests/timezones/tests.py | {
"start": 28600,
"end": 30239
} | class ____(TransactionTestCase):
"""
Test the TIME_ZONE database configuration parameter.
Since this involves reading and writing to the same database through two
connections, this is a TransactionTestCase.
"""
available_apps = ["timezones"]
@classmethod
def setUpClass(cls):
# @skipIfDBFeature and @skipUnlessDBFeature cannot be chained. The
# outermost takes precedence. Handle skipping manually instead.
if connection.features.supports_timezones:
raise SkipTest("Database has feature(s) supports_timezones")
if not connection.features.test_db_allows_multiple_connections:
raise SkipTest(
"Database doesn't support feature(s): "
"test_db_allows_multiple_connections"
)
super().setUpClass()
def test_read_datetime(self):
fake_dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=UTC)
Event.objects.create(dt=fake_dt)
with override_database_connection_timezone("Asia/Bangkok"):
event = Event.objects.get()
dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
self.assertEqual(event.dt, dt)
def test_write_datetime(self):
dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
with override_database_connection_timezone("Asia/Bangkok"):
Event.objects.create(dt=dt)
event = Event.objects.get()
fake_dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=UTC)
self.assertEqual(event.dt, fake_dt)
@override_settings(TIME_ZONE="Africa/Nairobi")
| ForcedTimeZoneDatabaseTests |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/test_rest_compliance.py | {
"start": 424,
"end": 6855
} | class ____:
"""Test REST compliance for API interfaces."""
def test_method_naming_conventions(self):
"""Test that all public methods follow REST naming conventions."""
for api_class in get_all_api_classes():
public_methods = [
method
for method in dir(api_class)
if not method.startswith("_") and callable(getattr(api_class, method))
]
# Remove __init__ and other special methods
public_methods = [m for m in public_methods if not m.startswith("__")]
for method_name in public_methods:
valid_prefix = any(
method_name.startswith(prefix) for prefix in REST_PREFIXES.keys()
)
assert valid_prefix, (
f"{api_class.__name__}.{method_name} doesn't follow REST naming conventions. "
f"Should start with one of: {', '.join(REST_PREFIXES.keys())}"
)
def test_type_signatures(self):
"""Test that methods only use primitives and Pydantic models."""
for api_class in get_all_api_classes():
public_methods = [
method
for method in dir(api_class)
if not method.startswith("_") and callable(getattr(api_class, method))
]
# Remove __init__ and other special methods
public_methods = [m for m in public_methods if not m.startswith("__")]
for method_name in public_methods:
method = getattr(api_class, method_name)
if not callable(method):
continue
sig = inspect.signature(method)
# Check parameters (skip 'self')
for param_name, param in sig.parameters.items():
if param_name == "self":
continue
if param.annotation != inspect.Parameter.empty:
assert is_allowed_type(param.annotation), (
f"{api_class.__name__}.{method_name} parameter '{param_name}' "
f"has invalid type {param.annotation}. "
f"Only primitives and Pydantic models are allowed."
)
# Check return type
if sig.return_annotation != inspect.Signature.empty:
# Return types must be Pydantic models (not primitives)
assert is_pydantic_model(sig.return_annotation), (
f"{api_class.__name__}.{method_name} return type {sig.return_annotation} "
f"must be a Pydantic model."
)
def test_response_consistency(self):
"""Test that list methods return consistent response structures."""
for api_class in get_all_api_classes():
public_methods = [
method
for method in dir(api_class)
if not method.startswith("_") and callable(getattr(api_class, method))
]
for method_name in public_methods:
if not method_name.startswith("list_"):
continue
method = getattr(api_class, method_name)
sig = inspect.signature(method)
if sig.return_annotation != inspect.Signature.empty:
return_type = sig.return_annotation
# Get the actual class if it's Optional
if get_origin(return_type) in (Union, type(Union)):
args = get_args(return_type)
non_none_args = [arg for arg in args if arg is not type(None)]
if non_none_args:
return_type = non_none_args[0]
# Check that it's a Pydantic model with an 'items' field
if inspect.isclass(return_type) and issubclass(return_type, BaseModel):
fields = return_type.model_fields
assert "items" in fields, (
f"{api_class.__name__}.{method_name} return type {return_type.__name__} "
f"should have an 'items' field for list responses."
)
def test_parameter_patterns(self):
"""Test that parameters follow consistent patterns."""
for api_class in get_all_api_classes():
public_methods = [
method
for method in dir(api_class)
if not method.startswith("_") and callable(getattr(api_class, method))
]
for method_name in public_methods:
method = getattr(api_class, method_name)
if not callable(method):
continue
sig = inspect.signature(method)
for param_name, param in sig.parameters.items():
if param_name == "self":
continue
# Check ID parameters use consistent naming
if "id" in param_name.lower():
# IDs should be in format resource_id (e.g., deployment_id)
assert param_name.endswith("_id") or param_name == "id", (
f"{api_class.__name__}.{method_name} parameter '{param_name}' "
f"should follow pattern 'resource_id' (e.g., deployment_id)"
)
# Check Optional parameters have proper typing
if param.default != inspect.Parameter.empty:
# Parameters with defaults should be Optional
if param.annotation != inspect.Parameter.empty:
origin = get_origin(param.annotation)
is_optional = origin in (Union, type(Union)) and type(None) in get_args(
param.annotation
)
assert is_optional or param.default is None, (
f"{api_class.__name__}.{method_name} parameter '{param_name}' "
f"has a default value but is not typed as Optional"
)
if __name__ == "__main__":
pytest.main([__file__, "-v"])
| TestRestCompliance |
python | giampaolo__psutil | tests/test_linux.py | {
"start": 23375,
"end": 26418
} | class ____(PsutilTestCase):
@pytest.mark.skipif(
not os.path.exists("/sys/devices/system/cpu/online"),
reason="/sys/devices/system/cpu/online does not exist",
)
def test_against_sysdev_cpu_online(self):
with open("/sys/devices/system/cpu/online") as f:
value = f.read().strip()
if "-" in str(value):
value = int(value.split('-')[1]) + 1
assert psutil.cpu_count() == value
@pytest.mark.skipif(
not os.path.exists("/sys/devices/system/cpu"),
reason="/sys/devices/system/cpu does not exist",
)
def test_against_sysdev_cpu_num(self):
ls = os.listdir("/sys/devices/system/cpu")
count = len([x for x in ls if re.search(r"cpu\d+$", x) is not None])
assert psutil.cpu_count() == count
@pytest.mark.skipif(
not shutil.which("nproc"), reason="nproc utility not available"
)
def test_against_nproc(self):
num = int(sh("nproc --all"))
assert psutil.cpu_count(logical=True) == num
@pytest.mark.skipif(
not shutil.which("lscpu"), reason="lscpu utility not available"
)
def test_against_lscpu(self):
out = sh("lscpu -p")
num = len([x for x in out.split('\n') if not x.startswith('#')])
assert psutil.cpu_count(logical=True) == num
def test_emulate_fallbacks(self):
import psutil._pslinux
original = psutil._pslinux.cpu_count_logical()
# Here we want to mock os.sysconf("SC_NPROCESSORS_ONLN") in
# order to cause the parsing of /proc/cpuinfo and /proc/stat.
with mock.patch(
'psutil._pslinux.os.sysconf', side_effect=ValueError
) as m:
assert psutil._pslinux.cpu_count_logical() == original
assert m.called
# Let's have open() return empty data and make sure None is
# returned ('cause we mimic os.cpu_count()).
with mock.patch('psutil._common.open', create=True) as m:
assert psutil._pslinux.cpu_count_logical() is None
assert m.call_count == 2
# /proc/stat should be the last one
assert m.call_args[0][0] == '/proc/stat'
# Let's push this a bit further and make sure /proc/cpuinfo
# parsing works as expected.
with open('/proc/cpuinfo', 'rb') as f:
cpuinfo_data = f.read()
fake_file = io.BytesIO(cpuinfo_data)
with mock.patch(
'psutil._common.open', return_value=fake_file, create=True
) as m:
assert psutil._pslinux.cpu_count_logical() == original
# Finally, let's make /proc/cpuinfo return meaningless data;
# this way we'll fall back on relying on /proc/stat
with mock_open_content({"/proc/cpuinfo": b""}) as m:
assert psutil._pslinux.cpu_count_logical() == original
assert m.called
@pytest.mark.skipif(not LINUX, reason="LINUX only")
| TestSystemCPUCountLogical |
python | prabhupant__python-ds | data_structures/binary_trees/largest_subtree_sum.py | {
"start": 76,
"end": 500
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def sum_util(root, ans):
if root is None:
return 0
s = root.val + sum_util(root.left, ans) + sum_util(root.right, ans)
ans[0] = max(ans[0], s)
return s
def find_sum(root):
if root is None:
return 0
ans = [-99999999]
sum_util(root, ans)
return ans[0]
| Node |
python | PyCQA__pylint | tests/functional/r/regression/regression_4680.py | {
"start": 95,
"end": 149
} | class ____(metaclass=foo.sub.Metaclass):
pass
| Failed |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datastore.py | {
"start": 21520,
"end": 23413
} | class ____(GoogleCloudBaseOperator):
"""
Gets the latest state of a long-running operation.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDatastoreGetOperationOperator`
.. seealso::
https://cloud.google.com/datastore/docs/reference/data/rest/v1/projects.operations/get
:param name: the name of the operation resource.
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"name",
"impersonation_chain",
)
def __init__(
self,
*,
name: str,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.name = name
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook = DatastoreHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
op = hook.get_operation(name=self.name)
return op
| CloudDatastoreGetOperationOperator |
python | joblib__joblib | joblib/externals/loky/process_executor.py | {
"start": 19599,
"end": 39519
} | class ____(threading.Thread):
"""Manages the communication between this process and the worker processes.
The manager is run in a local thread.
Args:
executor: A reference to the ProcessPoolExecutor that owns
this thread. A weakref will be own by the manager as well as
references to internal objects used to introspect the state of
the executor.
"""
def __init__(self, executor):
# Store references to necessary internals of the executor.
# A _ThreadWakeup to allow waking up the executor_manager_thread from
# the main Thread and avoid deadlocks caused by permanently
# locked queues.
self.thread_wakeup = executor._executor_manager_thread_wakeup
self.shutdown_lock = executor._shutdown_lock
# A weakref.ref to the ProcessPoolExecutor that owns this thread. Used
# to determine if the ProcessPoolExecutor has been garbage collected
# and that the manager can exit.
# When the executor gets garbage collected, the weakref callback
# will wake up the queue management thread so that it can terminate
# if there is no pending work item.
def weakref_cb(
_,
thread_wakeup=self.thread_wakeup,
shutdown_lock=self.shutdown_lock,
):
if mp is not None:
# At this point, the multiprocessing module can already be
# garbage collected. We only log debug info when still
# possible.
mp.util.debug(
"Executor collected: triggering callback for"
" QueueManager wakeup"
)
with shutdown_lock:
thread_wakeup.wakeup()
self.executor_reference = weakref.ref(executor, weakref_cb)
# The flags of the executor
self.executor_flags = executor._flags
# A list of the ctx.Process instances used as workers.
self.processes = executor._processes
# A ctx.Queue that will be filled with _CallItems derived from
# _WorkItems for processing by the process workers.
self.call_queue = executor._call_queue
# A ctx.SimpleQueue of _ResultItems generated by the process workers.
self.result_queue = executor._result_queue
# A queue.Queue of work ids e.g. Queue([5, 6, ...]).
self.work_ids_queue = executor._work_ids
# A dict mapping work ids to _WorkItems e.g.
# {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
self.pending_work_items = executor._pending_work_items
# A list of the work_ids that are currently running
self.running_work_items = executor._running_work_items
# A lock to avoid concurrent shutdown of workers on timeout and spawn
# of new processes or shut down
self.processes_management_lock = executor._processes_management_lock
super().__init__(name="ExecutorManagerThread")
if sys.version_info < (3, 9):
self.daemon = True
def run(self):
# Main loop for the executor manager thread.
while True:
self.add_call_item_to_queue()
result_item, is_broken, bpe = self.wait_result_broken_or_wakeup()
if is_broken:
self.terminate_broken(bpe)
return
if result_item is not None:
self.process_result_item(result_item)
# Delete reference to result_item to avoid keeping references
# while waiting on new results.
del result_item
if self.is_shutting_down():
self.flag_executor_shutting_down()
# Since no new work items can be added, it is safe to shutdown
# this thread if there are no pending work items.
if not self.pending_work_items:
self.join_executor_internals()
return
def add_call_item_to_queue(self):
# Fills call_queue with _WorkItems from pending_work_items.
# This function never blocks.
while True:
if self.call_queue.full():
return
try:
work_id = self.work_ids_queue.get(block=False)
except queue.Empty:
return
else:
work_item = self.pending_work_items[work_id]
if work_item.future.set_running_or_notify_cancel():
self.running_work_items += [work_id]
self.call_queue.put(
_CallItem(
work_id,
work_item.fn,
work_item.args,
work_item.kwargs,
),
block=True,
)
else:
del self.pending_work_items[work_id]
continue
def wait_result_broken_or_wakeup(self):
# Wait for a result to be ready in the result_queue while checking
# that all worker processes are still running, or for a wake up
# signal send. The wake up signals come either from new tasks being
# submitted, from the executor being shutdown/gc-ed, or from the
# shutdown of the python interpreter.
result_reader = self.result_queue._reader
wakeup_reader = self.thread_wakeup._reader
readers = [result_reader, wakeup_reader]
worker_sentinels = [p.sentinel for p in list(self.processes.values())]
ready = wait(readers + worker_sentinels)
bpe = None
is_broken = True
result_item = None
if result_reader in ready:
try:
result_item = result_reader.recv()
if isinstance(result_item, _RemoteTraceback):
bpe = BrokenProcessPool(
"A task has failed to un-serialize. Please ensure that"
" the arguments of the function are all picklable."
)
bpe.__cause__ = result_item
else:
is_broken = False
except BaseException as e:
bpe = BrokenProcessPool(
"A result has failed to un-serialize. Please ensure that "
"the objects returned by the function are always "
"picklable."
)
tb = traceback.format_exception(
type(e), e, getattr(e, "__traceback__", None)
)
bpe.__cause__ = _RemoteTraceback("".join(tb))
elif wakeup_reader in ready:
# This is simply a wake-up event that might either trigger putting
# more tasks in the queue or trigger the clean up of resources.
is_broken = False
else:
# A worker has terminated and we don't know why, set the state of
# the executor as broken
exit_codes = ""
if sys.platform != "win32":
# In Windows, introspecting terminated workers exitcodes seems
# unstable, therefore they are not appended in the exception
# message.
exit_codes = (
"\nThe exit codes of the workers are "
f"{get_exitcodes_terminated_worker(self.processes)}"
)
mp.util.debug(
"A worker unexpectedly terminated. Workers that "
"might have caused the breakage: "
+ str(
{
p.name: p.exitcode
for p in list(self.processes.values())
if p is not None and p.sentinel in ready
}
)
)
bpe = TerminatedWorkerError(
"A worker process managed by the executor was unexpectedly "
"terminated. This could be caused by a segmentation fault "
"while calling the function or by an excessive memory usage "
"causing the Operating System to kill the worker.\n"
f"{exit_codes}\n"
"Detailed tracebacks of the workers should have been printed "
"to stderr in the executor process if faulthandler was not "
"disabled."
)
self.thread_wakeup.clear()
return result_item, is_broken, bpe
def process_result_item(self, result_item):
# Process the received a result_item. This can be either the PID of a
# worker that exited gracefully or a _ResultItem
if isinstance(result_item, int):
# Clean shutdown of a worker using its PID, either on request
# by the executor.shutdown method or by the timeout of the worker
# itself: we should not mark the executor as broken.
with self.processes_management_lock:
p = self.processes.pop(result_item, None)
# p can be None if the executor is concurrently shutting down.
if p is not None:
p._worker_exit_lock.release()
mp.util.debug(
f"joining {p.name} when processing {p.pid} as result_item"
)
p.join()
del p
# Make sure the executor have the right number of worker, even if a
# worker timeout while some jobs were submitted. If some work is
# pending or there is less processes than running items, we need to
# start a new Process and raise a warning.
n_pending = len(self.pending_work_items)
n_running = len(self.running_work_items)
if n_pending - n_running > 0 or n_running > len(self.processes):
executor = self.executor_reference()
if (
executor is not None
and len(self.processes) < executor._max_workers
):
warnings.warn(
"A worker stopped while some jobs were given to the "
"executor. This can be caused by a too short worker "
"timeout or by a memory leak.",
UserWarning,
)
with executor._processes_management_lock:
executor._adjust_process_count()
executor = None
else:
# Received a _ResultItem so mark the future as completed.
work_item = self.pending_work_items.pop(result_item.work_id, None)
# work_item can be None if another process terminated (see above)
if work_item is not None:
if result_item.exception:
work_item.future.set_exception(result_item.exception)
else:
work_item.future.set_result(result_item.result)
self.running_work_items.remove(result_item.work_id)
def is_shutting_down(self):
# Check whether we should start shutting down the executor.
executor = self.executor_reference()
# No more work items can be added if:
# - The interpreter is shutting down OR
# - The executor that owns this thread is not broken AND
# * The executor that owns this worker has been collected OR
# * The executor that owns this worker has been shutdown.
# If the executor is broken, it should be detected in the next loop.
return _global_shutdown or (
(executor is None or self.executor_flags.shutdown)
and not self.executor_flags.broken
)
def terminate_broken(self, bpe):
# Terminate the executor because it is in a broken state. The bpe
# argument can be used to display more information on the error that
# lead the executor into becoming broken.
# Mark the process pool broken so that submits fail right now.
self.executor_flags.flag_as_broken(bpe)
# Mark pending tasks as failed.
for work_item in self.pending_work_items.values():
work_item.future.set_exception(bpe)
# Delete references to object. See issue16284
del work_item
self.pending_work_items.clear()
# Terminate remaining workers forcibly: the queues or their
# locks may be in a dirty state and block forever.
self.kill_workers(reason="broken executor")
# clean up resources
self.join_executor_internals()
def flag_executor_shutting_down(self):
# Flag the executor as shutting down and cancel remaining tasks if
# requested as early as possible if it is not gc-ed yet.
self.executor_flags.flag_as_shutting_down()
# Cancel pending work items if requested.
if self.executor_flags.kill_workers:
while self.pending_work_items:
_, work_item = self.pending_work_items.popitem()
work_item.future.set_exception(
ShutdownExecutorError(
"The Executor was shutdown with `kill_workers=True` "
"before this job could complete."
)
)
del work_item
# Kill the remaining worker forcibly to no waste time joining them
self.kill_workers(reason="executor shutting down")
def kill_workers(self, reason=""):
# Terminate the remaining workers using SIGKILL. This function also
# terminates descendant workers of the children in case there is some
# nested parallelism.
while self.processes:
_, p = self.processes.popitem()
mp.util.debug(f"terminate process {p.name}, reason: {reason}")
try:
kill_process_tree(p)
except ProcessLookupError: # pragma: no cover
pass
def shutdown_workers(self):
# shutdown all workers in self.processes
# Create a list to avoid RuntimeError due to concurrent modification of
# processes. nb_children_alive is thus an upper bound. Also release the
# processes' _worker_exit_lock to accelerate the shutdown procedure, as
# there is no need for hand-shake here.
with self.processes_management_lock:
n_children_to_stop = 0
for p in list(self.processes.values()):
mp.util.debug(f"releasing worker exit lock on {p.name}")
p._worker_exit_lock.release()
n_children_to_stop += 1
mp.util.debug(f"found {n_children_to_stop} processes to stop")
# Send the right number of sentinels, to make sure all children are
# properly terminated. Do it with a mechanism that avoid hanging on
# Full queue when all workers have already been shutdown.
n_sentinels_sent = 0
cooldown_time = 0.001
while (
n_sentinels_sent < n_children_to_stop
and self.get_n_children_alive() > 0
):
for _ in range(n_children_to_stop - n_sentinels_sent):
try:
self.call_queue.put_nowait(None)
n_sentinels_sent += 1
except queue.Full as e:
if cooldown_time > 5.0:
mp.util.info(
"failed to send all sentinels and exit with error."
f"\ncall_queue size={self.call_queue._maxsize}; "
f" full is {self.call_queue.full()}; "
)
raise e
mp.util.info(
"full call_queue prevented to send all sentinels at "
"once, waiting..."
)
sleep(cooldown_time)
cooldown_time *= 1.2
break
mp.util.debug(f"sent {n_sentinels_sent} sentinels to the call queue")
def join_executor_internals(self):
self.shutdown_workers()
# Release the queue's resources as soon as possible. Flag the feeder
# thread for clean exit to avoid having the crash detection thread flag
# the Executor as broken during the shutdown. This is safe as either:
# * We don't need to communicate with the workers anymore
# * There is nothing left in the Queue buffer except None sentinels
mp.util.debug("closing call_queue")
self.call_queue.close()
self.call_queue.join_thread()
# Closing result_queue
mp.util.debug("closing result_queue")
self.result_queue.close()
mp.util.debug("closing thread_wakeup")
with self.shutdown_lock:
self.thread_wakeup.close()
# If .join() is not called on the created processes then
# some ctx.Queue methods may deadlock on macOS.
with self.processes_management_lock:
mp.util.debug(f"joining {len(self.processes)} processes")
n_joined_processes = 0
while True:
try:
pid, p = self.processes.popitem()
mp.util.debug(f"joining process {p.name} with pid {pid}")
p.join()
n_joined_processes += 1
except KeyError:
break
mp.util.debug(
"executor management thread clean shutdown of "
f"{n_joined_processes} workers"
)
def get_n_children_alive(self):
# This is an upper bound on the number of children alive.
with self.processes_management_lock:
return sum(p.is_alive() for p in list(self.processes.values()))
_system_limits_checked = False
_system_limited = None
def _check_system_limits():
global _system_limits_checked, _system_limited
if _system_limits_checked and _system_limited:
raise NotImplementedError(_system_limited)
_system_limits_checked = True
try:
nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
except (AttributeError, ValueError):
# sysconf not available or setting not available
return
if nsems_max == -1:
# undetermined limit, assume that limit is determined
# by available memory only
return
if nsems_max >= 256:
# minimum number of semaphores available
# according to POSIX
return
_system_limited = (
f"system provides too few semaphores ({nsems_max} available, "
"256 necessary)"
)
raise NotImplementedError(_system_limited)
def _chain_from_iterable_of_lists(iterable):
"""
Specialized implementation of itertools.chain.from_iterable.
Each item in *iterable* should be a list. This function is
careful not to keep references to yielded objects.
"""
for element in iterable:
element.reverse()
while element:
yield element.pop()
def _check_max_depth(context):
# Limit the maxmal recursion level
global _CURRENT_DEPTH
if context.get_start_method() == "fork" and _CURRENT_DEPTH > 0:
raise LokyRecursionError(
"Could not spawn extra nested processes at depth superior to "
"MAX_DEPTH=1. It is not possible to increase this limit when "
"using the 'fork' start method."
)
if 0 < MAX_DEPTH and _CURRENT_DEPTH + 1 > MAX_DEPTH:
raise LokyRecursionError(
"Could not spawn extra nested processes at depth superior to "
f"MAX_DEPTH={MAX_DEPTH}. If this is intendend, you can change "
"this limit with the LOKY_MAX_DEPTH environment variable."
)
| _ExecutorManagerThread |
python | scipy__scipy | scipy/signal/tests/test_signaltools.py | {
"start": 119698,
"end": 125809
} | class ____(TestFiltFilt):
filtfilt_kind = 'sos'
@skip_xp_backends('jax.numpy', reason='sosfilt works in-place')
@skip_xp_backends('torch', reason='negative strides')
def test_equivalence(self, xp):
"""Test equivalence between sosfiltfilt and filtfilt"""
x = np.random.RandomState(0).randn(1000)
x = xp.asarray(x)
for order in range(1, 6):
zpk = signal.butter(order, 0.35, output='zpk')
b, a = zpk2tf(*zpk)
sos = zpk2sos(*zpk)
b, a, sos = map(xp.asarray, (b, a, sos))
y = filtfilt(b, a, x)
y_sos = sosfiltfilt(sos, x)
xp_assert_close(y, y_sos, atol=1e-12, err_msg=f'order={order}')
def filtfilt_gust_opt(b, a, x):
"""
An alternative implementation of filtfilt with Gustafsson edges.
This function computes the same result as
`scipy.signal._signaltools._filtfilt_gust`, but only 1-d arrays
are accepted. The problem is solved using `fmin` from `scipy.optimize`.
`_filtfilt_gust` is significantly faster than this implementation.
"""
def filtfilt_gust_opt_func(ics, b, a, x):
"""Objective function used in filtfilt_gust_opt."""
m = max(len(a), len(b)) - 1
z0f = ics[:m]
z0b = ics[m:]
y_f = lfilter(b, a, x, zi=z0f)[0]
y_fb = lfilter(b, a, y_f[::-1], zi=z0b)[0][::-1]
y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1]
y_bf = lfilter(b, a, y_b, zi=z0f)[0]
value = np.sum((y_fb - y_bf)**2)
return value
m = max(len(a), len(b)) - 1
zi = lfilter_zi(b, a)
ics = np.concatenate((x[:m].mean()*zi, x[-m:].mean()*zi))
result = fmin(filtfilt_gust_opt_func, ics, args=(b, a, x),
xtol=1e-10, ftol=1e-12,
maxfun=10000, maxiter=10000,
full_output=True, disp=False)
opt, fopt, niter, funcalls, warnflag = result
if warnflag > 0:
raise RuntimeError(
f"minimization failed in filtfilt_gust_opt: warnflag={warnflag}"
)
z0f = opt[:m]
z0b = opt[m:]
# Apply the forward-backward filter using the computed initial
# conditions.
y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1]
y = lfilter(b, a, y_b, zi=z0f)[0]
return y, z0f, z0b
def check_filtfilt_gust(b, a, shape, axis, irlen=None):
# Generate x, the data to be filtered.
rng = np.random.default_rng(123)
x = rng.standard_normal(shape)
# Apply filtfilt to x. This is the main calculation to be checked.
y = filtfilt(b, a, x, axis=axis, method="gust", irlen=irlen)
# Also call the private function so we can test the ICs.
yg, zg1, zg2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen)
# filtfilt_gust_opt is an independent implementation that gives the
# expected result, but it only handles 1-D arrays, so use some looping
# and reshaping shenanigans to create the expected output arrays.
xx = np.swapaxes(x, axis, -1)
out_shape = xx.shape[:-1]
yo = np.empty_like(xx)
m = max(len(a), len(b)) - 1
zo1 = np.empty(out_shape + (m,))
zo2 = np.empty(out_shape + (m,))
for indx in product(*[range(d) for d in out_shape]):
yo[indx], zo1[indx], zo2[indx] = filtfilt_gust_opt(b, a, xx[indx])
yo = np.swapaxes(yo, -1, axis)
zo1 = np.swapaxes(zo1, -1, axis)
zo2 = np.swapaxes(zo2, -1, axis)
xp_assert_close(y, yo, rtol=1e-8, atol=1e-9)
xp_assert_close(yg, yo, rtol=1e-8, atol=1e-9)
xp_assert_close(zg1, zo1, rtol=1e-8, atol=1e-9)
xp_assert_close(zg2, zo2, rtol=1e-8, atol=1e-9)
@make_xp_test_case(choose_conv_method)
@pytest.mark.fail_slow(10)
def test_choose_conv_method(xp):
for mode in ['valid', 'same', 'full']:
for ndim in [1, 2]:
n, k, true_method = 8, 6, 'direct'
x = np.random.randn(*((n,) * ndim))
h = np.random.randn(*((k,) * ndim))
method = choose_conv_method(x, h, mode=mode)
assert method == true_method
method_try, times = choose_conv_method(x, h, mode=mode, measure=True)
assert method_try in {'fft', 'direct'}
assert isinstance(times, dict)
assert 'fft' in times.keys() and 'direct' in times.keys()
n = 10
for not_fft_conv_supp in ["complex256", "complex192"]:
if hasattr(np, not_fft_conv_supp):
x = np.ones(n, dtype=not_fft_conv_supp)
h = x.copy()
assert choose_conv_method(x, h, mode=mode) == 'direct'
x = np.array([2**51], dtype=np.int64)
h = x.copy()
assert choose_conv_method(x, h, mode=mode) == 'direct'
@make_xp_test_case(choose_conv_method)
def test_choose_conv_method_2(xp):
for mode in ['valid', 'same', 'full']:
n = 10
for not_fft_conv_supp in ["complex256", "complex192"]:
if hasattr(np, not_fft_conv_supp):
x = np.ones(n, dtype=not_fft_conv_supp)
h = x.copy()
assert choose_conv_method(x, h, mode=mode) == 'direct'
@skip_xp_backends(np_only=True)
@pytest.mark.fail_slow(10)
def test_filtfilt_gust(xp):
# Design a filter.
z, p, k = signal.ellip(3, 0.01, 120, 0.0875, output='zpk')
# Find the approximate impulse response length of the filter.
eps = 1e-10
r = np.max(np.abs(p))
approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r)))
b, a = zpk2tf(z, p, k)
for irlen in [None, approx_impulse_len]:
signal_len = 5 * approx_impulse_len
# 1-d test case
check_filtfilt_gust(b, a, (signal_len,), 0, irlen)
# 3-d test case; test each axis.
for axis in range(3):
shape = [2, 2, 2]
shape[axis] = signal_len
check_filtfilt_gust(b, a, shape, axis, irlen)
# Test case with length less than 2*approx_impulse_len.
# In this case, `filtfilt_gust` should behave the same as if
# `irlen=None` was given.
length = 2*approx_impulse_len - 50
check_filtfilt_gust(b, a, (length,), 0, approx_impulse_len)
@make_xp_test_case(signal.decimate)
| TestSOSFiltFilt |
python | google__pytype | pytype/tests/test_collections_abc.py | {
"start": 107,
"end": 1964
} | class ____(test_base.BaseTest):
"""Tests for collections.abc."""
def test_mapping(self):
self.Check("""
import collections
class Foo(collections.abc.Mapping):
pass
""")
def test_bytestring(self):
"""Check that we handle type aliases."""
self.Check("""
import collections
x: collections.abc.ByteString
""")
def test_callable(self):
ty = self.Infer("""
from collections.abc import Callable
f: Callable[[str], str] = lambda x: x
""")
# TODO(mdemello): We should ideally not be reexporting the "Callable" type,
# and if we do it should be `Callable: type[typing.Callable]`.
self.assertTypesMatchPytd(
ty,
"""
import typing
Callable: type
f: typing.Callable[[str], str]
""",
)
def test_pyi_callable(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
from collections.abc import Callable
def f() -> Callable[[], float]: ...
""",
)
ty, _ = self.InferWithErrors(
"""
import foo
func = foo.f()
func(0.0) # wrong-arg-count
x = func()
""",
pythonpath=[d.path],
)
self.assertTypesMatchPytd(
ty,
"""
import foo
from typing import Callable
func: Callable[[], float]
x: float
""",
)
def test_generator(self):
self.Check("""
from collections.abc import Generator
def f() -> Generator[int, None, None]:
yield 0
""")
def test_set(self):
# collections.abc.Set is an alias for typing.AbstractSet.
self.Check("""
from collections.abc import Set
def f() -> Set[int]:
return frozenset([0])
""")
if __name__ == "__main__":
test_base.main()
| CollectionsABCTest |
python | ansible__ansible | lib/ansible/galaxy/collection/gpg.py | {
"start": 6812,
"end": 6939
} | class ____(GpgBaseError):
"""The used key has been revoked by its owner."""
@dataclass(frozen=True, slots=True)
| GpgKeyRevoked |
python | getsentry__sentry | tests/sentry/backup/test_models.py | {
"start": 1013,
"end": 4963
} | class ____(TransactionTestCase):
"""
For models that support different relocation scopes depending on properties of the model instance itself (ie, they have a set for their `__relocation_scope__`, rather than a single value), make sure that this dynamic deduction works correctly.
"""
def export(self) -> Any:
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir).joinpath(f"{self._testMethodName}.expect.json")
return export_to_file(tmp_path, ExportScope.Global)
@expect_models(DYNAMIC_RELOCATION_SCOPE_TESTED, ApiAuthorization, ApiToken)
def test_api_auth(self, expected_models: list[type[Model]]) -> None:
user = self.create_user()
# Bound to an app == global scope.
with assume_test_silo_mode(SiloMode.CONTROL):
app = ApiApplication.objects.create(name="test", owner=user)
auth = ApiAuthorization.objects.create(
application=app, user=self.create_user("api_app@example.com")
)
token = ApiToken.objects.create(
application=app, user=user, expires_at=None, name="test_api_auth_application_bound"
)
# TODO(getsentry/team-ospo#188): this should be extension scope once that gets added.
assert auth.get_relocation_scope() == RelocationScope.Global
assert token.get_relocation_scope() == RelocationScope.Global
# Unbound to an app == config scope.
with assume_test_silo_mode(SiloMode.CONTROL):
auth = ApiAuthorization.objects.create(user=self.create_user("api_auth@example.com"))
token = ApiToken.objects.create(
user=user, expires_at=None, name="test_api_auth_not_bound"
)
assert auth.get_relocation_scope() == RelocationScope.Config
assert token.get_relocation_scope() == RelocationScope.Config
verify_models_in_output(expected_models, self.export())
@expect_models(DYNAMIC_RELOCATION_SCOPE_TESTED, NotificationAction, NotificationActionProject)
def test_notification_action(self, expected_models: list[type[Model]]) -> None:
# Bound to an app == global scope.
app = self.create_sentry_app(name="test_app", organization=self.organization)
action = self.create_notification_action(
organization=self.organization, projects=[self.project], sentry_app_id=app.id
)
action_project = NotificationActionProject.objects.get(action=action)
# TODO(getsentry/team-ospo#188): this should be extension scope once that gets added.
assert action.get_relocation_scope() == RelocationScope.Global
assert action_project.get_relocation_scope() == RelocationScope.Global
# Bound to an integration == global scope.
integration = self.create_integration(
self.organization, provider="slack", name="Slack 1", external_id="slack:1"
)
action = self.create_notification_action(
organization=self.organization, projects=[self.project], integration_id=integration.id
)
action_project = NotificationActionProject.objects.get(action=action)
# TODO(getsentry/team-ospo#188): this should be extension scope once that gets added.
assert action.get_relocation_scope() == RelocationScope.Global
assert action_project.get_relocation_scope() == RelocationScope.Global
# Unbound to an app or integration == organization scope.
action = self.create_notification_action(
organization=self.organization, projects=[self.project]
)
action_project = NotificationActionProject.objects.get(action=action)
assert action.get_relocation_scope() == RelocationScope.Organization
assert action_project.get_relocation_scope() == RelocationScope.Organization
verify_models_in_output(expected_models, self.export())
| DynamicRelocationScopeTests |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 5337,
"end": 5501
} | class ____(TypedDict):
users: int
users_healthy: int
users_crashed: int
users_abnormal: int
users_unhandled: int
users_errored: int
| UserCounts |
python | apache__airflow | airflow-ctl/src/airflowctl/api/operations.py | {
"start": 24243,
"end": 24519
} | class ____(BaseOperations):
"""Provider operations."""
def list(self) -> ProviderCollectionResponse | ServerResponseError:
"""List all providers."""
return super().execute_list(path="providers", data_model=ProviderCollectionResponse)
| ProvidersOperations |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 74859,
"end": 75858
} | class ____(Operation):
def call(self, x):
return backend.numpy.deg2rad(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(x.dtype)
if dtype in ["int64", "float64"]:
dtype = "float64"
elif dtype not in ["bfloat16", "float16"]:
dtype = backend.floatx()
return KerasTensor(x.shape, dtype)
@keras_export(["keras.ops.deg2rad", "keras.ops.numpy.deg2rad"])
def deg2rad(x):
"""Convert angles from degrees to radians.
The conversion is defined as:
`rad = deg * (π / 180)`
Args:
x: Input tensor of angles in degrees.
Returns:
A tensor containing angles converted to radians.
Examples:
>>> from keras import ops
>>> ops.deg2rad(180.0)
3.141592653589793
>>> ops.deg2rad([0.0, 90.0, 180.0])
array([0., 1.57079633, 3.14159265])
"""
if any_symbolic_tensors((x,)):
return Deg2rad().symbolic_call(x)
return backend.numpy.deg2rad(x)
| Deg2rad |
python | encode__django-rest-framework | rest_framework/authtoken/admin.py | {
"start": 408,
"end": 794
} | class ____(ChangeList):
"""Map to matching User id"""
def url_for_result(self, result):
pk = result.user.pk
return reverse('admin:%s_%s_change' % (self.opts.app_label,
self.opts.model_name),
args=(quote(pk),),
current_app=self.model_admin.admin_site.name)
| TokenChangeList |
python | matplotlib__matplotlib | lib/matplotlib/font_manager.py | {
"start": 10020,
"end": 19748
} | class ____:
"""
A class for storing Font properties.
It is used when populating the font lookup dictionary.
"""
fname: str = ''
name: str = ''
style: str = 'normal'
variant: str = 'normal'
weight: str | int = 'normal'
stretch: str = 'normal'
size: str = 'medium'
def _repr_html_(self) -> str:
png_stream = self._repr_png_()
png_b64 = b64encode(png_stream).decode()
return f"<img src=\"data:image/png;base64, {png_b64}\" />"
def _repr_png_(self) -> bytes:
from matplotlib.figure import Figure # Circular import.
fig = Figure()
font_path = Path(self.fname) if self.fname != '' else None
fig.text(0, 0, self.name, font=font_path)
with BytesIO() as buf:
fig.savefig(buf, bbox_inches='tight', transparent=True)
return buf.getvalue()
def ttfFontProperty(font):
"""
Extract information from a TrueType font file.
Parameters
----------
font : `.FT2Font`
The TrueType font file from which information will be extracted.
Returns
-------
`FontEntry`
The extracted font properties.
"""
name = font.family_name
# Styles are: italic, oblique, and normal (default)
sfnt = font.get_sfnt()
mac_key = (1, # platform: macintosh
0, # id: roman
0) # langid: english
ms_key = (3, # platform: microsoft
1, # id: unicode_cs
0x0409) # langid: english_united_states
# These tables are actually mac_roman-encoded, but mac_roman support may be
# missing in some alternative Python implementations and we are only going
# to look for ASCII substrings, where any ASCII-compatible encoding works
# - or big-endian UTF-16, since important Microsoft fonts use that.
sfnt2 = (sfnt.get((*mac_key, 2), b'').decode('latin-1').lower() or
sfnt.get((*ms_key, 2), b'').decode('utf_16_be').lower())
sfnt4 = (sfnt.get((*mac_key, 4), b'').decode('latin-1').lower() or
sfnt.get((*ms_key, 4), b'').decode('utf_16_be').lower())
if sfnt4.find('oblique') >= 0:
style = 'oblique'
elif sfnt4.find('italic') >= 0:
style = 'italic'
elif sfnt2.find('regular') >= 0:
style = 'normal'
elif ft2font.StyleFlags.ITALIC in font.style_flags:
style = 'italic'
else:
style = 'normal'
# Variants are: small-caps and normal (default)
# !!!! Untested
if name.lower() in ['capitals', 'small-caps']:
variant = 'small-caps'
else:
variant = 'normal'
# The weight-guessing algorithm is directly translated from fontconfig
# 2.13.1's FcFreeTypeQueryFaceInternal (fcfreetype.c).
wws_subfamily = 22
typographic_subfamily = 16
font_subfamily = 2
styles = [
sfnt.get((*mac_key, wws_subfamily), b'').decode('latin-1'),
sfnt.get((*mac_key, typographic_subfamily), b'').decode('latin-1'),
sfnt.get((*mac_key, font_subfamily), b'').decode('latin-1'),
sfnt.get((*ms_key, wws_subfamily), b'').decode('utf-16-be'),
sfnt.get((*ms_key, typographic_subfamily), b'').decode('utf-16-be'),
sfnt.get((*ms_key, font_subfamily), b'').decode('utf-16-be'),
]
styles = [*filter(None, styles)] or [font.style_name]
def get_weight(): # From fontconfig's FcFreeTypeQueryFaceInternal.
# OS/2 table weight.
os2 = font.get_sfnt_table("OS/2")
if os2 and os2["version"] != 0xffff:
return os2["usWeightClass"]
# PostScript font info weight.
try:
ps_font_info_weight = (
font.get_ps_font_info()["weight"].replace(" ", "") or "")
except ValueError:
pass
else:
for regex, weight in _weight_regexes:
if re.fullmatch(regex, ps_font_info_weight, re.I):
return weight
# Style name weight.
for style in styles:
style = style.replace(" ", "")
for regex, weight in _weight_regexes:
if re.search(regex, style, re.I):
return weight
if ft2font.StyleFlags.BOLD in font.style_flags:
return 700 # "bold"
return 500 # "medium", not "regular"!
weight = int(get_weight())
# Stretch can be absolute and relative
# Absolute stretches are: ultra-condensed, extra-condensed, condensed,
# semi-condensed, normal, semi-expanded, expanded, extra-expanded,
# and ultra-expanded.
# Relative stretches are: wider, narrower
# Child value is: inherit
if any(word in sfnt4 for word in ['narrow', 'condensed', 'cond']):
stretch = 'condensed'
elif 'demi cond' in sfnt4:
stretch = 'semi-condensed'
elif any(word in sfnt4 for word in ['wide', 'expanded', 'extended']):
stretch = 'expanded'
else:
stretch = 'normal'
# Sizes can be absolute and relative.
# Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
# and xx-large.
# Relative sizes are: larger, smaller
# Length value is an absolute font size, e.g., 12pt
# Percentage values are in 'em's. Most robust specification.
if not font.scalable:
raise NotImplementedError("Non-scalable fonts are not supported")
size = 'scalable'
return FontEntry(font.fname, name, style, variant, weight, stretch, size)
def afmFontProperty(fontpath, font):
"""
Extract information from an AFM font file.
Parameters
----------
fontpath : str
The filename corresponding to *font*.
font : AFM
The AFM font file from which information will be extracted.
Returns
-------
`FontEntry`
The extracted font properties.
"""
name = font.get_familyname()
fontname = font.get_fontname().lower()
# Styles are: italic, oblique, and normal (default)
if font.get_angle() != 0 or 'italic' in name.lower():
style = 'italic'
elif 'oblique' in name.lower():
style = 'oblique'
else:
style = 'normal'
# Variants are: small-caps and normal (default)
# !!!! Untested
if name.lower() in ['capitals', 'small-caps']:
variant = 'small-caps'
else:
variant = 'normal'
weight = font.get_weight().lower()
if weight not in weight_dict:
weight = 'normal'
# Stretch can be absolute and relative
# Absolute stretches are: ultra-condensed, extra-condensed, condensed,
# semi-condensed, normal, semi-expanded, expanded, extra-expanded,
# and ultra-expanded.
# Relative stretches are: wider, narrower
# Child value is: inherit
if 'demi cond' in fontname:
stretch = 'semi-condensed'
elif any(word in fontname for word in ['narrow', 'cond']):
stretch = 'condensed'
elif any(word in fontname for word in ['wide', 'expanded', 'extended']):
stretch = 'expanded'
else:
stretch = 'normal'
# Sizes can be absolute and relative.
# Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
# and xx-large.
# Relative sizes are: larger, smaller
# Length value is an absolute font size, e.g., 12pt
# Percentage values are in 'em's. Most robust specification.
# All AFM fonts are apparently scalable.
size = 'scalable'
return FontEntry(fontpath, name, style, variant, weight, stretch, size)
def _cleanup_fontproperties_init(init_method):
"""
A decorator to limit the call signature to single a positional argument
or alternatively only keyword arguments.
We still accept but deprecate all other call signatures.
When the deprecation expires we can switch the signature to::
__init__(self, pattern=None, /, *, family=None, style=None, ...)
plus a runtime check that pattern is not used alongside with the
keyword arguments. This results eventually in the two possible
call signatures::
FontProperties(pattern)
FontProperties(family=..., size=..., ...)
"""
@functools.wraps(init_method)
def wrapper(self, *args, **kwargs):
# multiple args with at least some positional ones
if len(args) > 1 or len(args) == 1 and kwargs:
# Note: Both cases were previously handled as individual properties.
# Therefore, we do not mention the case of font properties here.
_api.warn_deprecated(
"3.10",
message="Passing individual properties to FontProperties() "
"positionally was deprecated in Matplotlib %(since)s and "
"will be removed in %(removal)s. Please pass all properties "
"via keyword arguments."
)
# single non-string arg -> clearly a family not a pattern
if len(args) == 1 and not kwargs and not cbook.is_scalar_or_string(args[0]):
# Case font-family list passed as single argument
_api.warn_deprecated(
"3.10",
message="Passing family as positional argument to FontProperties() "
"was deprecated in Matplotlib %(since)s and will be removed "
"in %(removal)s. Please pass family names as keyword"
"argument."
)
# Note on single string arg:
# This has been interpreted as pattern so far. We are already raising if a
# non-pattern compatible family string was given. Therefore, we do not need
# to warn for this case.
return init_method(self, *args, **kwargs)
return wrapper
| FontEntry |
python | huggingface__transformers | src/transformers/models/deit/configuration_deit.py | {
"start": 813,
"end": 5639
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DeiTModel`]. It is used to instantiate an DeiT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the DeiT
[facebook/deit-base-distilled-patch16-224](https://huggingface.co/facebook/deit-base-distilled-patch16-224)
architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
image_size (`int`, *optional*, defaults to 224):
The size (resolution) of each image.
patch_size (`int`, *optional*, defaults to 16):
The size (resolution) of each patch.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
qkv_bias (`bool`, *optional*, defaults to `True`):
Whether to add a bias to the queries, keys and values.
encoder_stride (`int`, *optional*, defaults to 16):
Factor to increase the spatial resolution by in the decoder head for masked image modeling.
pooler_output_size (`int`, *optional*):
Dimensionality of the pooler layer. If None, defaults to `hidden_size`.
pooler_act (`str`, *optional*, defaults to `"tanh"`):
The activation function to be used by the pooler.
Example:
```python
>>> from transformers import DeiTConfig, DeiTModel
>>> # Initializing a DeiT deit-base-distilled-patch16-224 style configuration
>>> configuration = DeiTConfig()
>>> # Initializing a model (with random weights) from the deit-base-distilled-patch16-224 style configuration
>>> model = DeiTModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "deit"
def __init__(
self,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
layer_norm_eps=1e-12,
image_size=224,
patch_size=16,
num_channels=3,
qkv_bias=True,
encoder_stride=16,
pooler_output_size=None,
pooler_act="tanh",
**kwargs,
):
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.qkv_bias = qkv_bias
self.encoder_stride = encoder_stride
self.pooler_output_size = pooler_output_size if pooler_output_size else hidden_size
self.pooler_act = pooler_act
__all__ = ["DeiTConfig"]
| DeiTConfig |
python | scipy__scipy | scipy/stats/_covariance.py | {
"start": 19509,
"end": 20229
} | class ____(Covariance):
__class_getitem__ = None
def __init__(self, cholesky):
L = self._validate_matrix(cholesky, 'cholesky')
self._factor = L
self._log_pdet = 2*np.log(np.diag(self._factor)).sum(axis=-1)
self._rank = L.shape[-1] # must be full rank for cholesky
self._shape = L.shape
self._allow_singular = False
@cached_property
def _covariance(self):
return self._factor @ self._factor.T
def _whiten(self, x):
m = x.T.shape[0]
res = linalg.solve_triangular(self._factor, x.T.reshape(m, -1), lower=True)
return res.reshape(x.T.shape).T
def _colorize(self, x):
return x @ self._factor.T
| CovViaCholesky |
python | keras-team__keras | keras/src/metrics/accuracy_metrics_test.py | {
"start": 7143,
"end": 8979
} | class ____(testing.TestCase):
def test_config(self):
cat_acc_obj = accuracy_metrics.CategoricalAccuracy(
name="categorical_accuracy", dtype="float32"
)
self.assertEqual(cat_acc_obj.name, "categorical_accuracy")
self.assertEqual(len(cat_acc_obj.variables), 2)
self.assertEqual(cat_acc_obj._dtype, "float32")
# Test get_config
cat_acc_obj_config = cat_acc_obj.get_config()
self.assertEqual(cat_acc_obj_config["name"], "categorical_accuracy")
self.assertEqual(cat_acc_obj_config["dtype"], "float32")
# Check save and restore config
cat_acc_obj2 = accuracy_metrics.CategoricalAccuracy.from_config(
cat_acc_obj_config
)
self.assertEqual(cat_acc_obj2.name, "categorical_accuracy")
self.assertEqual(len(cat_acc_obj2.variables), 2)
self.assertEqual(cat_acc_obj2._dtype, "float32")
def test_unweighted(self):
cat_acc_obj = accuracy_metrics.CategoricalAccuracy(
name="categorical_accuracy", dtype="float32"
)
y_true = np.array([[0, 0, 1], [0, 1, 0]])
y_pred = np.array([[0.1, 0.9, 0.8], [0.05, 0.95, 0]])
cat_acc_obj.update_state(y_true, y_pred)
result = cat_acc_obj.result()
self.assertAllClose(result, 0.5, atol=1e-3)
def test_weighted(self):
cat_acc_obj = accuracy_metrics.CategoricalAccuracy(
name="categorical_accuracy", dtype="float32"
)
y_true = np.array([[0, 0, 1], [0, 1, 0]])
y_pred = np.array([[0.1, 0.9, 0.8], [0.05, 0.95, 0]])
sample_weight = np.array([0.7, 0.3])
cat_acc_obj.update_state(y_true, y_pred, sample_weight=sample_weight)
result = cat_acc_obj.result()
self.assertAllClose(result, 0.3, atol=1e-3)
| CategoricalAccuracyTest |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_copy.py | {
"start": 65,
"end": 1266
} | class ____:
@pytest.mark.parametrize("attr", ["index", "columns"])
def test_copy_index_name_checking(self, float_frame, attr):
# don't want to be able to modify the index stored elsewhere after
# making a copy
ind = getattr(float_frame, attr)
ind.name = None
cp = float_frame.copy()
getattr(cp, attr).name = "foo"
assert getattr(float_frame, attr).name is None
def test_copy(self, float_frame, float_string_frame):
cop = float_frame.copy()
cop["E"] = cop["A"]
assert "E" not in float_frame
# copy objects
copy = float_string_frame.copy()
assert copy._mgr is not float_string_frame._mgr
def test_copy_consolidates(self):
# GH#42477
df = DataFrame(
{
"a": np.random.default_rng(2).integers(0, 100, size=55),
"b": np.random.default_rng(2).integers(0, 100, size=55),
}
)
for i in range(10):
df.loc[:, f"n_{i}"] = np.random.default_rng(2).integers(0, 100, size=55)
assert len(df._mgr.blocks) == 11
result = df.copy()
assert len(result._mgr.blocks) == 1
| TestCopy |
python | ansible__ansible | lib/ansible/module_utils/errors.py | {
"start": 2820,
"end": 2924
} | class ____(AnsibleValidationError):
"""Error with conditionally required parameters"""
| RequiredIfError |
python | huggingface__transformers | tests/models/sam3/test_modeling_sam3.py | {
"start": 9222,
"end": 16218
} | class ____:
def __init__(
self,
parent,
num_channels=3,
image_size=224, # Keep reasonable size: 224 = 16 * 14
hidden_size=32,
patch_size=14,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=64,
window_size=8, # 224/14 = 16 patches, 16/2 = 8 per window
global_attn_indexes=None,
fpn_hidden_size=32,
scale_factors=None,
geometry_encoder_hidden_size=32,
geometry_encoder_num_layers=1, # Reduced from 2 to 1
detr_encoder_hidden_size=32,
detr_encoder_num_layers=1, # Reduced from 2 to 1
detr_decoder_hidden_size=32,
detr_decoder_num_layers=1, # Reduced from 2 to 1
detr_decoder_num_queries=5, # Reduced from 10 to 5
mask_decoder_hidden_size=32,
batch_size=2,
is_training=False,
):
if global_attn_indexes is None:
global_attn_indexes = [0, 1]
if scale_factors is None:
scale_factors = [2.0, 1.0] # Just 2 scales to reduce params
self.parent = parent
self.num_channels = num_channels
self.image_size = image_size
self.hidden_size = hidden_size
self.patch_size = patch_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.window_size = window_size
self.global_attn_indexes = global_attn_indexes
self.fpn_hidden_size = fpn_hidden_size
self.scale_factors = scale_factors
self.batch_size = batch_size
self.is_training = is_training
# Geometry encoder
self.geometry_encoder_hidden_size = geometry_encoder_hidden_size
self.geometry_encoder_num_layers = geometry_encoder_num_layers
# DETR encoder/decoder
self.detr_encoder_hidden_size = detr_encoder_hidden_size
self.detr_encoder_num_layers = detr_encoder_num_layers
self.detr_decoder_hidden_size = detr_decoder_hidden_size
self.detr_decoder_num_layers = detr_decoder_num_layers
self.detr_decoder_num_queries = detr_decoder_num_queries
# Mask decoder
self.mask_decoder_hidden_size = mask_decoder_hidden_size
def prepare_config_and_inputs(self):
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
# Simple text input (will be processed by text encoder)
input_ids = torch.randint(0, 1000, (self.batch_size, 16), device=torch_device)
attention_mask = torch.ones_like(input_ids)
config = self.get_config()
return config, pixel_values, input_ids, attention_mask
def get_config(self):
backbone_config = Sam3ViTConfig(
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
num_channels=self.num_channels,
image_size=self.image_size,
patch_size=self.patch_size,
window_size=self.window_size,
global_attn_indexes=self.global_attn_indexes,
)
vision_config = Sam3VisionConfig(
backbone_config=backbone_config,
fpn_hidden_size=self.fpn_hidden_size,
scale_factors=self.scale_factors,
)
# Small text config for testing (instead of default full CLIP model)
text_config = {
"vocab_size": 1000, # Keep at 1000 for stability
"hidden_size": 32,
"intermediate_size": 64,
"projection_dim": 32,
"num_hidden_layers": 1,
"num_attention_heads": 4,
"max_position_embeddings": 32, # Keep at 32 for stability
"hidden_act": "gelu",
}
geometry_encoder_config = Sam3GeometryEncoderConfig(
hidden_size=self.geometry_encoder_hidden_size,
num_layers=self.geometry_encoder_num_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
mask_fuser_hidden_size=self.geometry_encoder_hidden_size, # Match hidden_size to reduce params
mask_fuser_num_layers=1, # Reduce from default 2 to 1
)
detr_encoder_config = Sam3DETREncoderConfig(
hidden_size=self.detr_encoder_hidden_size,
num_layers=self.detr_encoder_num_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
)
detr_decoder_config = Sam3DETRDecoderConfig(
hidden_size=self.detr_decoder_hidden_size,
num_layers=self.detr_decoder_num_layers,
num_queries=self.detr_decoder_num_queries,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
)
mask_decoder_config = Sam3MaskDecoderConfig(
hidden_size=self.mask_decoder_hidden_size,
num_upsampling_stages=2, # Reduced from 3 to 2
)
return Sam3Config(
vision_config=vision_config,
text_config=text_config,
geometry_encoder_config=geometry_encoder_config,
detr_encoder_config=detr_encoder_config,
detr_decoder_config=detr_decoder_config,
mask_decoder_config=mask_decoder_config,
)
def create_and_check_model(self, config, pixel_values, input_ids, attention_mask):
model = Sam3Model(config=config)
model.to(torch_device)
model.eval()
with torch.no_grad():
result = model(pixel_values=pixel_values, input_ids=input_ids, attention_mask=attention_mask)
# Check output shapes
self.parent.assertIsNotNone(result.pred_masks)
self.parent.assertIsNotNone(result.pred_boxes)
self.parent.assertIsNotNone(result.pred_logits)
# Masks should be [batch_size, num_queries, H, W]
self.parent.assertEqual(result.pred_masks.shape[0], self.batch_size)
self.parent.assertEqual(result.pred_masks.shape[1], self.detr_decoder_num_queries)
# Boxes should be [batch_size, num_queries, 4]
self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.detr_decoder_num_queries, 4))
# Logits should be [batch_size, num_queries]
self.parent.assertEqual(result.pred_logits.shape, (self.batch_size, self.detr_decoder_num_queries))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, pixel_values, input_ids, attention_mask = config_and_inputs
inputs_dict = {
"pixel_values": pixel_values,
"input_ids": input_ids,
"attention_mask": attention_mask,
}
return config, inputs_dict
@require_torch
| Sam3ModelTester |
python | getsentry__sentry | src/sentry/hybridcloud/migrations/0022_webhook_payload_update.py | {
"start": 155,
"end": 2009
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = False
dependencies = [
("hybridcloud", "0001_squashed_0021_django_arrayfield_scope_list"),
]
operations = [
migrations.AddField(
model_name="webhookpayload",
name="destination_type",
field=models.CharField(db_default="sentry_region"),
),
migrations.AlterField(
model_name="webhookpayload",
name="region_name",
field=models.CharField(null=True),
),
migrations.AddConstraint(
model_name="webhookpayload",
constraint=models.CheckConstraint(
condition=models.Q(
("destination_type", "sentry_region"), ("region_name__isnull", False)
),
name="webhookpayload_region_name_not_null",
),
),
]
| Migration |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/bincount_op_test.py | {
"start": 1474,
"end": 7991
} | class ____(test_util.TensorFlowTestCase):
def test_empty(self):
with self.session():
self.assertAllEqual(
self.evaluate(bincount_ops.bincount([], minlength=5)),
[0, 0, 0, 0, 0])
self.assertAllEqual(
self.evaluate(bincount_ops.bincount([], minlength=1)), [0])
self.assertAllEqual(
self.evaluate(bincount_ops.bincount([], minlength=0)), [])
self.assertEqual(
self.evaluate(
bincount_ops.bincount([], minlength=0, dtype=np.float32)).dtype,
np.float32)
self.assertEqual(
self.evaluate(
bincount_ops.bincount([], minlength=3, dtype=np.float64)).dtype,
np.float64)
self.assertAllEqual(
self.evaluate(
bincount_ops.bincount(
constant_op.constant([], shape=[0], dtype=np.int32),
minlength=5,
binary_output=True,
)
),
[0, 0, 0, 0, 0],
)
def test_values(self):
with self.session():
self.assertAllEqual(
self.evaluate(bincount_ops.bincount([1, 1, 1, 2, 2, 3])),
[0, 3, 2, 1])
arr = [1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]
self.assertAllEqual(
self.evaluate(bincount_ops.bincount(arr)), [0, 5, 4, 3, 2, 1])
arr += [0, 0, 0, 0, 0, 0]
self.assertAllEqual(
self.evaluate(bincount_ops.bincount(arr)), [6, 5, 4, 3, 2, 1])
self.assertAllEqual(self.evaluate(bincount_ops.bincount([])), [])
self.assertAllEqual(self.evaluate(bincount_ops.bincount([0, 0, 0])), [3])
self.assertAllEqual(
self.evaluate(bincount_ops.bincount([5])), [0, 0, 0, 0, 0, 1])
self.assertAllEqual(
self.evaluate(bincount_ops.bincount(np.arange(10000))),
np.ones(10000))
def test_maxlength(self):
with self.session():
self.assertAllEqual(
self.evaluate(bincount_ops.bincount([5], maxlength=3)), [0, 0, 0])
self.assertAllEqual(
self.evaluate(bincount_ops.bincount([1], maxlength=3)), [0, 1])
self.assertAllEqual(
self.evaluate(bincount_ops.bincount([], maxlength=3)), [])
def test_random_with_weights(self):
num_samples = 10000
with self.session():
np.random.seed(42)
for dtype in [dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64]:
arr = np.random.randint(0, 1000, num_samples)
if dtype == dtypes.int32 or dtype == dtypes.int64:
weights = np.random.randint(-100, 100, num_samples)
else:
weights = np.random.random(num_samples)
self.assertAllClose(
self.evaluate(bincount_ops.bincount(arr, weights)),
np.bincount(arr, weights))
def test_random_without_weights(self):
num_samples = 10000
with self.session():
np.random.seed(42)
for dtype in [np.int32, np.float32]:
arr = np.random.randint(0, 1000, num_samples)
weights = np.ones(num_samples).astype(dtype)
self.assertAllClose(
self.evaluate(bincount_ops.bincount(arr, None)),
np.bincount(arr, weights))
@test_util.run_gpu_only
@test_util.disable_xla("Bincount is deterministic with XLA")
def test_bincount_determinism_error(self):
arr = np.random.randint(0, 1000, size=1000)
with test_util.deterministic_ops(), self.assertRaisesRegex(
errors_impl.UnimplementedError,
"Determinism is not yet supported in GPU implementation of "
"(Dense)?Bincount.",
):
self.evaluate(bincount_ops.bincount(arr, None, axis=None))
arr = np.random.randint(0, 1000, size=(100, 100))
with test_util.deterministic_ops(), self.assertRaisesRegex(
errors_impl.UnimplementedError,
"Determinism is not yet supported in GPU implementation of "
"(Dense)?Bincount."):
self.evaluate(bincount_ops.bincount(arr, None, axis=-1))
def test_zero_weights(self):
with self.session():
self.assertAllEqual(
self.evaluate(bincount_ops.bincount(np.arange(1000), np.zeros(1000))),
np.zeros(1000))
@test_util.disable_xla("This is not raised on XLA CPU")
def test_negative(self):
# unsorted_segment_sum will only report InvalidArgumentError on CPU
with self.cached_session(), ops.device("/CPU:0"):
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError), "must be non-negative"
):
self.evaluate(bincount_ops.bincount([1, 2, 3, -1, 6, 8]))
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError), "must be non-negative"
):
self.evaluate(
gen_math_ops.dense_bincount(
input=[[1, 1, 3], [0, -1, 2]], weights=[], size=4
)
)
@test_util.run_in_graph_and_eager_modes
def test_shape_function(self):
# size must be scalar.
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError),
"(?s)Shape must be rank 0 but is rank 1.*Bincount"):
gen_math_ops.bincount([1, 2, 3, 1, 6, 8], [1], [])
# size must be positive.
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"must be non-negative"):
gen_math_ops.bincount([1, 2, 3, 1, 6, 8], -5, [])
# if size is a constant then the shape is known.
v1 = gen_math_ops.bincount([1, 2, 3, 1, 6, 8], 5, [])
self.assertAllEqual(v1.get_shape().as_list(), [5])
# if size is a placeholder then the shape is unknown.
with ops.Graph().as_default():
s = array_ops.placeholder(dtype=dtypes.int32)
v2 = gen_math_ops.bincount([1, 2, 3, 1, 6, 8], s, [])
self.assertAllEqual(v2.get_shape().as_list(), [None])
@test_util.run_in_graph_and_eager_modes
def test_invalid_inputs(self):
binary_output = True
inp = random_ops.random_uniform(
shape=[10, 10],
minval=-10000,
maxval=10000,
dtype=dtypes.int32,
seed=-2460)
size = random_ops.random_uniform(
shape=[], minval=-10000, maxval=10000, dtype=dtypes.int32, seed=-10000)
weights = random_ops.random_uniform(
shape=[],
minval=-10000,
maxval=10000,
dtype=dtypes.float32,
seed=-10000)
with self.assertRaises(errors.InvalidArgumentError):
self.evaluate(
gen_math_ops.dense_bincount(
input=inp,
size=size,
weights=weights,
binary_output=binary_output))
| BincountTest |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/np_dtypes_test.py | {
"start": 982,
"end": 2466
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.parameters([False, True])
def testAllowF64False(self, prefer_f32):
np_dtypes.set_allow_float64(False)
np_dtypes.set_prefer_float32(prefer_f32)
self.assertEqual(dtypes.float32, np_dtypes.default_float_type())
self.assertEqual(dtypes.float32,
np_dtypes._result_type(np.zeros([], np.float64), 1.1))
def testAllowF64TruePreferF32False(self):
np_dtypes.set_allow_float64(True)
np_dtypes.set_prefer_float32(False)
self.assertEqual(dtypes.float64, np_dtypes.default_float_type())
self.assertEqual(dtypes.float64, np_dtypes._result_type(1.1))
self.assertEqual(dtypes.complex128, np_dtypes._result_type(1.j))
def testAllowF64TruePreferF32True(self):
np_dtypes.set_allow_float64(True)
np_dtypes.set_prefer_float32(True)
self.assertEqual(dtypes.float32, np_dtypes.default_float_type())
self.assertEqual(dtypes.float32, np_dtypes._result_type(1.1))
self.assertEqual(dtypes.float64,
np_dtypes._result_type(np.zeros([], np.float64), 1.1))
self.assertEqual(dtypes.complex64, np_dtypes._result_type(1.1j))
self.assertEqual(dtypes.complex128,
np_dtypes._result_type(np.zeros([], np.complex128), 1.1j))
self.assertEqual(dtypes.complex64,
np_dtypes._result_type(np.zeros([], np.float32), 1.1j))
if __name__ == '__main__':
ops.enable_eager_execution()
test.main()
| DTypeTest |
python | google__jax | jax/experimental/mosaic/gpu/constraints.py | {
"start": 10560,
"end": 11436
} | class ____:
"""States that `lhs` and `rhs` are equal."""
lhs: Expression
rhs: Expression
def holds(self) -> bool | None:
if self.lhs == self.rhs:
return True
if isinstance(self.lhs, Constant) and isinstance(self.rhs, Constant):
return False
return None
def __str__(self):
return f"Equals({self.lhs} == {self.rhs})"
_SUPPORTED_TILED_RELAYOUTS = frozenset([
# Transposed layouts.
(fa.WGMMA_LAYOUT, fa.WGMMA_TRANSPOSED_LAYOUT),
(fa.WGMMA_TRANSPOSED_LAYOUT, fa.WGMMA_LAYOUT),
(fa.TCGEN05_LAYOUT, fa.TCGEN05_TRANSPOSED_LAYOUT),
(fa.TCGEN05_TRANSPOSED_LAYOUT, fa.TCGEN05_LAYOUT),
# "Conversion-optimized" layouts.
(fa.WGMMA_LAYOUT_UPCAST_2X, fa.WGMMA_LAYOUT),
(fa.WGMMA_LAYOUT_UPCAST_4X, fa.WGMMA_LAYOUT_UPCAST_2X),
(fa.WGMMA_LAYOUT_UPCAST_4X, fa.WGMMA_LAYOUT),
])
@dataclasses.dataclass(frozen=True)
| Equals |
python | streamlit__streamlit | lib/tests/streamlit/web/server/bidi_component_request_handler_test.py | {
"start": 6751,
"end": 10127
} | class ____(tornado.testing.AsyncHTTPTestCase):
def setUp(self) -> None: # type: ignore[override]
self.manager = BidiComponentManager()
self.temp_dir = tempfile.TemporaryDirectory()
super().setUp()
# Prepare a package with asset_dir and a file to be served
self.package_root = Path(self.temp_dir.name) / "pkg"
self.package_root.mkdir(parents=True, exist_ok=True)
self.assets_dir = self.package_root / "assets"
self.assets_dir.mkdir(parents=True, exist_ok=True)
self.js_file_path = self.assets_dir / "bundle.js"
with open(self.js_file_path, "w") as f:
f.write("console.log('served from asset_dir');")
manifest = ComponentManifest(
name="pkg",
version="0.0.1",
components=[ComponentConfig(name="slider", asset_dir="assets")],
)
self.manager.register_from_manifest(manifest, self.package_root)
def tearDown(self) -> None: # type: ignore[override]
super().tearDown()
self.temp_dir.cleanup()
def get_app(self) -> tornado.web.Application: # type: ignore[override]
return tornado.web.Application(
[
(
r"/_stcore/bidi-components/(.*)",
BidiComponentRequestHandler,
{"component_manager": self.manager},
)
]
)
def test_serves_within_asset_dir(self) -> None:
"""Handler should serve files under manifest-declared asset_dir."""
resp = self.fetch("/_stcore/bidi-components/pkg.slider/bundle.js")
assert resp.code == 200
assert resp.body.decode() == "console.log('served from asset_dir');"
def test_forbids_traversal_outside_asset_dir(self) -> None:
"""Traversal outside asset_dir is forbidden and returns 403."""
resp = self.fetch("/_stcore/bidi-components/pkg.slider/../../etc/passwd")
assert resp.code == 403
def test_absolute_path_injection_forbidden(self) -> None:
"""Absolute path injection via double-slash should be forbidden (403)."""
# When the requested filename begins with a slash due to a double-slash in the URL,
# joining with the component root would otherwise discard the root. We must reject it.
resp = self.fetch("/_stcore/bidi-components/pkg.slider//etc/passwd")
assert resp.code == 403
def test_symlink_escape_outside_asset_dir_forbidden(self) -> None:
"""Symlink in asset_dir pointing outside should be forbidden (403)."""
# Create a real file outside of the component asset_dir
outside_file = Path(self.temp_dir.name) / "outside.js"
outside_file.write_text("console.log('outside');")
# Create a symlink inside the asset_dir pointing to the outside file
link_path = self.assets_dir / "link_out.js"
try:
# On Windows, creating symlinks may require elevated permissions; skip if unsupported
os.symlink(outside_file, link_path)
except (OSError, NotImplementedError):
self.skipTest("Symlinks not supported in this environment")
# Attempt to fetch the symlinked file via the handler
resp = self.fetch("/_stcore/bidi-components/pkg.slider/link_out.js")
assert resp.code == 403
| BidiComponentRequestHandlerAssetDirTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/inferredTypes3.py | {
"start": 119,
"end": 164
} | class ____(NotImplementedError): ...
| OtherError |
python | python-pillow__Pillow | Tests/test_core_resources.py | {
"start": 802,
"end": 5111
} | class ____:
def teardown_method(self) -> None:
# Restore default values
Image.core.set_alignment(1)
Image.core.set_block_size(1024 * 1024)
Image.core.set_blocks_max(0)
Image.core.clear_cache()
def test_get_alignment(self) -> None:
alignment = Image.core.get_alignment()
assert alignment > 0
def test_set_alignment(self) -> None:
for i in [1, 2, 4, 8, 16, 32]:
Image.core.set_alignment(i)
alignment = Image.core.get_alignment()
assert alignment == i
# Try to construct new image
Image.new("RGB", (10, 10))
with pytest.raises(ValueError):
Image.core.set_alignment(0)
with pytest.raises(ValueError):
Image.core.set_alignment(-1)
with pytest.raises(ValueError):
Image.core.set_alignment(3)
def test_get_block_size(self) -> None:
block_size = Image.core.get_block_size()
assert block_size >= 4096
def test_set_block_size(self) -> None:
for i in [4096, 2 * 4096, 3 * 4096]:
Image.core.set_block_size(i)
block_size = Image.core.get_block_size()
assert block_size == i
# Try to construct new image
Image.new("RGB", (10, 10))
with pytest.raises(ValueError):
Image.core.set_block_size(0)
with pytest.raises(ValueError):
Image.core.set_block_size(-1)
with pytest.raises(ValueError):
Image.core.set_block_size(4000)
def test_set_block_size_stats(self) -> None:
Image.core.reset_stats()
Image.core.set_blocks_max(0)
Image.core.set_block_size(4096)
Image.new("RGB", (256, 256))
stats = Image.core.get_stats()
assert stats["new_count"] >= 1
assert stats["allocated_blocks"] >= 64
if not is_pypy():
assert stats["freed_blocks"] >= 64
def test_get_blocks_max(self) -> None:
blocks_max = Image.core.get_blocks_max()
assert blocks_max >= 0
def test_set_blocks_max(self) -> None:
for i in [0, 1, 10]:
Image.core.set_blocks_max(i)
blocks_max = Image.core.get_blocks_max()
assert blocks_max == i
# Try to construct new image
Image.new("RGB", (10, 10))
with pytest.raises(ValueError):
Image.core.set_blocks_max(-1)
if sys.maxsize < 2**32:
with pytest.raises(ValueError):
Image.core.set_blocks_max(2**29)
@pytest.mark.skipif(is_pypy(), reason="Images not collected")
def test_set_blocks_max_stats(self) -> None:
Image.core.reset_stats()
Image.core.set_blocks_max(128)
Image.core.set_block_size(4096)
Image.new("RGB", (256, 256))
Image.new("RGB", (256, 256))
stats = Image.core.get_stats()
assert stats["new_count"] >= 2
assert stats["allocated_blocks"] >= 64
assert stats["reused_blocks"] >= 64
assert stats["freed_blocks"] == 0
assert stats["blocks_cached"] == 64
@pytest.mark.skipif(is_pypy(), reason="Images not collected")
def test_clear_cache_stats(self) -> None:
Image.core.reset_stats()
Image.core.clear_cache()
Image.core.set_blocks_max(128)
Image.core.set_block_size(4096)
Image.new("RGB", (256, 256))
Image.new("RGB", (256, 256))
# Keep 16 blocks in cache
Image.core.clear_cache(16)
stats = Image.core.get_stats()
assert stats["new_count"] >= 2
assert stats["allocated_blocks"] >= 64
assert stats["reused_blocks"] >= 64
assert stats["freed_blocks"] >= 48
assert stats["blocks_cached"] == 16
def test_large_images(self) -> None:
Image.core.reset_stats()
Image.core.set_blocks_max(0)
Image.core.set_block_size(4096)
Image.new("RGB", (2048, 16))
Image.core.clear_cache()
stats = Image.core.get_stats()
assert stats["new_count"] >= 1
assert stats["allocated_blocks"] >= 16
assert stats["reused_blocks"] >= 0
assert stats["blocks_cached"] == 0
if not is_pypy():
assert stats["freed_blocks"] >= 16
| TestCoreMemory |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 202828,
"end": 202928
} | class ____(
_Int8MultiRangeTests, _MultiRangeTypeRoundTrip
):
pass
| Int8MultiRangeRoundTripTest |
python | django__django | tests/custom_pk/fields.py | {
"start": 1618,
"end": 1914
} | class ____(models.BigAutoField):
def from_db_value(self, value, expression, connection):
if value is None:
return None
return MyWrapper(value)
def get_prep_value(self, value):
if value is None:
return None
return int(value)
| MyAutoField |
python | dask__distributed | distributed/diagnostics/eventstream.py | {
"start": 253,
"end": 2190
} | class ____(SchedulerPlugin):
"""Maintain a copy of worker events"""
def __init__(self, scheduler=None):
self.name = "EventStream"
self.buffer = []
if scheduler:
scheduler.add_plugin(self)
def transition(self, key, start, finish, *args, **kwargs):
if start == "processing":
kwargs["key"] = key
if finish == "memory" or finish == "erred":
self.buffer.append(kwargs)
def swap_buffer(scheduler, es):
es.buffer, buffer = [], es.buffer
return buffer
def teardown(scheduler, es):
scheduler.remove_plugin(name=es.name)
async def eventstream(address, interval):
"""Open a TCP connection to scheduler, receive batched task messages
The messages coming back are lists of dicts. Each dict is of the following
form::
{'key': 'mykey', 'worker': 'host:port', 'status': status,
'compute_start': time(), 'compute_stop': time(),
'transfer_start': time(), 'transfer_stop': time(),
'disk_load_start': time(), 'disk_load_stop': time(),
'other': 'junk'}
Where ``status`` is either 'OK', or 'error'
Parameters
----------
address: address of scheduler
interval: time between batches, in seconds
Examples
--------
>>> stream = await eventstream('127.0.0.1:8786', 0.100) # doctest: +SKIP
>>> print(await read(stream)) # doctest: +SKIP
[{'key': 'x', 'status': 'OK', 'worker': '192.168.0.1:54684', ...},
{'key': 'y', 'status': 'error', 'worker': '192.168.0.1:54684', ...}]
"""
address = coerce_to_address(address)
comm = await connect(address)
await comm.write(
{
"op": "feed",
"setup": dumps_function(EventStream),
"function": dumps_function(swap_buffer),
"interval": interval,
"teardown": dumps_function(teardown),
}
)
return comm
| EventStream |
python | getsentry__sentry | tests/sentry/users/api/serializers/test_user.py | {
"start": 1865,
"end": 3899
} | class ____(TestCase):
def test_simple(self) -> None:
user = self.create_user()
UserPermission.objects.create(user=user, permission="foo")
org = self.create_organization(owner=user)
auth_provider = AuthProvider.objects.create(organization_id=org.id, provider="dummy")
auth_identity = AuthIdentity.objects.create(
auth_provider=auth_provider, ident=user.email, user=user
)
auth = Authenticator.objects.create(
type=available_authenticators(ignore_backup=True)[0].type, user=user, config={}
)
result = serialize(user, user, DetailedUserSerializer())
assert result["id"] == str(user.id)
assert result["has2fa"] is True
assert len(result["emails"]) == 1
assert result["emails"][0]["email"] == user.email
assert result["emails"][0]["is_verified"]
assert "identities" in result
assert len(result["identities"]) == 1
assert result["identities"][0]["id"] == str(auth_identity.id)
assert result["identities"][0]["name"] == auth_identity.ident
assert "authenticators" in result
assert len(result["authenticators"]) == 1
assert result["authenticators"][0]["id"] == str(auth.id)
assert result["canReset2fa"] is True
self.create_organization(owner=user)
result = serialize(user, user, DetailedUserSerializer())
assert result["canReset2fa"] is False
def test_with_avatar(self) -> None:
UserAvatar.objects.create(
user_id=self.user.id,
avatar_type=1, # upload
ident="abc123",
control_file_id=1,
)
result = serialize(self.user, self.user, DetailedUserSerializer())
assert "avatar" in result
assert result["avatar"]["avatarUuid"] == "abc123"
assert result["avatar"]["avatarType"] == "upload"
assert result["avatar"]["avatarUrl"] == "http://testserver/avatar/abc123/"
@control_silo_test
| DetailedUserSerializerTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super12.py | {
"start": 251,
"end": 384
} | class ____(BaseProto):
def method1(self) -> None:
# This should generate an error.
return super().method1()
| ProtoImpl |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/oracledb.py | {
"start": 26753,
"end": 28240
} | class ____(AsyncAdapt_dbapi_cursor):
_cursor: AsyncCursor
_awaitable_cursor_close: bool = False
__slots__ = ()
@property
def outputtypehandler(self):
return self._cursor.outputtypehandler
@outputtypehandler.setter
def outputtypehandler(self, value):
self._cursor.outputtypehandler = value
def var(self, *args, **kwargs):
return self._cursor.var(*args, **kwargs)
def setinputsizes(self, *args: Any, **kwargs: Any) -> Any:
return self._cursor.setinputsizes(*args, **kwargs)
def _aenter_cursor(self, cursor: AsyncCursor) -> AsyncCursor:
try:
return cursor.__enter__()
except Exception as error:
self._adapt_connection._handle_exception(error)
async def _execute_async(self, operation, parameters):
# override to not use mutex, oracledb already has a mutex
if parameters is None:
result = await self._cursor.execute(operation)
else:
result = await self._cursor.execute(operation, parameters)
if self._cursor.description and not self.server_side:
self._rows = collections.deque(await self._cursor.fetchall())
return result
async def _executemany_async(
self,
operation,
seq_of_parameters,
):
# override to not use mutex, oracledb already has a mutex
return await self._cursor.executemany(operation, seq_of_parameters)
| AsyncAdapt_oracledb_cursor |
python | spack__spack | lib/spack/spack/test/concretization/core.py | {
"start": 117774,
"end": 125346
} | class ____:
"""Collects test on separate concretization"""
@pytest.mark.parametrize("strategy", ["minimal", "full"])
def test_two_gmake(self, strategy):
"""Tests that we can concretize a spec with nodes using the same build
dependency pinned at different versions.
o hdf5@1.0
|\
o | pinned-gmake@1.0
o | gmake@3.0
/
o gmake@4.1
"""
spack.config.CONFIG.set("concretizer:duplicates:strategy", strategy)
s = spack.concretize.concretize_one("hdf5")
# Check that hdf5 depends on gmake@=4.1
hdf5_gmake = s["hdf5"].dependencies(name="gmake", deptype="build")
assert len(hdf5_gmake) == 1 and hdf5_gmake[0].satisfies("@=4.1")
# Check that pinned-gmake depends on gmake@=3.0
pinned_gmake = s["pinned-gmake"].dependencies(name="gmake", deptype="build")
assert len(pinned_gmake) == 1 and pinned_gmake[0].satisfies("@=3.0")
@pytest.mark.parametrize("strategy", ["minimal", "full"])
def test_two_setuptools(self, strategy):
"""Tests that we can concretize separate build dependencies, when we are dealing
with extensions.
o py-shapely@1.25.0
|\
| |\
| o | py-setuptools@60
|/ /
| o py-numpy@1.25.0
|/|
| |\
| o | py-setuptools@59
|/ /
o | python@3.11.2
o | gmake@3.0
/
o gmake@4.1
"""
spack.config.CONFIG.set("concretizer:duplicates:strategy", strategy)
s = spack.concretize.concretize_one("py-shapely")
# Requirements on py-shapely
setuptools = s["py-shapely"].dependencies(name="py-setuptools", deptype="build")
assert len(setuptools) == 1 and setuptools[0].satisfies("@=60")
# Requirements on py-numpy
setuptools = s["py-numpy"].dependencies(name="py-setuptools", deptype="build")
assert len(setuptools) == 1 and setuptools[0].satisfies("@=59")
gmake = s["py-numpy"].dependencies(name="gmake", deptype="build")
assert len(gmake) == 1 and gmake[0].satisfies("@=4.1")
# Requirements on python
gmake = s["python"].dependencies(name="gmake", deptype="build")
assert len(gmake) == 1 and gmake[0].satisfies("@=3.0")
def test_solution_without_cycles(self):
"""Tests that when we concretize a spec with cycles, a fallback kicks in to recompute
a solution without cycles.
"""
s = spack.concretize.concretize_one("cycle-a")
assert s["cycle-a"].satisfies("+cycle")
assert s["cycle-b"].satisfies("~cycle")
s = spack.concretize.concretize_one("cycle-b")
assert s["cycle-a"].satisfies("~cycle")
assert s["cycle-b"].satisfies("+cycle")
@pytest.mark.parametrize("strategy", ["minimal", "full"])
def test_pure_build_virtual_dependency(self, strategy):
"""Tests that we can concretize a pure build virtual dependency, and ensures that
pure build virtual dependencies are accounted in the list of possible virtual
dependencies.
virtual-build@1.0
| [type=build, virtual=pkgconfig]
pkg-config@1.0
"""
spack.config.CONFIG.set("concretizer:duplicates:strategy", strategy)
s = spack.concretize.concretize_one("virtual-build")
assert s["pkgconfig"].name == "pkg-config"
@pytest.mark.regression("40595")
def test_no_multiple_solutions_with_different_edges_same_nodes(self):
r"""Tests that the root node, which has a dependency on py-setuptools without constraint,
doesn't randomly pick one of the two setuptools (@=59, @=60) needed by its dependency.
o py-floating@1.25.0/3baitsp
|\
| |\
| | |\
| o | | py-shapely@1.25.0/4hep6my
|/| | |
| |\| |
| | |/
| |/|
| | o py-setuptools@60/cwhbthc
| |/
|/|
| o py-numpy@1.25.0/5q5fx4d
|/|
| |\
| o | py-setuptools@59/jvsa7sd
|/ /
o | python@3.11.2/pdmjekv
o | gmake@3.0/jv7k2bl
/
o gmake@4.1/uo6ot3d
"""
spec_str = "py-floating"
root = spack.concretize.concretize_one(spec_str)
assert root["py-shapely"].satisfies("^py-setuptools@=60")
assert root["py-numpy"].satisfies("^py-setuptools@=59")
edges = root.edges_to_dependencies("py-setuptools")
assert len(edges) == 1
assert edges[0].spec.satisfies("@=60")
@pytest.mark.regression("43647")
def test_specifying_different_versions_build_deps(self):
"""Tests that we can concretize a spec with nodes using the same build
dependency pinned at different versions, when the constraint is specified
in the root spec.
o hdf5@1.0
|\
o | pinned-gmake@1.0
o | gmake@3.0
/
o gmake@4.1
"""
hdf5_str = "hdf5@1.0 ^gmake@4.1"
pinned_str = "pinned-gmake@1.0 ^gmake@3.0"
input_specs = [Spec(hdf5_str), Spec(pinned_str)]
solver = spack.solver.asp.Solver()
result = solver.solve(input_specs)
assert any(x.satisfies(hdf5_str) for x in result.specs)
assert any(x.satisfies(pinned_str) for x in result.specs)
@pytest.mark.regression("44289")
def test_all_extensions_depend_on_same_extendee(self):
"""Tests that we don't reuse dependencies that bring in a different extendee"""
setuptools = spack.concretize.concretize_one("py-setuptools ^python@3.10")
solver = spack.solver.asp.Solver()
setup = spack.solver.asp.SpackSolverSetup()
result, _, _ = solver.driver.solve(
setup, [Spec("py-floating ^python@3.11")], reuse=list(setuptools.traverse())
)
assert len(result.specs) == 1
floating = result.specs[0]
assert all(setuptools.dag_hash() != x.dag_hash() for x in floating.traverse())
pythons = [x for x in floating.traverse() if x.name == "python"]
assert len(pythons) == 1 and pythons[0].satisfies("@3.11")
@pytest.mark.parametrize(
"v_str,v_opts,checksummed",
[
("1.2.3", {"sha256": f"{1:064x}"}, True),
# it's not about the version being "infinite",
# but whether it has a digest
("develop", {"sha256": f"{1:064x}"}, True),
# other hash types
("1.2.3", {"checksum": f"{1:064x}"}, True),
("1.2.3", {"md5": f"{1:032x}"}, True),
("1.2.3", {"sha1": f"{1:040x}"}, True),
("1.2.3", {"sha224": f"{1:056x}"}, True),
("1.2.3", {"sha384": f"{1:096x}"}, True),
("1.2.3", {"sha512": f"{1:0128x}"}, True),
# no digest key
("1.2.3", {"bogus": f"{1:064x}"}, False),
# git version with full commit sha
("1.2.3", {"commit": f"{1:040x}"}, True),
(f"{1:040x}=1.2.3", {}, True),
# git version with short commit sha
("1.2.3", {"commit": f"{1:07x}"}, False),
(f"{1:07x}=1.2.3", {}, False),
# git tag is a moving target
("1.2.3", {"tag": "v1.2.3"}, False),
("1.2.3", {"tag": "v1.2.3", "commit": f"{1:07x}"}, False),
# git branch is a moving target
("1.2.3", {"branch": "releases/1.2"}, False),
# git ref is a moving target
("git.branch=1.2.3", {}, False),
],
)
def test_drop_moving_targets(v_str, v_opts, checksummed):
v = Version(v_str)
assert spack.solver.asp._is_checksummed_version((v, v_opts)) == checksummed
| TestConcretizeSeparately |
python | ray-project__ray | python/ray/_private/thirdparty/pyamdsmi/pyamdsmi.py | {
"start": 5138,
"end": 5328
} | class ____(Structure):
_fields_ = [('num_supported', c_int32),
('current', c_uint32),
('frequency', c_uint64 * RSMI_MAX_NUM_FREQUENCIES)]
| rsmi_frequencies_t |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/mixins.py | {
"start": 10978,
"end": 11754
} | class ____:
"""
Mixin for views that should only be accessible when OIDC is enabled.
If OIDC is not enabled:
* if DEBUG is True, raises an ImproperlyConfigured exception explaining why
* otherwise, returns a 404 response, logging the same warning
"""
debug_error_message = (
"django-oauth-toolkit OIDC views are not enabled unless you "
"have configured OIDC_ENABLED in the settings"
)
def dispatch(self, *args, **kwargs):
if not oauth2_settings.OIDC_ENABLED:
if settings.DEBUG:
raise ImproperlyConfigured(self.debug_error_message)
log.warning(self.debug_error_message)
return HttpResponseNotFound()
return super().dispatch(*args, **kwargs)
| OIDCOnlyMixin |
python | python-pillow__Pillow | Tests/test_image_access.py | {
"start": 6667,
"end": 8452
} | class ____:
IMAGE_MODES1 = ["LA", "RGB", "RGBA"]
IMAGE_MODES2 = ["L", "I", "I;16"]
INVALID_TYPES = ["foo", 1.0, None]
@pytest.mark.parametrize("mode", IMAGE_MODES1)
def test_putpixel_type_error1(self, mode: str) -> None:
im = hopper(mode)
for v in self.INVALID_TYPES:
with pytest.raises(TypeError, match="color must be int or tuple"):
im.putpixel((0, 0), v) # type: ignore[arg-type]
@pytest.mark.parametrize(
"mode, band_numbers, match",
(
("L", (0, 2), "color must be int or single-element tuple"),
("LA", (0, 3), "color must be int, or tuple of one or two elements"),
(
"RGB",
(0, 2, 5),
"color must be int, or tuple of one, three or four elements",
),
),
)
def test_putpixel_invalid_number_of_bands(
self, mode: str, band_numbers: tuple[int, ...], match: str
) -> None:
im = hopper(mode)
for band_number in band_numbers:
with pytest.raises(TypeError, match=match):
im.putpixel((0, 0), (0,) * band_number)
@pytest.mark.parametrize("mode", IMAGE_MODES2)
def test_putpixel_type_error2(self, mode: str) -> None:
im = hopper(mode)
for v in self.INVALID_TYPES:
with pytest.raises(
TypeError, match="color must be int or single-element tuple"
):
im.putpixel((0, 0), v) # type: ignore[arg-type]
@pytest.mark.parametrize("mode", IMAGE_MODES1 + IMAGE_MODES2)
def test_putpixel_overflow_error(self, mode: str) -> None:
im = hopper(mode)
with pytest.raises(OverflowError):
im.putpixel((0, 0), 2**80)
| TestImagePutPixelError |
python | kamyu104__LeetCode-Solutions | Python/number-of-ways-to-assign-edge-weights-ii.py | {
"start": 801,
"end": 3029
} | class ____(object):
def assignEdgeWeights(self, edges, queries):
"""
:type edges: List[List[int]]
:type queries: List[List[int]]
:rtype: List[int]
"""
MOD = 10**9+7
def iter_dfs():
lookup = [False]*len(adj)
lookup2 = [[] for _ in xrange(len(adj))]
for i, q in enumerate(queries):
for x in q:
lookup2[x-1].append(i)
uf = UnionFind(len(adj))
ancestor = range(len(adj))
dist = [0]*len(adj)
result = [0]*len(queries)
stk = [(1, (0,))]
while stk:
step, args = stk.pop()
if step == 1:
u = args[0]
for i in lookup2[u]:
if queries[i][0] == queries[i][1]:
continue
result[i] += dist[u]
for x in queries[i]:
if lookup[x-1]:
result[i] -= 2*dist[ancestor[uf.find_set(x-1)]]
lookup[u] = True
stk.append((2, (u, 0)))
elif step == 2:
u, i = args
if i == len(adj[u]):
continue
v = adj[u][i]
stk.append((2, (u, i+1)))
if lookup[v]:
continue
dist[v] = dist[u]+1
stk.append((3, (v, u)))
stk.append((1, (v, u)))
elif step == 3:
v, u = args
uf.union_set(v, u)
ancestor[uf.find_set(u)] = u
return result
adj = [[] for _ in xrange(len(edges)+1)]
for u, v in edges:
adj[u-1].append(v-1)
adj[v-1].append(u-1)
result = iter_dfs()
POW2 = [1]*(len(adj)-1)
for i in xrange(len(POW2)-1):
POW2[i+1] = (POW2[i]*2)%MOD
return [POW2[x-1] if x-1 >= 0 else 0 for x in result]
# Time: O(n + q)
# Space: O(n + q)
# dfs, Tarjan's Offline LCA Algorithm, combinatorics
| Solution |
python | django__django | tests/model_forms/models.py | {
"start": 14699,
"end": 14867
} | class ____(models.Model):
numbers = models.ManyToManyField(
Number,
through=NumbersToDice,
limit_choices_to=models.Q(value__gte=1),
)
| Dice |
python | pytorch__pytorch | torch/testing/_internal/common_methods_invocations.py | {
"start": 152520,
"end": 152801
} | class ____(_TestParamsMaxPoolBase):
def __init__(self) -> None:
super().__init__()
self.kwargs['kernel_size'] += [(3,)]
self.kwargs['stride'] += [(2,)]
self.kwargs['padding'] += [(1,)]
self.kwargs['dilation'] += [(1,)]
| _TestParamsMaxPool1d |
python | getsentry__sentry | src/sentry/search/events/builder/discover.py | {
"start": 6256,
"end": 6595
} | class ____(DiscoverQueryBuilder):
def resolve_query(
self,
query: str | None = None,
selected_columns: list[str] | None = None,
groupby_columns: list[str] | None = None,
equations: list[str] | None = None,
orderby: list[str] | str | None = None,
) -> None:
pass
| UnresolvedQuery |
python | scipy__scipy | scipy/stats/_resampling.py | {
"start": 98151,
"end": 101934
} | class ____(ResamplingMethod):
"""Configuration information for a permutation hypothesis test.
Instances of this class can be passed into the `method` parameter of some
hypothesis test functions to perform a permutation version of the
hypothesis tests.
Attributes
----------
n_resamples : int, optional
The number of resamples to perform. Default is 9999.
batch : int, optional
The number of resamples to process in each vectorized call to
the statistic. Batch sizes >>1 tend to be faster when the statistic
is vectorized, but memory usage scales linearly with the batch size.
Default is ``None``, which processes all resamples in a single batch.
rng : `numpy.random.Generator`, optional
Pseudorandom number generator used to perform resampling.
If `rng` is passed by keyword to the initializer or the `rng` attribute is used
directly, types other than `numpy.random.Generator` are passed to
`numpy.random.default_rng` to instantiate a ``Generator`` before use.
If `rng` is already a ``Generator`` instance, then the provided instance is
used. Specify `rng` for repeatable behavior.
If this argument is passed by position, if `random_state` is passed by keyword
into the initializer, or if the `random_state` attribute is used directly,
legacy behavior for `random_state` applies:
- If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
singleton is used.
- If `random_state` is an int, a new ``RandomState`` instance is used,
seeded with `random_state`.
- If `random_state` is already a ``Generator`` or ``RandomState`` instance then
that instance is used.
.. versionchanged:: 1.15.0
As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
transition from use of `numpy.random.RandomState` to
`numpy.random.Generator`, this attribute name was changed from
`random_state` to `rng`. For an interim period, both names will continue to
work, although only one may be specified at a time. After the interim
period, uses of `random_state` will emit warnings. The behavior of both
`random_state` and `rng` are outlined above, but only `rng` should be used
in new code.
"""
rng: object # type: ignore[misc]
_rng: object = field(init=False, repr=False, default=None) # type: ignore[assignment]
@property
def random_state(self):
# Uncomment in SciPy 1.17.0
# warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
return self._random_state
@random_state.setter
def random_state(self, val):
# Uncomment in SciPy 1.17.0
# warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
self._random_state = val
@property # type: ignore[no-redef]
def rng(self): # noqa: F811
return self._rng
def __init__(self, n_resamples=9999, batch=None, random_state=None, *, rng=None):
# Uncomment in SciPy 1.17.0
# warnings.warn(_rs_deprecation.replace('attribute', 'argument'),
# DeprecationWarning, stacklevel=2)
self._rng = rng
self._random_state = random_state
super().__init__(n_resamples=n_resamples, batch=batch)
def _asdict(self):
# `dataclasses.asdict` deepcopies; we don't want that.
d = dict(n_resamples=self.n_resamples, batch=self.batch)
if self.rng is not None:
d['rng'] = self.rng
if self.random_state is not None:
d['random_state'] = self.random_state
return d
@dataclass
| PermutationMethod |
python | numpy__numpy | numpy/f2py/tests/test_data.py | {
"start": 2124,
"end": 2523
} | class ____(util.F2PyTest):
sources = [util.getpath("tests", "src", "crackfortran", "data_multiplier.f")]
# For gh-23276
def test_data_stmts(self):
assert self.module.mycom.ivar1 == 3
assert self.module.mycom.ivar2 == 3
assert self.module.mycom.ivar3 == 2
assert self.module.mycom.ivar4 == 2
assert self.module.mycom.evar5 == 0
| TestDataMultiplierF77 |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hparams.py | {
"start": 24817,
"end": 25020
} | class ____(BoringModel):
def __init__(self, hparams):
super().__init__()
self._hparams = hparams # pretend BoringModel did not call self.save_hyperparameters()
| SuperClassPositionalArgs |
python | getsentry__sentry | tests/sentry/middleware/test_ratelimit_middleware.py | {
"start": 12809,
"end": 13190
} | class ____(Endpoint):
permission_classes = (AllowAny,)
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={"GET": {RateLimitCategory.IP: RateLimit(limit=2, window=100)}}
)
def inject_call(self):
return
def get(self, request):
self.inject_call()
return Response({"ok": True})
| RateLimitHeaderTestEndpoint |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.