<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def ndiffs(x, alpha=0.05, test='kpss', max_d=2, **kwargs):
 """Estimate ARIMA differencing term, ``d``. Perform a test of stationarity for different levels of ``d`` to estimate the number of differences required to make a given time series stationary. Will select the maximum value of ``d`` for which the time series is judged stationary by the statistical test. Parameters x : array-like, shape=(n_samples, [n_features]) The array (time series) to difference. alpha : float, optional (default=0.05) Level of the test. This is the value above below which the P-value will be deemed significant. test : str, optional (default='kpss') Type of unit root test of stationarity to use in order to test the stationarity of the time-series. One of ('kpss', 'adf', 'pp') max_d : int, optional (default=2) Maximum number of non-seasonal differences allowed. Must be a positive integer. The estimated value of ``d`` will not exceed ``max_d``. Returns ------- d : int The estimated differencing term. This is the maximum value of ``d`` such that ``d <= max_d`` and the time series is judged stationary. If the time series is constant, will return 0. References .. [1] R's auto_arima ndiffs function: https://bit.ly/2Bu8CHN """

    if max_d <= 0:
        raise ValueError('max_d must be a positive integer')

    # get the test
    testfunc = get_callable(test, VALID_TESTS)(alpha, **kwargs).should_diff
    x = column_or_1d(check_array(x, ensure_2d=False,
                                 force_all_finite=True, dtype=DTYPE))

    # base case, if constant return 0
    d = 0
    if is_constant(x):
        return d

    # get initial diff
    pval, dodiff = testfunc(x)

    # if initially NaN, return 0
    if np.isnan(pval):
        return 0  # (d is zero, but this is more explicit to the reader)

    # Begin loop.
    while dodiff and d < max_d:
        d += 1

        # do differencing
        x = diff(x)
        if is_constant(x):
            return d

        # get new result
        pval, dodiff = testfunc(x)

        # if it's NaN now, take the last non-null one
        if np.isnan(pval):
            return d - 1

    # when d >= max_d
    return d