當前位置: 首頁>>代碼示例>>Python>>正文


Python pandas.date_range方法代碼示例

本文整理匯總了Python中pandas.date_range方法的典型用法代碼示例。如果您正苦於以下問題:Python pandas.date_range方法的具體用法?Python pandas.date_range怎麽用?Python pandas.date_range使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pandas的用法示例。


在下文中一共展示了pandas.date_range方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _test_strip_unused_cols

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def _test_strip_unused_cols(self):
        data = pd.DataFrame({
            'name': ['tom', 'jack'],
            'age': [24, 56],
            'gender': ['male', 'male'],
            'address': ['cn', 'us']
        })
        data.index = pd.date_range(start='2017-01-01', periods=2)

        origin_cols = ['name', 'age', 'gender', 'address']
        unused_cols = ['address', 'gender']
        new_cols = ['name', 'age']

        self.assertEqual(list(data.columns).sort(), origin_cols.sort())

        bdu.Utils.strip_unused_cols(data, *unused_cols)

        self.assertEqual(list(data.columns).sort(), new_cols.sort()) 
開發者ID:pandalibin,項目名稱:backtrader-cn,代碼行數:20,代碼來源:test_datas_utils.py

示例2: monthly_mean_at_each_ind

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def monthly_mean_at_each_ind(monthly_means, sub_monthly_timeseries):
    """Copy monthly mean over each time index in that month.

    Parameters
    ----------
    monthly_means : xarray.DataArray
        array of monthly means
    sub_monthly_timeseries : xarray.DataArray
        array of a timeseries at sub-monthly time resolution

    Returns
    -------
    xarray.DataArray with eath monthly mean value from `monthly_means` repeated
    at each time within that month from `sub_monthly_timeseries`

    See Also
    --------
    monthly_mean_ts : Create timeseries of monthly mean values
    """
    time = monthly_means[TIME_STR]
    start = time.indexes[TIME_STR][0].replace(day=1, hour=0)
    end = time.indexes[TIME_STR][-1]
    new_indices = pd.date_range(start=start, end=end, freq='MS')
    arr_new = monthly_means.reindex(time=new_indices, method='backfill')
    return arr_new.reindex_like(sub_monthly_timeseries, method='pad') 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:27,代碼來源:times.py

示例3: test_parameter_array_indexed_json_load

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def test_parameter_array_indexed_json_load(simple_linear_model, tmpdir):
    """Test ArrayIndexedParameter can be loaded from json dict"""
    model = simple_linear_model
    # Daily time-step
    index = pd.date_range('2015-01-01', periods=365, freq='D', name='date')
    df = pd.DataFrame(np.arange(365), index=index, columns=['data'])
    df_path = tmpdir.join('df.csv')
    df.to_csv(str(df_path))

    data = {
        'type': 'arrayindexed',
        'url': str(df_path),
        'index_col': 'date',
        'parse_dates': True,
        'column': 'data',
    }

    p = load_parameter(model, data)
    model.setup()

    si = ScenarioIndex(0, np.array([0], dtype=np.int32))
    for v, ts in enumerate(model.timestepper):
        np.testing.assert_allclose(p.value(ts, si), v) 
開發者ID:pywr,項目名稱:pywr,代碼行數:25,代碼來源:test_parameters.py

示例4: test_parameter_df_embed_load

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def test_parameter_df_embed_load(model):

    # Daily time-step
    index = pd.date_range('2015-01-01', periods=365, freq='D', name='date')
    df = pd.DataFrame(np.random.rand(365), index=index, columns=['data'])

    # Save to JSON and load. This is the format we support loading as embedded data
    df_data = df.to_json(date_format="iso")
    # Removing the time information from the dataset for testing purposes
    df_data = df_data.replace('T00:00:00.000Z', '')
    df_data = json.loads(df_data)

    data = {
        'type': 'dataframe',
        'data': df_data,
        'parse_dates': True,
    }

    p = load_parameter(model, data)
    p.setup() 
開發者ID:pywr,項目名稱:pywr,代碼行數:22,代碼來源:test_parameters.py

示例5: _basic_init

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def _basic_init(self):
        self.name = "貨幣基金"
        self.rate = 0
        datel = list(
            pd.date_range(dt.datetime.strftime(self.start, "%Y-%m-%d"), yesterdaydash())
        )
        valuel = []
        for i, date in enumerate(datel):
            valuel.append((1 + self.interest) ** i)
        dfdict = {
            "date": datel,
            "netvalue": valuel,
            "totvalue": valuel,
            "comment": [0 for _ in datel],
        }
        df = pd.DataFrame(data=dfdict)
        self.price = df[df["date"].isin(opendate)] 
開發者ID:refraction-ray,項目名稱:xalpha,代碼行數:19,代碼來源:info.py

