prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
Index,
Series,
concat,
date_range,
)
import pandas._testing as tm
class TestEmptyConcat:
def test_handle_empty_objects(self, sort):
df = DataFrame(np.random.randn(10, 4), columns=list("abcd"))
... | concat([s1, s2], axis=0) | pandas.concat |
import sys
import pandas as pd
from datetime import timedelta, datetime, date, time
import API
# if __name__ == '__main__':
# main(sys.argv[1])
# Global constants
DATA_TYPE = 'Adj Close'
DAYS_LOOK_BACK = 5110 # 12*252 years expresed in days
HOW_RECENT = 0
MAIN_FOLDER = 'C:/Users/champ/Python_proj/base_financial... | pd.read_csv(securities_file_location, sep=';') | pandas.read_csv |
import gc
import logging
import traceback
from collections import defaultdict
from datetime import datetime, timedelta
from multiprocessing import Process, Queue
import numpy as np
import pandas as pd
import xarray as xr
from typhon.geodesy import great_circle_distance
from typhon.geographical import GeoIndex
from ty... | pd.Grouper(freq=bin_duration) | pandas.Grouper |
#!/bin/env python3
import pandas as pd
import numpy as np
import glob
import re
from tqdm.notebook import tqdm
from pathlib import Path
def read_conll(input_file, label_nr=3):
"""Reads a conllu file."""
ids = []
texts = []
tags = []
#
text = []
tag = []
idx = None
for line in open... | pd.read_csv(path) | pandas.read_csv |
"""
Timing and Telemetry Data - :mod:`fastf1.core`
==============================================
The Fast-F1 core is a collection of functions and data objects for accessing
and analyzing F1 timing and telemetry data.
Data Objects
------------
All data is provided through the following data objects:
.. autosum... | pd.Series(st.index) | pandas.Series |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 08:59:17 2019
@author: <NAME>
@contact: <EMAIL>
"""
import pandas as pd
def relative_strong_signal(data,threshold,val_threshold):
""" This function compute date based sectional
relative strong/weak indicator given dataframe with
structur... | pd.DataFrame() | pandas.DataFrame |
import re
from unittest.mock import Mock, patch
import numpy as np
import pandas as pd
import pytest
from rdt.transformers import (
CategoricalTransformer, LabelEncodingTransformer, OneHotEncodingTransformer)
RE_SSN = re.compile(r'\d\d\d-\d\d-\d\d\d\d')
class TestCategoricalTransformer:
def test___init__(... | pd.Series(['a', 'b', 'c']) | pandas.Series |
import os
import pathlib
import sys
import febrl_data_transform as transform
import pandas as pd
OUTPUT_DATA_DIR = pathlib.Path(__file__).parent / "holdout"
ORIGINALS_DATA_DIR = pathlib.Path(__file__).parent / "holdout" / "originals"
def main():
# Read in FEBRL data with dupes and separate into A/B/true links.... | pd.concat(true_links) | pandas.concat |
import os
from os.path import join
import collections
import numpy as np
import pandas as pd
from itertools import chain
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer, MissingIndicator
from sklearn.pipeline import make_union, Pipeline
from sklearn.ensemble import RandomF... | pd.DataFrame(X_split, columns=['20016-2.0']) | pandas.DataFrame |
'''Runs program'''
import pandas as pd
import matplotlib.pyplot as plt
import create_data as cd
def prompt():
'''Prompts the user what information they want to see.
:returns: page URL
'''
page_list = {
"Marine Fish": "https://www.liveaquaria.com/divers-den/category/3/marine-fish",
"Fr... | pd.DataFrame(data, columns=['Name', 'Price']) | pandas.DataFrame |
import operator
import re
import warnings
import numpy as np
import pytest
from pandas._libs.sparse import IntIndex
import pandas.util._test_decorators as td
import pandas as pd
from pandas import isna
from pandas.core.sparse.api import SparseArray, SparseDtype, SparseSeries
import pandas.util.testing as tm
from pan... | SparseDtype(np.bool) | pandas.core.sparse.api.SparseDtype |
import sys
import pandas as pd
import pandas_ta as ta
import investpy as iv
import numpy as np
from datetime import date, datetime
from calendar import monthrange
def find_days_in_month():
today = date.today()
first = today.replace(day=1)
last = today.replace(day=monthrange(today.year, today.month)[1])
... | pd.to_datetime(df['Date']) | pandas.to_datetime |
# coding=utf-8
# pylint: disable-msg=E1101,W0612
""" test get/set & misc """
import pytest
from datetime import timedelta
import numpy as np
import pandas as pd
from pandas.core.dtypes.common import is_scalar
from pandas import (Series, DataFrame, MultiIndex,
Timestamp, Timedelta, Categorical)
... | pd.Timestamp('2016-01-01 00:00', tz=tz) | pandas.Timestamp |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 12 16:49:09 2021
@author: Administrator
"""
#this website is called macrotrends
#this script is designed to scrape its financial statements
#yahoo finance only contains the recent 5 year
#macrotrends can trace back to 2005 if applicable
import re
import jso... | pd.DataFrame() | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 23 08:06:31 2021
@author: bcamc
"""
#%% Import Packages
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition, inset_axes
from matplotlib.lines import Line2D
import pandas as pd
import numpy ... | pd.read_csv(write_dir[:-14]+'RFR_kde_3mon.csv') | pandas.read_csv |
import numpy as np
import pandas as pd
from sklearn.model_selection import ParameterGrid
from itertools import product
from explore.ContCat import ContCat
def data_iter():
np.random.seed(2342)
n = 30
# 2 classes
cont = np.random.normal(size=n)
cat = np.random.choice([0, 1], size=n).astype(str)... | pd.Series(cont) | pandas.Series |
#Creates temperature mean from Tmin and Tmax average
import sys
import numpy as np
import pandas as pd
import rasterio
from osgeo import gdal
from affine import Affine
from pyproj import Transformer
#NAMING SETTINGS & OUTPUT FLAGS----------------------------------------------#
MASTER_DIR = r'/home/hawaii_climate_prod... | pd.to_datetime(date_range[0],format='%Y%m%d') | pandas.to_datetime |
__author__ = "<NAME>"
__version__ = ".2"
import pandas as pd
import numpy as np
from datetime import datetime
from dateutil.relativedelta import relativedelta
class MetricsFunctions:
def average_los_in_es_shelter(self, entries_df, cleaned=False):
"""
Used For:
:param entr... | pd.to_datetime(exits["Entry Exit Exit Date"]) | pandas.to_datetime |
from builtins import print
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from scipy.io import arff
import sci... | pd.DataFrame(data[0]) | pandas.DataFrame |
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-3-Clause-Clear
# Copyright (c) 2019, The Numerical Algorithms Group, Ltd. All rights reserved.
"""Shared routines for different Metric Sets
"""
from warnings import warn
import numpy
import pandas
from ..trace import Trace
from ..traceset import TraceSet
from ..... | pandas.Series(data=[metadata.tag], index=[idxkey]) | pandas.Series |
"""
Unit test of Inverse Transform
"""
import unittest
import pandas as pd
import numpy as np
import category_encoders as ce
import catboost as cb
import sklearn
import lightgbm
import xgboost
from shapash.utils.transform import inverse_transform, apply_preprocessing, get_col_mapping_ce
class TestInverseTransformCate... | pd.DataFrame(data=[0, 1, 0, 0], columns=['y']) | pandas.DataFrame |
import xml.etree.ElementTree as ET
from pathlib import Path
import cv2
import pandas as pd
from tqdm import tqdm
from manga_ocr_dev.env import MANGA109_ROOT
def get_books():
root = MANGA109_ROOT / 'Manga109s_released_2021_02_28'
books = (root / 'books.txt').read_text().splitlines()
books = pd.DataFrame(... | pd.DataFrame(data) | pandas.DataFrame |
import subprocess
import os
import pandas as pd
import glob
def setup_module(module):
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(THIS_DIR)
def teardown_module(module):
cmd = ["make clean"]
cmdOutput = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
def run_comma... | pd.DataFrame(columns = ["program","fp64_NAN", "fp64_INF", "fp64_SUB","fp32_NAN", "fp32_INF", "fp32_SUB","kernel","FP instructions","check_time","ori_time","slowdown"]) | pandas.DataFrame |
# Copyright(C) 2020 Google Inc.
#
# 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, so... | tm.assert_series_equal(result, expected) | pandas.util.testing.assert_series_equal |
#! /usr/bin/env python3
"""
Copyright 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 law or agreed to in wri... | pd.get_dummies(graph_labels) | pandas.get_dummies |
"""Read data files in different formats"""
import json as jsonlib
import pandas as pd
from eln.decorators.register_reader import register_reader, READERS as _READERS
from eln.helpers.logger import log_error
class UnsupportedFileFormatError(TypeError):
"""Unsupported file format"""
def read(plugin, *args, **kwar... | pd.read_csv(file_path) | pandas.read_csv |
# TODO move away from this test generator style since its we need to manage the generator file,
# which is no longer in this project workspace, as well as the output test file.
## ##
# #
# THI... | pd.DataFrame(test_class.data) | pandas.DataFrame |
""" test indexing with ix """
from warnings import catch_warnings
import numpy as np
import pandas as pd
from pandas.types.common import is_scalar
from pandas.compat import lrange
from pandas import Series, DataFrame, option_context, MultiIndex
from pandas.util import testing as tm
from pandas.core.common import Per... | tm.assert_frame_equal(df2, expected) | pandas.util.testing.assert_frame_equal |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
project_name = "reco-tut-mlh"; branch = "main"; account = "sparsh-ai"
project_path = os.path.join('/content', project_name)
# In[2]:
if not os.path.exists(project_path):
get_ipython().system(u'cp /content/drive/MyDrive/mykeys.py /content')
import m... | pd.DataFrame(val_data_te_ratings) | pandas.DataFrame |
# importing modules
import numpy as np
import pandas as pd
###ETL reddit data
#----------------------------------------------------------------------------------------------------------------------------------------
def pq (names, subredits='allstocks', sort='relevance', date='all', comments=False):
#importing r... | pd.to_numeric(comments['sentiment_score']) | pandas.to_numeric |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
import re
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import train_test_split
import xgboost as xgb
from sklearn.cluster import MiniBatchKMeans
def process_am... | pd.to_datetime(all_data.first_review) | pandas.to_datetime |
import pandas as pd
STRING_COLS = ["slug", "token"]
INT_COLS = ["tok_id", "length", "label"]
FLOAT_COLS = [
"page",
"x0",
"y0",
"x1",
"y1",
"gross_amount",
"match",
"digitness",
"log_amount",
]
BOOL_COLS = ["is_dollar"]
def fix_type(df, col, na_value, dtype, downcast=False):
i... | pd.to_numeric(df[col], downcast=dtype) | pandas.to_numeric |
from typing import Dict, List
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import pandas as pd
import seaborn as sns
from tqdm import tqdm
import wandb
api = wandb.Api()
entity = "proteins"
import matplotlib.ticker as ticker
class StupidLogFormatter(ticker.LogFormatter):
... | pd.DataFrame({"name": name_list}) | pandas.DataFrame |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import click
import logging
from dotenv import find_dotenv, load_dotenv
import pandas as pd
import numpy as np
import re
from sklearn.externals import joblib
# This program reads in both train and test data set
# and creates a dataset dictionary
# of cleaned and sani... | pd.read_csv(train_filepath, dtype={'Age': np.float64}) | pandas.read_csv |
"""
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... | pd.DataFrame() | pandas.DataFrame |
"""
This script is for analysing the outputs from the implementation of DeepAR in GluonTS
"""
import os, time
from pathlib import Path
import streamlit as st
import pandas as pd
import numpy as np
from gluonts.model.predictor import Predictor
from gluonts.dataset.common import ListDataset
from gluonts.transform import ... | pd.to_datetime(player_test_data.loc[:, 'date']) | pandas.to_datetime |
import numpy as np
import pytest
from pandas._libs import join as _join
from pandas import Categorical, DataFrame, Index, merge
import pandas._testing as tm
class TestIndexer:
@pytest.mark.parametrize(
"dtype", ["int32", "int64", "float32", "float64", "object"]
)
def test_outer_join... | _join.left_join_indexer(idx2.values, idx.values) | pandas._libs.join.left_join_indexer |
# -*- coding: utf-8 -*-
"""
Covid-19 em São Paulo
Gera gráficos para acompanhamento da pandemia de Covid-19
na cidade e no estado de São Paulo.
@author: https://github.com/DaviSRodrigues
"""
from datetime import datetime, timedelta
from io import StringIO
import locale
import math
from tableauscraper import TableauS... | pd.to_datetime(leitos_municipais_privados.data, format='%d/%m/%Y') | pandas.to_datetime |
# -*- coding: utf-8 -*-
import numpy as np
import pytest
from pandas._libs.tslib import iNaT
import pandas.compat as compat
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
from pandas import (
CategoricalIndex, DatetimeIndex, Float64Index, Index, Int64Index,
IntervalIndex, MultiIn... | tm.assert_index_equal(result, expected) | pandas.util.testing.assert_index_equal |
import pickle
import argparse
import common_utils
import itertools
import tqdm
import re
import collections
import random
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
def get_top_frags(zipped, threshold):
assert threshold > ... | pd.DataFrame(chunk) | pandas.DataFrame |
"""The postprocessing metric computation."""
import os # type: ignore
import numpy as np # type: ignore
import PySAM
import pandas as pd # type: ignore
import PySAM.PySSC as pssc # type: ignore
import PySAM.Singleowner as pysam_singleowner_financial_model # type: ignore
from copy import deepcopy # type: ignore
f... | pd.DataFrame(vals, columns=keys) | pandas.DataFrame |
#%%
import pandas as pd
import numpy as np
import holoviews as hv
import hvplot.pandas
from scipy.sparse.linalg import svds
from scipy.stats import chisquare, chi2_contingency
from sklearn.decomposition import TruncatedSVD
from umoja.ca import CA
hv.extension('bokeh')
#%%
X = context.io.load('xente_train')
Y = contex... | pd.get_dummies(time_since_last.PID) | pandas.get_dummies |
"""SQL io tests
The SQL tests are broken down in different classes:
- `PandasSQLTest`: base class with common methods for all test classes
- Tests for the public API (only tests with sqlite3)
- `_TestSQLApi` base class
- `TestSQLApi`: test the public API with sqlalchemy engine
- `TestSQLiteFallbackApi`: t... | tm.assert_frame_equal(iris_frame1, iris_frame2) | pandas._testing.assert_frame_equal |
#!usr/bin/env python
"""
Evaluate the performance of the generative model on multiple aspects:
to be filled
"""
import pandas as pd
import numpy as np
from post_processing import data
from rdkit import Chem, DataStructs
import scipy.stats as ss
import math
from rdkit import Chem
from rdkit.Chem.Draw import IPythonCons... | pd.read_csv('Training') | pandas.read_csv |
import numpy as np
from numpy.random import randn
import pytest
from pandas import DataFrame, Series
import pandas._testing as tm
@pytest.mark.parametrize("name", ["var", "vol", "mean"])
def test_ewma_series(series, name):
series_result = getattr(series.ewm(com=10), name)()
assert isinstance(series_result, S... | Series([1.0, np.nan, 101.0]) | pandas.Series |
# write_Division_Codes_from_Census.py (scripts)
# !/usr/bin/env python3
# coding=utf-8
"""
Grabs Census Region and Division codes from a static URL.
- Writes reshaped file to datapath as csv.
"""
import pandas as pd
import numpy as np
from flowsa.settings import datapath
url = "https://www2.census.gov/programs-sur... | pd.read_excel(url) | pandas.read_excel |
"""
Module for collecting metrics values from GCE datastore
generated with the cloud functions located in feature_engineering
USAGE:
$python3 collect_from_datastore.py
This will create a .csv file in the current folder containing
the values of all the metrics available in the database for later
use in the jupyter not... | pd.set_option('display.max_colwidth', -1) | pandas.set_option |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 23:14:33 2020
@author: arti
"""
import pandas as pd
import seaborn as sns
df = pd.read_csv('./titanic.csv')
pd.set_option('display.max_columns', 15)
rdf = df.drop(['deck', 'embark_town'], axis=1)
rdf = rdf.dropna(subset=['age'], how='any', a... | pd.concat([ndf, onehot_embarked], axis=1) | pandas.concat |
import pandas as pd
import numpy as np
import json
import argparse
import os
def get_args():
""" Allows users to input arguments
Returns:
argparse.ArgumentParser.parse_args
Object containing options input by user
"""
def isFile(string: str):
if os.path.isfile(string):
... | pd.DataFrame(paper_list) | pandas.DataFrame |
import pandas as pd
from numpy import datetime64
from pandas_datareader import data
from pandas.core.series import Series
from pandas.core.frame import DataFrame
from yahoofinancials import YahooFinancials
# holding period return in percents
def get_holding_period_return(df: DataFrame, start, end, col) -> float:
... | pd.DataFrame.from_dict(df) | pandas.DataFrame.from_dict |
'''
Copyright 2022 Airbus SAS
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
dis... | pd.DataFrame({'years': hist_energy['years'], 'Total production': hist_energy['Industry']}) | pandas.DataFrame |
"""
**hep_ml.speedup** is module to obtain formulas with machine learning,
which can be applied very fast (with a speed comparable to simple selections),
while keeping high quality of classification.
In many application (i.e. triggers in HEP) it is pressing to get really fast formula.
This module contains tools to pre... | pandas.DataFrame(result, columns=X.columns) | pandas.DataFrame |
import pytest
from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG, _period_code_map
from pandas.errors import OutOfBoundsDatetime
from pandas import Period, Timestamp, offsets
class TestFreqConversion:
"""Test frequency conversion of date objects"""
@pytest.mark.parametrize("freq", ["A", "Q", ... | Period("2020-01-30 15:57:27.576166", freq="U") | pandas.Period |
"""Tests for the sdv.constraints.base module."""
import warnings
from unittest.mock import Mock, patch
import pandas as pd
import pytest
from copulas.multivariate.gaussian import GaussianMultivariate
from copulas.univariate import GaussianUnivariate
from rdt.hyper_transformer import HyperTransformer
from sdv.constrai... | pd.DataFrame() | pandas.DataFrame |
# Import required libraries
import pandas as pd
import nest_asyncio
import numpy as np
import warnings
import re
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import TweetTokenizer
# Configurations
warnings.filterwarnings('ignore')
# This function takes a card and transforms... | pd.DataFrame(columns=tokens_set_list) | pandas.DataFrame |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 01:48:49 2018
@author: ozkan
"""
import pandas as pd
import numpy as np
#from sklearn.preprocessing import MinMaxScaler, LabelEncoder
from scipy import stats
from contextlib import contextmanager
import time
import gc
def nonUnique(x):
retu... | pd.factorize(POS_CASH[f_]) | pandas.factorize |
"""
This module implements visualizations for EOPatch
Credits:
Copyright (c) 2017-2019 <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
This source code is licensed under the... | pd.DataFrame(data=blank_timestamps, columns=[self.timestamp_column]) | pandas.DataFrame |
# Imports: standard library
import re
import copy
import datetime
from typing import Dict, List, Tuple, Union, Optional
# Imports: third party
import numpy as np
import pandas as pd
# Imports: first party
from ml4c3.metrics import weighted_crossentropy
from definitions.ecg import ECG_PREFIX
from definitions.ici impor... | pd.to_datetime(ecg_dates_str) | pandas.to_datetime |
import pickle
from ds import *
import pandas as pd
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn impor... | pd.Categorical(df['category']) | pandas.Categorical |
#!/usr/bin/env python
# encoding:utf-8
"""
Author : <NAME>
Date : 2021/8/4
Time: 20:06
File: precision_table_plot.py
HomePage : http://github.com/yuanqingmei
Email : <EMAIL>
compute the avg std max min values and draw the box plot of precision and recall.
"""
import time
def precision_table_plot(working_dir="F:\\NJU... | pd.set_option('display.width', 5000) | pandas.set_option |
################################################################################
# The contents of this file are Teradata Public Content and have been released
# to the Public Domain.
# <NAME> & <NAME> - April 2020 - v.1.1
# Copyright (c) 2020 by Teradata
# Licensed under BSD; see "license.txt" file in the bundle root ... | pd.to_numeric(df['married_ind']) | pandas.to_numeric |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 11:41:44 2018
@author: MichaelEK
"""
import types
import pandas as pd
import numpy as np
import json
from pdsf import sflake as sf
from utils import split_months
def process_allo(param, permit_use):
"""
Function to process the consented allocation from the in... | pd.merge(rv5b, waps1, on='Wap') | pandas.merge |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 30 09:52:31 2021
@author: HaoLI
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 8 11:48:41 2021
@author: HaoLI
"""
import torch, torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torc... | pd.read_csv('data1210rename_use.csv') | pandas.read_csv |
# -*- coding: utf-8 -*-
from collections import namedtuple
import csv
import json
import os
import re
import sys
import pkg_resources
from zipfile import ZipFile
import requests
from tiingo.restclient import RestClient
from tiingo.exceptions import (
InstallPandasException,
APIColumnNameError,
InvalidFre... | pd.to_datetime(prices.index) | pandas.to_datetime |
import ast
import os
import logging
import numpy as np
import pandas as pd
logger = logging.getLogger("iocurves analysis")
def boltzman(x, xmid, tau):
"""
evaluate the boltzman function with midpoint xmid and time constant tau over x
"""
return 1./(1. + np.exp(-(x - xmid)/tau))
def sigmoid(x, x0, ... | pd.DataFrame(index=time_points) | pandas.DataFrame |
import os
import math
import numpy as np
import collections
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
from collections.abc import Iterable
import stethoscope.plotting_constants as plotting_constants
def _roundup(x):
return int(math.ceil(x / 100) * 100)
class Ut... | pd.to_datetime(utilization_ts.index) | pandas.to_datetime |
import json
import pandas as pd
from objects.folder import Folder
from objects.mapping import Mapping
from objects.source import Source
from objects.target import Target
from objects.target_field import TargetField
from objects.source_field import SourceField
from objects.transformation import Transformation
from obj... | pd.DataFrame(transformations) | pandas.DataFrame |
import sys
import random as rd
import matplotlib
#matplotlib.use('Agg')
matplotlib.use('TkAgg') # revert above
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import os
import numpy as np
import glob
from pathlib import Path
from scipy.interpolate import UnivariateSpline
from scipy.optimize imp... | pd.read_csv(cdata_name) | pandas.read_csv |
import time
import copy
import pandas as pd
import networkx as nx
from fup.core.manager import Manager
from fup.core.functions import get_module_blueprints, get_blueprint
import fup.profiles
import fup.modules
def overwrite_config(a, b):
for key in b:
if isinstance(a.get(key), dict) and isinstance(b.get(k... | pd.DataFrame(stats) | pandas.DataFrame |
# coding: utf8
import torch
import numpy as np
import os
import warnings
import pandas as pd
from time import time
import logging
from torch.nn.modules.loss import _Loss
import torch.nn.functional as F
from sklearn.utils import column_or_1d
import scipy.sparse as sp
from clinicadl.tools.deep_learning.iotools import c... | pd.read_csv(cnn_metrics_path, sep='\t') | pandas.read_csv |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
pd.set_option('display.max_columns', 100)
pd.options.mode.chained_assignment = None
train_path = '../input/forest-cover-type-prediction/train.csv'
test_path = '../input/forest-cover-type-prediction/test.csv'
subm... | pd.read_csv(submit_path, index_col=0) | pandas.read_csv |
# Library for parsing arbitrary valid ipac tbl files and writing them out.
# Written by: <NAME>
# at: UCLA 2012, July 18
# The main elements the user should concern themselves with are:
#
# TblCol: a class for storing an IPAC table column, including all data and
# functions needed to input/output that column.
#... | pd.to_datetime(v) | pandas.to_datetime |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 2 15:46:53 2020
@author: Barney
"""
import os
import pandas as pd
import scipy.stats as stats
import numpy as np
#Misc
MINUTES_IN_HOUR = 60 #minutes
DAYS_IN_WEEK = 7 #days
HOURS_IN_DAY = 24 #hours
DIARY_INTERVAL = 10 #minutes
DIARY_OFFSET = 4 #hours (i.e. diary starts ... | pd.concat(time_results_df) | pandas.concat |
# -*- coding: utf-8 -*-
"""
Project : PyCoA
Date : april 2020 - march 2021
Authors : <NAME>, <NAME>, <NAME>
Copyright ©pycoa.fr
License: See joint LICENSE file
Module : coa.display
About :
-------
An interface module to easily plot pycoa data with bokeh
"""
from coa.tools import kwargs_test, extract_dates, ver... | pd.DataFrame({'clustername':sumgeo.clustername,'centroidx':centrosx,'centroidy':centrosy,'cases':cases,'geometry':sumgeo['geometry']}) | pandas.DataFrame |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pickle
import shutil
import sys
import tempfile
import numpy as np
from numpy import arange, nan
import pandas.testing as pdt
from pandas import DataFrame, MultiIndex, Series, to_datetime
# dependencies testing specific
import pytest
import recordlinka... | DataFrame({'col': arrayA}) | pandas.DataFrame |
import dash
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_html_components as html
import numpy as np
import pandas as pd
import plotly.graph_objs as go
df = pd.read_csv("./data/kiva_loans.csv", parse_dates=True)
def split_borrower_gender(l):
m = 0
f = 0
if type... | pd.to_datetime(df['date']) | pandas.to_datetime |
import pandas as pd
import matplotlib.pyplot as plt
retail_data1 = pd.read_csv('https://storage.googleapis.com/dqlab-dataset/10%25_original_randomstate%3D42/retail_data_from_1_until_3_reduce.csv')
retail_data2 = pd.read_csv('https://storage.googleapis.com/dqlab-dataset/10%25_original_randomstate%3D42/retail_data_from_... | pd.to_datetime(retail_table['order_date']) | pandas.to_datetime |
# Energy and entropy map
# calculation for pdb files
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn import preprocessing
import matplotlib.pyplot as plt
import seaborn as sns
from MD_Analysis import *
import easygui as eg
# Getting the phi/psi angles
# pdb = e... | pd.DataFrame() | pandas.DataFrame |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 13:34:51 2019
@author: jaime
#"""
import h5py as h5
from circle_fit import least_squares_circle
import pandas as pd
import re as re
from sys import platform
import numpy as np
import os
cmy = 365 * 24 * 60 * 60. * 100
class UserChoice(Excepti... | pd.DataFrame(data=mat_info, columns=['mat']) | pandas.DataFrame |
import sys
from sqlalchemy import create_engine
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.multioutput import MultiOutputClassifier
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.ensemble import RandomForestClassifier
from sklearn.mod... | pd.read_sql_table('Response', engine) | pandas.read_sql_table |
from kfp.components import InputPath, OutputPath
from kfp.v2.dsl import (Artifact,
Dataset,
Input,
Model,
Output,
Metrics,
ClassificationMetrics)
def get_full_tech_indi(
# ... | pd.read_pickle(tech_indi_dataset11.path) | pandas.read_pickle |
from flask import Flask,request, render_template, session, redirect, url_for, session
import numpy as np
import pickle
import pandas as pd
import datetime as dt
import bz2
app = Flask(__name__)
# data = bz2.BZ2File('model.pkl', 'rb')
# model = pickle.load(data)
# REMEMBER TO LOAD THE MODEL AND THE SCALER!
def conve... | pd.DataFrame.from_dict(feature_dict) | pandas.DataFrame.from_dict |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster.bicluster import SpectralCoclustering
from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool, ColumnDataSource
from itertools import product
######... | pd.DataFrame(data, columns=["name", "age", "ZIP"]) | pandas.DataFrame |
import click
import pandas as pd
import os
import time
from binance.client import Client
@click.command()
@click.option('--pm', default=0.01, help='Profit Margin')
@click.option('--ci', default=60, help='Check interval in seconds')
def trade_coins(pm, ci):
if os.path.isdir('crypto-data'):
pass
e... | pd.read_csv('crypto-data/coins_rebought_history.csv') | pandas.read_csv |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
import yfinance as yf
yf.pdr_override()
import datetime as dt
symbol = 'AMD'
market = 'SPY'
num_of_years = 1
start = dt.date.today() - dt.timedelta(days=365*num_of_years)
end... | pd.Series(dataset['High'] + 4 * (PP - dataset['Low'])) | pandas.Series |
import numpy as np
import pandas as pd
from scipy.optimize import minimize
from tqdm import tqdm
from kndetect.utils import extract_mimic_alerts_region
def get_feature_names(npcs=3):
"""
Create the list of feature names depending on the number of principal components.
Parameters
----------
npcs ... | pd.DataFrame.from_dict(features_df) | pandas.DataFrame.from_dict |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 30 20:25:08 2019
@author: alexandradarmon
"""
### RUN TIME SERIES
import pandas as pd
from punctuation.recognition.training_testing_split import (
get_nn_indexes
)
from punctuation.feature_operations.distances import d_KL
from punctuation... | pd.merge(dickens, df_temporal, how='left', on='title') | pandas.merge |
import pandas as pd
import numpy as np
from pandas_datareader import data
import matplotlib.pyplot as plt
import yaml
import sys
import math
plt.style.use('ggplot')
def LoadConfig(
yamlpath: str)-> dict:
config = yaml.load(
open(yamlpath, 'r'),
Loader=yaml.FullLoader)
return config
d... | pd.DataFrame(data=Agent.prices[::-1], index=None, columns=["a"]) | pandas.DataFrame |
import pandas as pd
import geopandas as gpd
import numpy as np
from .graph import Graph
from ..util import transform
import logging
from math import ceil, floor, sqrt
class BusSim:
def __init__(
self,
manager,
day,
start_time,
elapse_time,
avg_walking_speed=1.4,
... | pd.DataFrame(stops_radius_list) | pandas.DataFrame |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
pd.set_option('display.max_columns', 500)
def clean_features(data, type):
df = pd.DataFrame(data)
# df = df.drop("PassengerId", axis=1)
df.set_index("PassengerId")
df = df.drop(columns=['Cabin', 'Name', 'Tick... | pd.DataFrame([alive_age, dead_age]) | pandas.DataFrame |
from pandas import DataFrame, read_csv
from PyQt5 import uic, QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QTableView, QPushButton, QHeaderView
from Util import UI_DIR, resource_path
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self)... | DataFrame() | pandas.DataFrame |
# coding: utf8
from .tsv_utils import complementary_list, add_demographics, baseline_df, chi2
from ..deep_learning.iotools import return_logger
from scipy.stats import ttest_ind
import shutil
import pandas as pd
from os import path
import numpy as np
import os
import logging
sex_dict = {'M': 0, 'F': 1}
def create_s... | pd.DataFrame() | pandas.DataFrame |
__author__ = 'saeedamen' # <NAME>
#
# Copyright 2016-2020 Cuemacro - https://www.cuemacro.com / @cuemacro
#
# 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/LICENS... | pd.DatetimeIndex([delivery_date]) | pandas.DatetimeIndex |
import zipfile
import io
import requests
import json
import pandas as pd
pd.options.mode.chained_assignment = None
import os, sys, yaml
try: modulepath = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/') + '/'
except NameError: modulepath = 'facilitymatcher/'
output_dir = modulepath + 'output/'
data_dir ... | pd.read_csv(data_dir+'facilitymatches_manual.csv',header=0,dtype={'FacilityID':'str','FRS_ID':'str'}) | pandas.read_csv |
from . import filtertools
from .sound import Sound
from .library.voice_activity_detection import extract_voiced_segments
from .dataset import NoiseDataSet
import bisect
import librosa.core
import nltk
import numpy as np
import os
import pandas as pd
import scipy.fft
import scipy.signal
import time
class Test(object)... | pd.DataFrame(columns=old_results.columns, index=old_results.index) | pandas.DataFrame |
import unittest
import qteasy as qt
import pandas as pd
from pandas import Timestamp
import numpy as np
from numpy import int64
import itertools
import datetime
from qteasy.utilfuncs import list_to_str_format, regulate_date_format, time_str_format, str_to_list
from qteasy.utilfuncs import maybe_trade_day, is_market_tr... | Timestamp('2020-01-04 00:00:00', freq='D') | pandas.Timestamp |
import os
import pandas as pd
import pytest
from requests_mock.mocker import Mocker
from upgini import FeaturesEnricher, SearchKey
from upgini.metadata import RuntimeParameters
from .utils import (
mock_default_requests,
mock_get_features_meta,
mock_get_metadata,
mock_initial_search,
mock_initial... | pd.read_csv(path, sep=",") | pandas.read_csv |
import sys
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
plt.rcParams['font.size'] = 6
root_path = os.path.dirname(os.path.abspath('__file__'))
# root_path = os.path.abspath(os.path.join(root_path,os.path.pardir))
graphs_path = root_pat... | pd.read_csv(root_path+'/Zhangjiashan_vmd/projects/esvr/one_step_3_ahead_forecast_pacf/optimal_model_results.csv') | pandas.read_csv |
#!/usr/bin/env python3
import argparse
import configparser
import json
# import logging
import pandas as pd
# set logging
# logger=logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)
# formatter=logging.Formatter('[%(asctime)s:%(levelname)s:%(lineno)d %(message)s', datefmt='%H:%M:%S') #time:levelname:message... | pd.read_csv(args.i) | pandas.read_csv |
#
# Copyright 2018, Planet Labs, Inc.
#
# 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 ... | pd.to_datetime(df['julian'], unit='D', origin='julian') | pandas.to_datetime |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.