prompt
stringlengths
19
1.03M
completion
stringlengths
4
2.12k
api
stringlengths
8
90
from collections import OrderedDict import numpy as np import pytest from pandas._libs.tslib import Timestamp from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike import pandas as pd from pandas import Index, MultiIndex, date_range import pandas.util.testing as tm def test_constructor_singl...
pd.Categorical(['a', 'a', 'b', 'b', 'c', 'c'], ordered=True)
pandas.Categorical
""" Create DASS features for both the ground truth dataset. """ # region PREPARE WORKSPACE # Import dependencies import os import pandas as pd from joblib import load import sklearn # Get current working directory my_path = os.getcwd() # Load the ground truth datasets truth_depression = pd.read_csv(my_path + '/dat...
pd.DataFrame(y_depression)
pandas.DataFrame
#Importing the required packages from flask import Flask, render_template, request import os import pandas as pd from pandas import ExcelFile import matplotlib.pyplot as plt import numpy as np import seaborn as sns import warnings warnings.filterwarnings('ignore') from sklearn.preprocessing import StandardScaler, Label...
pd.read_excel('trainfile.xlsx')
pandas.read_excel
# -*- coding: utf-8 -*- """ Created on Sun Apr 25 17:40:53 2021 @author: ali_d """ #Pandas import pandas as pd import numpy as np #data numbers = [20,30,40,50] print("----") leters = ["a","b","c","d",40] pandas_pd = pd.Series(numbers) pandas_pd1 = pd.Series(leters) print(pandas_pd) print(type(pandas_pd)) print(p...
pd.concat([df_customersA,df_ordersB])
pandas.concat
import pandas as pd # setting display options for df
pd.set_option('display.max_rows', 500)
pandas.set_option
from datetime import datetime import pandas as pd from iexfinance.base import _IEXBase class APIReader(_IEXBase): @property def url(self): return "status" def fetch(self): return super(APIReader, self).fetch() def _convert_output(self, out): converted_date = datetime.fromti...
pd.DataFrame(out, index=[converted_date])
pandas.DataFrame
import numpy as np import pandas as pd from pandas import DataFrame, MultiIndex, Index, Series, isnull from pandas.compat import lrange from pandas.util.testing import assert_frame_equal, assert_series_equal from .common import MixIn class TestNth(MixIn): def test_first_last_nth(self): # tests for first...
assert_frame_equal(last, expected)
pandas.util.testing.assert_frame_equal
# pylint: disable-msg=E1101,W0612 from datetime import datetime, time, timedelta, date import sys import os import operator from distutils.version import LooseVersion import nose import numpy as np randn = np.random.randn from pandas import (Index, Series, TimeSeries, DataFrame, isnull, date_ran...
offsets.Hour()
pandas.tseries.offsets.Hour
#!/usr/bin/env python import click import os import codecs import json import pandas as pd from nlppln.utils import create_dirs, get_files @click.command() @click.argument('in_dir', type=click.Path(exists=True)) @click.option('--out_dir', '-o', default=os.getcwd(), type=click.Path()) @click.option('--name', '-n', de...
pd.concat(frames, ignore_index=True)
pandas.concat
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import random from sklearn.model_selection import ShuffleSplit from datetime import datetime from sklearn.preprocessing import FunctionTransformer import scipy.io as sio datasets = ['bugzilla', 'columba', 'jdt', 'mozilla', 'platform', 'postgres'] key ...
pd.to_datetime(self.data.index, format='%Y/%m/%d %H:%M')
pandas.to_datetime
# -*- coding: utf-8 -*- """ Created on Sat Apr 3 13:46:06 2021 @author: Sebastian """ import sys sys.path.append('..\\src') import unittest import common.globalcontainer as glob from dataobjects.stock import Stock import engines.scaffold import engines.analysis import pandas as pd import datetime import logging i...
pd.DataFrame(d, index=idx)
pandas.DataFrame
import pandas as pd import numpy as np #from sklearn.feature_selection import VarianceThreshold from sklearn.feature_selection import mutual_info_classif,chi2 from sklearn.feature_selection import SelectKBest, SelectPercentile from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.metrics i...
pd.Series(mse_values)
pandas.Series
""" lib/vector.py FIT3162 - Team 10 - Final Year Computer Science Project Copyright <NAME>, <NAME>, <NAME> 2019 Script containing the class to process vector files to get environment data """ from osgeo import ogr, osr, gdal from pathlib import Path import pandas as pd def conv_to_point(row): """ M...
pd.DataFrame()
pandas.DataFrame
# Test for evaluering af hvert forecast og sammenligning mellem forecast import pandas as pd import numpy as np from numpy.random import rand from numpy import ix_ from itertools import product import chart_studio.plotly as py import chart_studio import plotly.graph_objs as go import statsmodels.api as sm chart_studio...
pd.DataFrame(f_dm, columns=['f_dm'])
pandas.DataFrame
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # file_name : process_csv.py # time : 3/08/2019 14:10 # author : ruiyang # email : <EMAIL> import sys import numpy as np import pandas as pd from Bio.PDB.PDBParser import PDBParser def split_csv(path): """ :function: 将csv原文件分列,返回标准由DataFrame组成的csv,并...
pd.read_csv(file)
pandas.read_csv
import pandas as pd import numpy as np #***********************From dict of Series or dicts******************** #dictionary takes key:value dict = {"Name":pd.Series(["Nahid", "Rafi", "Meem"]), "Age":pd.Series([21,22,21]), "Weight":pd.Series([48,75,76]), "Height":pd.Series([5.3, 5.8, 5.6])} df =...
pd.DataFrame(dict)
pandas.DataFrame
# Global Summary # Infections / Deaths # Administered / Fully Vaccinated (%) # Daily Changes / Daily Changes Per 100K (%) # Infections, Deaths, Administered, Fully Vaccinated # Country + State # Line Graphs / Heatmap # pylint: disable=unused-variable # pylint: disable=anomalous-backslash-in-string import generic im...
pd.merge(dataset[idx][['Date','adm0_a3','Country/Region',stat_key]],candidates[['index',stat_key]],how='inner',left_on='adm0_a3',right_on=stat_key)
pandas.merge
import os import numpy as np import pandas as pd import pytest from featuretools import list_primitives from featuretools.primitives import ( Age, Count, Day, GreaterThan, Haversine, Last, Max, Mean, Min, Mode, Month, NumCharacters, NumUnique, NumWords, Perc...
pd.testing.assert_series_equal(expected_rolling_numeric, expected_rolling_offset)
pandas.testing.assert_series_equal
""" k-NN module. **Available routines:** - class ``KNN``: Builds K-Nearest Neighbours model using cross validation. Credits ------- :: Authors: - Diptesh - Madhu Date: Sep 25, 2021 """ # pylint: disable=invalid-name # pylint: disable=R0902,R0903,R0913,C0413 from typing import List, Dict, ...
pd.DataFrame(columns=self.x_var)
pandas.DataFrame
# Source # Portfolio optimization in finance is the technique of creating a portfolio of assets, for which your investment has the maximum return and minimum risk. # https://pythoninvest.com/long-read/practical-portfolio-optimisation # https://github.com/realmistic/PythonInvest-basic-fin-analysis ###################...
pd.set_option('display.max_colwidth', None)
pandas.set_option
import os import pandas as pd import numpy as np from scipy import stats from scipy.stats import norm, skewnorm from datetime import datetime, date, timedelta, timezone from dateutil import parser import pytz from sklearn.model_selection import ParameterGrid import matplotlib.pyplot as plt import seaborn as sns from...
pd.to_datetime(dates["date"])
pandas.to_datetime
import numpy as np from scipy.io import loadmat import os from pathlib import Path # from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt import seaborn as sns import pandas as pd # plotting parameters sns.set(font_scale=1.1) sns.set_context("talk") sns.set_palette(['#701f57', '#ad1759', '#e1...
pd.concat([res_data,res],axis=0)
pandas.concat
import numpy as np import pandas as pd import matplotlib.pyplot as plt def synthetic_example(mu=0, sigma = 1,N=400, c_boundary=False,y_ints=[5,6,7], SEED=4): np.random.seed(SEED) plt.figure(figsize=(9,9)) plt.title("Synthetic Data Example", fontsize=20) c1 = np.ones( (2,N)) + np.random.normal(0,sig...
pd.DataFrame(X, columns=['Feature1', 'Feature2', 'Target'])
pandas.DataFrame
import warnings warnings.filterwarnings('ignore', 'statsmodels.tsa.arima_model.ARMA', FutureWarning) warnings.filterwarnings('ignore', 'statsmodels.tsa.arima_model.ARIMA', FutureWarning) import numpy as np import pandas as pd from sklearn.metrics import mean_squared_erro...
pd.to_datetime(test.index)
pandas.to_datetime
import zlib import base64 import json import re import fnmatch import pendulum import requests from redis import Redis import pandas as pd from pymongo import MongoClient import pymongo.errors as merr from ..constants import YEAR from .orm import Competition def _val(v, s=None): if s is None: s = {"raw...
pd.DataFrame(l, columns=["player", "team", "g", "p"])
pandas.DataFrame
import numpy as np import pandas as pd from numba import njit import pytest import os from collections import namedtuple from itertools import product, combinations from vectorbt import settings from vectorbt.utils import checks, config, decorators, math, array, random, enum, data, params from tests.utils import hash...
pd.Series([1, 2, 3])
pandas.Series
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/loading.ipynb (unless otherwise specified). __all__ = ['DATA_PATH', 'N_TRAIN', 'N_TEST', 'get_csvs', 'CSV_NAMES_MAP', 'get_meter_data', 'get_nan_stats', 'show_nans', 'test_meter_train_and_test_set', 'get_building_data', 'test_building', 'get_weather_data', ...
pd.read_csv(path)
pandas.read_csv
""" Define the SeriesGroupBy and DataFrameGroupBy classes that hold the groupby interfaces (and some implementations). These are user facing as the result of the ``df.groupby(...)`` operations, which here returns a DataFrameGroupBy object. """ from __future__ import annotations from collections import abc from functo...
doc(Series.nlargest)
pandas.util._decorators.doc
# -*- coding: utf-8 -*- """ Created on Mon Feb 22 08:32:48 2016 @module: choice_tools.py @name: Helpful Tools for Choice Model Estimation @author: <NAME> @summary: Contains functions that help prepare one's data for choice model estimation or helps speed the estimation process (the 'mappings')...
pd.read_csv(data)
pandas.read_csv
from abc import abstractmethod from collections import OrderedDict import os import pickle import re from typing import Tuple, Union import pandas as pd import numpy as np import gym from gridworld.log import logger from gridworld import ComponentEnv from gridworld.utils import to_scaled, to_raw, maybe_rescale_box_s...
pd.DataFrame(data, columns=["temp_lb", "temp_ub"], index=self.df.index)
pandas.DataFrame
""" Tasks ------- Search and transform jsonable structures, specifically to make it 'easy' to make tabular/csv output for other consumers. Example ~~~~~~~~~~~~~ *give me a list of all the fields called 'id' in this stupid, gnarly thing* >>> Q('id',gnarly_data) ['id1','id2','id3'] Observations: --...
u('beta')
pandas.compat.u
import numpy as np import pandas as pd import math import matplotlib.pyplot as plt import yfinance as yf from pandas_datareader import data as web import datetime as dt from empyrical import* import quantstats as qs from darts.models import* from darts import TimeSeries from darts.utils.missing_values import...
pd.Series()
pandas.Series
from itertools import product import pandas as pd from sklearn.datasets import load_boston from vivid.core import AbstractFeature from vivid.out_of_fold import EnsembleFeature from vivid.out_of_fold.boosting import XGBoostRegressorOutOfFold, OptunaXGBRegressionOutOfFold, LGBMRegressorOutOfFold from vivid.out_of_fold....
pd.DataFrame()
pandas.DataFrame
import datetime import hashlib import os import time from warnings import ( catch_warnings, simplefilter, ) import numpy as np import pytest import pandas as pd from pandas import ( DataFrame, DatetimeIndex, Index, MultiIndex, Series, Timestamp, concat, date_range, timedelt...
read_hdf(store, "df")
pandas.io.pytables.read_hdf
""" Functions for converting object to other types """ import numpy as np import pandas as pd from pandas.core.common import (_possibly_cast_to_datetime, is_object_dtype, isnull) import pandas.lib as lib # TODO: Remove in 0.18 or 2017, which ever is sooner def _possibly_convert_objec...
pd.to_datetime(values, errors='coerce', box=False)
pandas.to_datetime
from datetime import datetime import numpy as np import pytest import pandas as pd from pandas import ( Categorical, CategoricalIndex, DataFrame, Index, MultiIndex, Series, qcut, ) import pandas._testing as tm def cartesian_product_for_groupers(result, args, names, fill...
DataFrame({"cat": cat, "ser": ser})
pandas.DataFrame
#!/usr/bin/env python # coding: utf-8 # In[1]: import time import warnings warnings.filterwarnings('ignore') import pandas as pd, numpy as np import math, json, gc, random, os, sys import torch import logging import torch.nn as nn import torch.optim as optim import torch.utils.data as data from sklearn.model_selecti...
pd.read_csv('/kaggle/input/stanford-covid-vaccine/sample_submission.csv')
pandas.read_csv
import copy import io import json import os import string from collections import OrderedDict from datetime import datetime from unittest import TestCase import numpy as np import pandas as pd import pytest import pytz from hypothesis import ( given, settings, ) from hypothesis.strategies import ( dateti...
pd.read_csv(fp.name, dtype=dtypes)
pandas.read_csv
""" Copyright 2022 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distrib...
pd.DataFrame(A)
pandas.DataFrame
# -*- coding: utf-8 -*- import pytest import numpy as np import pandas as pd import pandas.util.testing as tm import pandas.compat as compat ############################################################### # Index / Series common tests which may trigger dtype coercions ###############################################...
pd.Series(self.rep[to_key], index=index, name='yyy')
pandas.Series
import pandas as pd from pandas import DataFrame from sklearn.ensemble import RandomForestRegressor from sklearn.feature_selection import f_regression from sklearn.linear_model import LinearRegression from sklearn.preprocessing import StandardScaler from sklearn.svm import SVR, LinearSVR from metalfi.src.data.dataset ...
DataFrame(data=data[dmf], columns=dmf)
pandas.DataFrame
# -*- coding: utf-8 -*- import numpy as np import pytest from numpy.random import RandomState from numpy import nan from datetime import datetime from itertools import permutations from pandas import (Series, Categorical, CategoricalIndex, Timestamp, DatetimeIndex, Index, IntervalIndex) import pan...
tm.assert_numpy_array_equal(result, expected)
pandas.util.testing.assert_numpy_array_equal
# coding: utf-8 # # Generates the table of the ontological issues. # # ### Note this code assumes that you've already computed psx -- the predicted probabilities for all examples in the training set using four-fold cross-validation. If you have no done that you will need to use `imagenet_train_crossval.py` to do thi...
pd.DataFrame(edges)
pandas.DataFrame
""" ======================= Visualizing the Results ======================= Auto-Pytorch uses SMAC to fit individual machine learning algorithms and then ensembles them together using `Ensemble Selection <https://www.cs.cornell.edu/~caruana/ctp/ct.papers/caruana.icml04.icdm06long.pdf>`_. The following examples shows ...
pd.DataFrame(estimator.ensemble_performance_history)
pandas.DataFrame
from json import load from matplotlib.pyplot import title from database.database import DbClient from discord import Embed import pandas as pd from util.data import load_data class Analytics: def __init__(self, server_id: str, db): self.server_id = server_id self.db = db @staticmethod de...
pd.value_counts(df["hours"])
pandas.value_counts
# coding: utf-8 # # Val Strategy # > A good validation strategy is key to winning a competition # > # > — @CPMP # # The val strategy should be trusted in and utilized for all feature engineering tasks and for hyper parameter tuning. # # Generally, the best val strategy will somehow mimic the train-test (submission...
pd.read_csv('input/test_identity.csv.zip')
pandas.read_csv
"""Interface for running a registry of models on a registry of validations.""" from typing import Optional, Tuple from kotsu.typing import Model, Results, Validation import functools import logging import os import time import pandas as pd from kotsu import store from kotsu.registration import ModelRegistry, ModelSp...
pd.DataFrame.from_records(results_list)
pandas.DataFrame.from_records
import importlib from hydroDL.master import basins from hydroDL.app import waterQuality from hydroDL import kPath, utils from hydroDL.model import trainTS from hydroDL.data import gageII, usgs from hydroDL.post import axplot, figplot from sklearn.linear_model import LinearRegression from hydroDL.data import usgs, gageI...
pd.datetime(1979, 1, 1)
pandas.datetime
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
assert_frame_equal(df, rdf)
pandas.util.testing.assert_frame_equal
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from stockstats import StockDataFrame import warnings import traceback warnings.filterwarnings('ignore') import argparse import re import sys, os sys.path.append(os.getcwd()) import os import requests from req...
pd.to_timedelta(364 + i, unit='d')
pandas.to_timedelta
import sys sys.path.append("../ern/") sys.path.append("../dies/") import copy import torch import numpy as np import pandas as pd from dies.utils import listify from sklearn.metrics import mean_squared_error as mse from torch.utils.data.dataloader import DataLoader from fastai.basic_data import DataBunch from fastai.b...
pd.DataFrame({"RMSE": res_rmses, "ParkId": park_ids})
pandas.DataFrame
# -*- coding: utf-8 -*- """ :Author: <NAME> :Date: 2018. 6. 19. """ import numpy as np import pandas as pd from pandas.io.excel import ExcelFile from preprocess.core.columns import * KIND = 'Kind' SYMBOL = 'Symbol' NAME = 'name' ITEM_NAME = 'Item Name ' ITEM = 'Item' FREQUENCY = 'Frequency' SYMBOL_NAME = 'Symbol Nam...
pd.concat([melted_benchmarks, melted_risk_free])
pandas.concat
import os import numpy as np import pandas as pd import consts first_period='01-2017' last_period='02-2020' # Coleta a substring referente ao ano e a transforma no tipo int first_year = int(first_period[3:]) # Coleta a substring referente ao ano e a transforma no tipo int last_year = int(last_period[3:]) # Coleta...
pd.merge(df, df_mes[['CNES', f'{ano}-{mes}']], how='outer', left_on='CNES', right_on='CNES')
pandas.merge
import pandas as pd import numpy as np import os path='D:\sufe\A' files=os.listdir(path) train_data=pd.read_csv('D:\sufe\A\data_train_changed.csv') data1=pd.read_csv('D:\sufe\A\contest_ext_crd_cd_ln.tsv',sep='\t') data2=pd.read_csv('D:\sufe\A\contest_ext_crd_cd_ln_spl.tsv',sep='\t') p=pd.merge(train_data,data1,on='REP...
pd.merge(p,data2,on='REPORT_ID',how='left')
pandas.merge
#%% import pandas as pd import json import os class Preprocessing: optional = object() """ Helper class for Preprocessing Data """ @staticmethod def extract_str_dict_df(df, column): """ To parse data that have rows that look like: "{"/m/01jfsb": "Thriller", "/m/06n90...
pd.concat(df_1[co_to_keep], df_2[co_to_keep])
pandas.concat
import Orange import pandas as pd import numpy as np import matplotlib.pyplot as plt from parameters import output_dir, rank_dir, input_dir from classifiers import classifiers_list from datasets import dataset_biclass, dataset_multiclass # geometry order = ['area', 'volume', 'area_volume_ratio', ...
pd.concat([df_B1, df_B2, df_GEO, df_SMOTE, df_SMOTEsvm, df_original, df_dto])
pandas.concat
import unittest import numpy as np import pandas as pd from haychecker.chc.metrics import constraint class TestConstraint(unittest.TestCase): def test_empty(self): df = pd.DataFrame() df["c1"] = [] df["c2"] = [] condition1 = {"column": "c1", "operator": "lt", "value": 1000} ...
pd.DataFrame()
pandas.DataFrame
import os from multiprocessing import Pool, cpu_count from itertools import repeat import pandas as pd from solvers.solvers import SOLVER_MAP from problem_classes.random_qp import RandomQPExample from problem_classes.eq_qp import EqQPExample from problem_classes.portfolio import PortfolioExample from problem_classes.l...
pd.concat(n_results)
pandas.concat
# -*- coding: utf-8 -*- from datetime import timedelta, time import numpy as np from pandas import (DatetimeIndex, Float64Index, Index, Int64Index, NaT, Period, PeriodIndex, Series, Timedelta, TimedeltaIndex, date_range, period_range, timedelta_range, notnu...
pd.TimedeltaIndex(['1 day', '2 day', '3 day'])
pandas.TimedeltaIndex
# pylint: disable=redefined-outer-name import itertools import time import pytest import math import flask import pandas as pd import numpy as np import json import psutil # noqa # pylint: disable=unused-import from bentoml.utils.dataframe_util import _csv_split, _guess_orient from bentoml.adapters import DataframeI...
pd.concat(dfs)
pandas.concat
import pandas as pd import numpy as np from os.path import join import sys sys.path.append('../utils') import preproc_utils class CsvLoaderMain: def __init__(self, data_path): self.data_path = data_path def LoadCsv2HDF5(self, tbl_name, write_path = './'): if tbl_name in ['monva...
pd.to_datetime(chunk.Datetime)
pandas.to_datetime
""" Nothing but variate many functions """ # from config import * import matplotlib.pyplot as plt from pathlib import Path import numpy.ma as ma import math import pandas as pd import skgstat as skg import numpy as np import glob import geopandas import os from skimage.graph import route_through_array from sklearn.mode...
pd.DataFrame()
pandas.DataFrame
# Copyright 2019 <NAME> GmbH # Copyright 2020-2021 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
pd.DataFrame.from_dict(self._timers)
pandas.DataFrame.from_dict
# -*- coding: utf-8 -*- import re,pandas as pd,numpy as np from pandas import DataFrame import os pathDir=os.listdir(r'C:\Users\aklasim\Desktop\Py6.11 Pdf\t1') pt=(r'C:\Users\aklasim\Desktop\Py6.11 Pdf\t1') cols=['工单编号','上级工单编号','项目编号','工单描述','上级工单描述','施工单位','合同号','计划服务费','开工日期','完工日期','作业类型','通知单创建','通知单批准','计划','...
eries(cert)
pandas.Series
from datetime import datetime from sqlite3 import connect from typing import Dict, NamedTuple, Optional, Mapping import json from black import line_to_string import kfp.dsl as dsl import kfp from kfp.components import func_to_container_op, InputPath, OutputPath import kfp.compiler as compiler from kfp.dsl.types import...
pd.read_sql_query(f"select * from drug_classification_staging", con=engine)
pandas.read_sql_query
"""Process the USCRN station table ftp://ftp.ncdc.noaa.gov/pub/data/uscrn/products/stations.tsv """ import pandas as pd from pyiem.util import get_dbconn def main(): """Go""" pgconn = get_dbconn('mesosite', user='mesonet') cursor = pgconn.cursor() df = pd.read_csv('stations.tsv', sep=r'\t', engine='...
pd.isnull(station)
pandas.isnull
# -*- coding: utf-8 -*- from datetime import datetime import pandas as pd import numpy as np from findy.database.schema.fundamental.finance import BalanceSheet from findy.database.plugins.eastmoney.common import to_report_period_type from findy.database.plugins.eastmoney.finance.base_china_stock_finance_recorder impo...
pd.to_datetime(df['timestamp'])
pandas.to_datetime
from collections import OrderedDict from datetime import timedelta import numpy as np import pytest from pandas.core.dtypes.dtypes import DatetimeTZDtype import pandas as pd from pandas import DataFrame, Series, Timestamp, date_range, option_context import pandas._testing as tm def _check_cast(df, v): """ ...
date_range("20130101", periods=3)
pandas.date_range
import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.ticker import FuncFormatter from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() params = { "axes.titlesize": 14, "axes.labelsize": 14, "font.size": 14, "xtick.labelsize": 14, ...
pd.read_csv(outfile)
pandas.read_csv
# Imports import pandas as pd from edbo.utils import Data # import pdb from sklearn.manifold import TSNE import matplotlib.pyplot as plt import matplotlib from sklearn.cluster import KMeans import numpy as np from sklearn import metrics from edbo.bro import BO_express from gpytorch.priors import GammaPrior import rand...
pd.concat([full_yield_df, value])
pandas.concat
import requests import json import os from dotenv import load_dotenv import pandas as pd import pickle import time # Getting the api key from .env load_dotenv() API_KEY = os.getenv("RIOT_API_KEY") # Getting the data from a json file to a string while True: try: matchesID = pickle.load(open("matchesId.p", ...
pd.DataFrame()
pandas.DataFrame
from datetime import datetime, timedelta import unittest from pandas.core.datetools import ( bday, BDay, BQuarterEnd, BMonthEnd, BYearEnd, MonthEnd, DateOffset, Week, YearBegin, YearEnd, Hour, Minute, Second, format, ole2datetime, to_datetime, normalize_date, getOffset, getOffsetName, inferTimeR...
Week(weekday=0)
pandas.core.datetools.Week
# -*- coding: utf-8 -*- import logging from dotenv import find_dotenv, load_dotenv import pickle import os import numpy as np import pandas as pd from goactiwe import GoActiwe from goactiwe.steps import remove_drops import dask.dataframe as dd from fastparquet import write, ParquetFile def fill_df_with_datetime_vars...
pd.TimeGrouper('15min')
pandas.TimeGrouper
import os from nose.tools import * import unittest import pandas as pd from py_entitymatching.utils.generic_helper import get_install_path import py_entitymatching.catalog.catalog_manager as cm import py_entitymatching.utils.catalog_helper as ch from py_entitymatching.io.parsers import read_csv_metadata datasets_path...
pd.DataFrame()
pandas.DataFrame
#!/usr/bin/env python # coding: utf-8 # # Vatsal's Code # This notebook shows you how to build a model for predicting degradation at various locations along RNA sequence. # * We will first pre-process and tokenize the sequence, secondary structure and loop type. # * Then, we will use all the information to train a ...
pd.concat(oof_preds_all)
pandas.concat
import biom import skbio import numpy as np import pandas as pd from deicode.matrix_completion import MatrixCompletion from deicode.preprocessing import rclr from deicode._rpca_defaults import (DEFAULT_RANK, DEFAULT_MSC, DEFAULT_MFC, DEFAULT_ITERATIONS) from scipy.linalg import svd ...
pd.Series(s, index=rename_cols)
pandas.Series
# 指标计算器 import pandas as pd import talib def talib_OBV(DataFrame): res = talib.OBV(DataFrame.close.values, DataFrame.volume.values) return pd.DataFrame({'OBV': res}, index=DataFrame.index) def talib_DEMA(DataFrame, N=30): res = talib.DEMA(DataFrame.close.values, timeperiod=N) return pd.DataFrame({'...
pd.DataFrame({'TRANGE': res}, index=DataFrame.index)
pandas.DataFrame
# -*- coding: utf-8 -*- import re import warnings from datetime import timedelta from itertools import product import pytest import numpy as np import pandas as pd from pandas import (CategoricalIndex, DataFrame, Index, MultiIndex, compat, date_range, period_range) from pandas.compat import PY...
lrange(4)
pandas.compat.lrange
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt import os from RLC.real_chess import agent, environment, learn, tree import chess from chess.pgn import Game opponent = agent.GreedyAgent() env = environment.Board(opponent, FEN...
pd.DataFrame(learner.reward_trace)
pandas.DataFrame
import os import numpy as np import pandas as pd from time import time from lr.models.transformers.RobertaWrapper import RobertaWrapper from lr.models.transformers.processor import clean_df from lr.training.util import filter_df_by_label from tqdm import tqdm import glob import argparse import logging # Help Function...
pd.DataFrame(dict_)
pandas.DataFrame
import numpy as np import pandas as pd class NB: def __init__(self): self.target = "" # name of the label self.columns = pd.Index([]) # name of the features self.num_cols = pd.Index([]) # name of numerical features self.cat_cols = pd.Index([]) # name of categorical features ...
pd.Series(_ll)
pandas.Series
import pandas as pd import numpy as np import category_encoders as ce from sklearn.preprocessing import normalize from sklearn.utils import resample from imblearn.over_sampling import SMOTE, RandomOverSampler from imblearn.under_sampling import NearMiss from scipy.stats import skew, kurtosis from src.utils.common.commo...
pd.concat([df_minority_upsampled, df_majority])
pandas.concat
""" Code for "How Is Earnings News Transmitted to Stock Prices?" by <NAME> and <NAME>. Python 2 The main function takes the TAS (Time and Sales) file for one exchange on one month and extracts only the trades from daily files, creating trade files. """ from os import listdir import os import pandas as p...
pd.DataFrame(ls, columns=['Filename'])
pandas.DataFrame
# Regular Imports from geojson.feature import * from src.h3_utils import * import geopandas as gpd import pandas as pd def generate_hourly_charges(charges): # Create a unique identifier charges['ID'] = [i for i in range(0, charges.shape[0])] # Create dataframe by minutes in this datetime range start =...
pd.datetime(year=x.year, month=x.month, day=x.day, hour=x.hour)
pandas.datetime
import pandas as pd class PassHash: def __init__(self): # Combinations of header labels self.base = ['Rk', 'Date', 'G#', 'Age', 'Tm', 'Home', 'Opp', 'Result', 'GS'] self.passing = ['pass_cmp', 'pass_att', 'Cmp%', 'pass_yds', 'pass_td', 'Int', 'Rate', 'Sk', 'Sk-Yds', ...
pd.DataFrame(columns=self.punting + self.scoring2p)
pandas.DataFrame
import pandas as pd class FeatureExtractor(): def __init__(self): pass def fit(self, X_df, y): pass def transform(self, X_df): X_df.index = range(len(X_df)) X_df_new = pd.concat( [X_df.get(['instant_t', 'windspeed', 'latitude', 'longitude', ...
pd.get_dummies(X_df.nature, prefix='nature', drop_first=True)
pandas.get_dummies
# ___________________________________________________________________________ # # Prescient # Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. # This software is ...
pd.DataFrame({'datetime':dt, 'forecasts':forecast[site], 'actuals':actual[site]})
pandas.DataFrame
# coding: utf-8 # --- # # _You are currently looking at **version 1.5** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._ # # ...
pd.merge(energy,GDP,on='Country')
pandas.merge
import io import numpy as np import pytest from pandas.compat._optional import VERSIONS from pandas import ( DataFrame, date_range, read_csv, read_excel, read_feather, read_json, read_parquet, read_pickle, read_stata, read_table, ) import pandas._testing as tm from pandas.util...
read_csv("s3://pandas-test/tips.csv.gz", storage_options=s3so)
pandas.read_csv
#! /usr/bin/env python from datetime import datetime, timedelta import hb_config import mwapi from mwapi.errors import APIError import requests from requests_oauthlib import OAuth1 import pandas as pd import json #TODO #encapsulate what's in MAIN #pull hard-coded vals to hb_config #docstrings #rmv my dumb API functio...
pd.DataFrame(mems)
pandas.DataFrame
""" this is compilation of functions to analyse BEAM-related data for NYC simulation """ from urllib.error import HTTPError import matplotlib.pyplot as plt import numpy as np import time import datetime as dt import pandas as pd from shapely.geometry import Point from shapely.geometry.polygon import Polygon from io ...
pd.concat([run, pc], axis=0)
pandas.concat
# encoding: utf-8 # (c) 2017-2021 Open Risk (https://www.openriskmanagement.com) # # TransitionMatrix is licensed under the Apache 2.0 license a copy of which is included # in the source distribution of TransitionMatrix. This is notwithstanding any licenses of # third-party software included in this distribution. You ...
pd.read_csv('../../datasets/rating_data_raw.csv')
pandas.read_csv
from flask import Flask, render_template, request, redirect, url_for, session import pandas as pd import pymysql import os import io #from werkzeug.utils import secure_filename from pulp import * import numpy as np import pymysql import pymysql.cursors from pandas.io import sql #from sqlalchemy import create...
pd.DataFrame(csdata)
pandas.DataFrame
# Copyright 2021 The Funnel Rocket Maintainers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
Series(data=str_user_ids)
pandas.Series
import matplotlib.pyplot as plt import matplotlib.pylab as pylab import os from PIL import Image import numpy as np # import torch import json import sys from tqdm import tqdm, trange from pycocotools.coco import COCO import skimage.io as io import pylab from convert_fat_coco import * from mpl_toolkits.axes_grid1 impo...
pd.concat(li, axis=0, ignore_index=False)
pandas.concat
import numpy as np import pandas as pd import os.path from glob import glob import scipy.stats as ss from sklearn.metrics import r2_score, roc_auc_score, average_precision_score COLORS = { 'orange': '#f0593e', 'dark_red': '#7c2712', 'red': '#ed1d25', 'yellow': '#ed9f22', 'light_green': '#67bec5...
pd.DataFrame(columns=['tf', 'comp_group', 'p_score'])
pandas.DataFrame
import pandas as pd from sklearn.base import BaseEstimator import numpy as np import warnings class TopCause(BaseEstimator): '''TopCause finds the single largest action to improve a performance metric. Parameters ---------- max_p : float maximum allowed probability of error (default: 0.05) ...
pd.DataFrame(results)
pandas.DataFrame
import pytest import os from mapping import util from pandas.util.testing import assert_frame_equal, assert_series_equal import pandas as pd from pandas import Timestamp as TS import numpy as np @pytest.fixture def price_files(): cdir = os.path.dirname(__file__) path = os.path.join(cdir, 'data/') files = ...
TS('2015-01-03')
pandas.Timestamp
from __future__ import absolute_import, division, print_function import datetime import pandas as pd from config import * def _drop_in_time_slice(m2m, m2b, m5cb, time_slice, to_drop): """Drops certain members from data structures, only in a given time slice. This can be useful for removing people who weren't...
pd.Timestamp(period1_end, tz=time_zone)
pandas.Timestamp
""" Info about all of noaa data can be found at: http://www.ndbc.noaa.gov/docs/ndbc_web_data_guide.pdf What all the values mean: http://www.ndbc.noaa.gov/measdes.shtml WDIR Wind direction (degrees clockwise from true N). WSPD Wind speed (m/s) averaged over an eight-minute period. GST P...
pd.DataFrame()
pandas.DataFrame