示例6: _get_peb_range

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def _get_peb_range(code, start, end):  # 盈利,淨資產,總市值
    """
    獲取指定指數一段時間內的 pe pb 值。

    :param code: 聚寬形式指數代碼。
    :param start:
    :param end:
    :return: pd.DataFrame
    """
    if len(code.split(".")) != 2:
        code = _inverse_convert_code(code)
    data = {"date": [], "pe": [], "pb": []}
    for d in pd.date_range(start=start, end=end, freq="W-FRI"):
        data["date"].append(d)
        logger.debug("compute pe pb on %s" % d)
        r = get_peb(code, date=d.strftime("%Y-%m-%d"))
        data["pe"].append(r["pe"])
        data["pb"].append(r["pb"])
    return pd.DataFrame(data) 
開發者ID:refraction-ray,項目名稱:xalpha,代碼行數:21,代碼來源:universal.py

示例7: get_fund_peb_range

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def get_fund_peb_range(code, start, end):
    """
    獲取一段時間的基金曆史估值,每周五為頻率

    :param code:
    :param start:
    :param end:
    :return:
    """
    if code.startswith("F"):
        code = code[1:]
    data = {"date": [], "pe": [], "pb": []}
    for d in pd.date_range(start=start, end=end, freq="W-FRI"):
        data["date"].append(d)
        r = get_fund_peb(code, date=d.strftime("%Y-%m-%d"))
        data["pe"].append(r["pe"])
        data["pb"].append(r["pb"])
    return pd.DataFrame(data) 
開發者ID:refraction-ray,項目名稱:xalpha,代碼行數:20,代碼來源:universal.py

示例8: test_review

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def test_review(capsys):
    st1 = xa.policy.buyandhold(gf, start="2018-08-10", end="2019-01-01")
    st2 = xa.policy.scheduled_tune(
        gf,
        totmoney=1000,
        times=pd.date_range("2018-01-01", "2019-01-01", freq="W-MON"),
        piece=[(0.1, 2), (0.15, 1)],
    )
    check = xa.review([st1, st2], ["Plan A", "Plan Z"])
    assert isinstance(check.content, str) == True
    conf = {}
    check.notification(conf)
    captured = capsys.readouterr()
    assert captured.out == "沒有提醒待發送\n"
    check.content = "a\nb"
    check.notification(conf)
    captured = capsys.readouterr()
    assert captured.out == "郵件發送失敗\n" 
開發者ID:refraction-ray,項目名稱:xalpha,代碼行數:20,代碼來源:test_realtime.py

示例9: _resample_pandas

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def _resample_pandas(signal, desired_length):
    # Convert to Time Series
    index = pd.date_range("20131212", freq="L", periods=len(signal))
    resampled_signal = pd.Series(signal, index=index)

    # Create resampling factor
    resampling_factor = str(np.round(1 / (desired_length / len(signal)), 6)) + "L"

    # Resample
    resampled_signal = resampled_signal.resample(resampling_factor).bfill().values

    # Sanitize
    resampled_signal = _resample_sanitize(resampled_signal, desired_length)

    return resampled_signal


# =============================================================================
# Internals
# ============================================================================= 
開發者ID:neuropsychology,項目名稱:NeuroKit,代碼行數:22,代碼來源:signal_resample.py

示例10: test_iterate_over_bounds_set_by_date_season_extra_time

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def test_iterate_over_bounds_set_by_date_season_extra_time(self):
        start = [pysat.datetime(2009, 1, 1, 1, 10),
                 pysat.datetime(2009, 2, 1, 1, 10)]
        stop = [pysat.datetime(2009, 1, 15, 1, 10),
                pysat.datetime(2009, 2, 15, 1, 10)]
        self.testInst.bounds = (start, stop)
        # filter
        start = self.testInst._filter_datetime_input(start)
        stop = self.testInst._filter_datetime_input(stop)
        # iterate
        dates = []
        for inst in self.testInst:
            dates.append(inst.date)
        out = pds.date_range(start[0], stop[0]).tolist()
        out.extend(pds.date_range(start[1], stop[1]).tolist())
        assert np.all(dates == out) 
開發者ID:pysat,項目名稱:pysat,代碼行數:18,代碼來源:test_instrument.py

示例11: test_iterate_over_bounds_set_by_fname_via_next

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def test_iterate_over_bounds_set_by_fname_via_next(self):
        start = '2009-01-01.nofile'
        stop = '2009-01-15.nofile'
        start_d = pysat.datetime(2009, 1, 1)
        stop_d = pysat.datetime(2009, 1, 15)
        self.testInst.bounds = (start, stop)
        dates = []
        loop_next = True
        while loop_next:
            try:
                self.testInst.next()
                dates.append(self.testInst.date)
            except StopIteration:
                loop_next = False
        out = pds.date_range(start_d, stop_d).tolist()
        assert np.all(dates == out) 
開發者ID:pysat,項目名稱:pysat,代碼行數:18,代碼來源:test_instrument.py

示例12: test_iterate_over_bounds_set_by_fname_via_prev

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def test_iterate_over_bounds_set_by_fname_via_prev(self):
        start = '2009-01-01.nofile'
        stop = '2009-01-15.nofile'
        start_d = pysat.datetime(2009, 1, 1)
        stop_d = pysat.datetime(2009, 1, 15)
        self.testInst.bounds = (start, stop)
        dates = []
        loop = True
        while loop:
            try:
                self.testInst.prev()
                dates.append(self.testInst.date)
            except StopIteration:
                loop = False
        out = pds.date_range(start_d, stop_d).tolist()
        assert np.all(dates == out[::-1]) 
開發者ID:pysat,項目名稱:pysat,代碼行數:18,代碼來源:test_instrument.py

示例13: zscore_ds_plot

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def zscore_ds_plot(training, target, future, corrected):
    labels = ["training", "future", "target", "corrected"]
    colors = {k: c for (k, c) in zip(labels, sns.color_palette("Set2", n_colors=4))}

    alpha = 0.5

    time_target = pd.date_range("1980-01-01", "1989-12-31", freq="D")
    time_training = time_target[~((time_target.month == 2) & (time_target.day == 29))]
    time_future = pd.date_range("1990-01-01", "1999-12-31", freq="D")
    time_future = time_future[~((time_future.month == 2) & (time_future.day == 29))]

    plt.figure(figsize=(8, 4))
    plt.plot(time_training, training.uas, label="training", alpha=alpha, c=colors["training"])
    plt.plot(time_target, target.uas, label="target", alpha=alpha, c=colors["target"])

    plt.plot(time_future, future.uas, label="future", alpha=alpha, c=colors["future"])
    plt.plot(time_future, corrected.uas, label="corrected", alpha=alpha, c=colors["corrected"])

    plt.xlabel("Time")
    plt.ylabel("Eastward Near-Surface Wind (m s-1)")
    plt.legend()

    return 
開發者ID:jhamman,項目名稱:scikit-downscale,代碼行數:25,代碼來源:utils.py

示例14: test_zscore_shift

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def test_zscore_shift():
    time = pd.date_range(start="2018-01-01", end="2020-01-01")
    data_X = np.zeros(len(time))
    data_y = np.ones(len(time))

    X = xr.DataArray(data_X, name="foo", dims=["index"], coords={"index": time}).to_dataframe()
    y = xr.DataArray(data_y, name="foo", dims=["index"], coords={"index": time}).to_dataframe()

    shift_expected = xr.DataArray(
        np.ones(364), name="foo", dims=["day"], coords={"day": np.arange(1, 365)}
    ).to_series()

    zscore = ZScoreRegressor()
    zscore.fit(X, y)

    np.testing.assert_allclose(zscore.shift_, shift_expected) 
開發者ID:jhamman,項目名稱:scikit-downscale,代碼行數:18,代碼來源:test_pointwise_models.py

示例15: test_should_return_data_when_date_range_spans_libraries

# 需要導入模塊: import pandas [as 別名]
# 或者: from pandas import date_range [as 別名]
def test_should_return_data_when_date_range_spans_libraries(toplevel_tickstore, arctic):
    arctic.initialize_library('FEED_2010.LEVEL1', tickstore.TICK_STORE_TYPE)
    arctic.initialize_library('FEED_2011.LEVEL1', tickstore.TICK_STORE_TYPE)
    tickstore_2010 = arctic['FEED_2010.LEVEL1']
    tickstore_2011 = arctic['FEED_2011.LEVEL1']
    toplevel_tickstore.add(DateRange(start=dt(2010, 1, 1), end=dt(2010, 12, 31, 23, 59, 59, 999000)), 'FEED_2010.LEVEL1')
    toplevel_tickstore.add(DateRange(start=dt(2011, 1, 1), end=dt(2011, 12, 31, 23, 59, 59, 999000)), 'FEED_2011.LEVEL1')
    dates = pd.date_range('20100101', periods=6, tz=mktz('Europe/London'))
    df_10 = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
    tickstore_2010.write('blah', df_10)
    dates = pd.date_range('20110101', periods=6, tz=mktz('Europe/London'))
    df_11 = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
    tickstore_2011.write('blah', df_11)
    res = toplevel_tickstore.read('blah', DateRange(start=dt(2010, 1, 2), end=dt(2011, 1, 4)), list('ABCD'))
    expected_df = pd.concat([df_10[1:], df_11[:4]])
    assert_frame_equal(expected_df, res.tz_convert(mktz('Europe/London'))) 
開發者ID:man-group,項目名稱:arctic,代碼行數:18,代碼來源:test_toplevel.py


注:本文中的pandas.date_range方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。