prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
import time
from typing import List
import tushare as ts
import pandas as pd
from pandas import DataFrame, Series
import os
import csv
import random
from datetime import datetime, timedelta
from utils.config_reader import ConfigReader
from utils.log import logger
from utils.common import get_file_list
config_reader = ... | pd.concat(name_list) | pandas.concat |
# -*- coding: utf-8 -*-
"""
13 July 2020
Author: <NAME>
Dataset version update 03
Adding newly released datasets.
"""
import pandas as pd
# Adding the new datasets released in June 2020
df = pd.read_csv(r"filepath\Aggregate-API.csv", sep = ";")
df1 = pd.read_csv(r"filepath\API_Melaka_2019_cleaned.csv")
df2 = | pd.read_csv(r"filepath\API_NS_2019_cleaned.csv") | pandas.read_csv |
#
# Copyright 2018 Quantopian, 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 wr... | pd.Series(d) | pandas.Series |
#Preliminaries
import numpy as np
import numpy
import pandas as pd
import random
import statsmodels.api as sm
import math
from sklearn.utils import resample
from scipy import percentile
from scipy import stats
from matplotlib import pyplot as plt
import requests
import io
import seaborn as sns
from matplotlib.patches i... | pd.DataFrame(data=factor_data,columns=factor_names) | pandas.DataFrame |
import pytest
import numpy as np
import pandas as pd
from pandas import Categorical, Series, CategoricalIndex
from pandas.core.dtypes.concat import union_categoricals
from pandas.util import testing as tm
class TestUnionCategoricals(object):
def test_union_categorical(self):
# GH 13361
data = [
... | union_categoricals([c1, c2], sort_categories=False) | pandas.core.dtypes.concat.union_categoricals |
import os
import re
import numpy as np
import pandas as pd
from pyd3d.utils import formatSci
from pyd3d.mdf import read
from IPython.display import Markdown as md
# from https://github.com/Carlisle345748/Delft3D-Toolbox/blob/master/delft3d/TimeSeriesFile.py
class TimeSeries(object):
"""Read, modify and export Del... | pd.concat([relative_time, time_series], axis=1) | pandas.concat |
# Copyright 2016 Ufora 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 i... | pandas.Series([1, -1, -1, 1, 1, 1, -1, 1, 1, -1]) | pandas.Series |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import rfft, irfft, rfftfreq
# Fast Fourier Transform (FFT)
def fast_fourier_transform(data_measured, data_desired, n, t):
# Define function on which the FFT shall be executed
dm_pos = data_measu... | pd.DataFrame(ddl) | pandas.DataFrame |
'''
Urban-PLUMBER processing code
Associated with the manuscript: Harmonized, gap-filled dataset from 20 urban flux tower sites
Copyright (c) 2021 <NAME>
Licensed under the Apache License, Version 2.0 (the "License").
You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
'''
__title__ =... | pd.DataFrame(index=times) | pandas.DataFrame |
'''
Illustration of the uncertainty surrounding point estimations of the decay value (with and without stationarity breaks) in a Hawkes process.
This code produces normalized decay distributions which deviate from the standard Gaussian, as exemplified in Fig. 1 in the paper.
'''
import functools
import os
import sys
im... | pd.DataFrame({"Beta": df, "SplitBeta": df_splitbeta}) | pandas.DataFrame |
import pandas as pd
import inspect
import functools
# ============================================ DataFrame ============================================ #
# Decorates a generator function that yields rows (v,...)
def pd_dfrows(columns=None):
def dec(fn):
def wrapper(*args,**kwargs):
return pd... | pd.DataFrame(d,inx,columns=columns) | pandas.DataFrame |
#!/usr/bin/env python3
import argparse
from collections import Counter
from itertools import combinations
from math import lgamma, log, factorial
import numpy as np
import operator
import os
import pandas as pd
from functools import reduce
import sys
import time
import warnings
###############################
##### A... | pd.DataFrame(columns=['child', 'palim', 'alpha', 'all_scores', 'n_scores_' + bound, 'time_' + bound, 'inf_n_scores', 'best_pa']) | pandas.DataFrame |
#! /usr/bin/env python3
import pandas as pd
import os
from steves_utils.summary_utils import (
get_experiments_from_path
)
from steves_utils.utils_v2 import (
get_experiments_base_path
)
class tuned_1v2_Helper:
def __init__(self, series_path = os.path.join(get_experiments_base_path(), "tuned_1v2")):
... | pd.DataFrame(all_trials) | 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... | tm.assert_index_equal(dropped, expected) | pandas.util.testing.assert_index_equal |
import pandas as pd
import numpy as np
from datetime import date
"""
dataset split:
(date_received)
dateset3: 20160701~20160731 (113640),features3 from 20160315~20160630 (off_test)
dateset2: 20160515~20160615 (258446),features2 from 20160201~2... | pd.merge(merchant2_feature,t3,on='merchant_id',how='left') | pandas.merge |
import logging as log
import typing
from takco.linkedstring import LinkedString
try:
import pandas as pd
except:
log.error(f"Cannot import pandas")
@pd.api.extensions.register_dataframe_accessor("takco")
class TakcoAccessor:
def __init__(self, df):
self._df = df
self.provenance = {}
... | pd.MultiIndex.from_arrays(self.head) | pandas.MultiIndex.from_arrays |
#some of these imports are extraneous and left over from the flask megatutorial
from flask import render_template, flash, redirect, url_for, request, Flask, jsonify, send_from_directory
from app import app, db, DataWizardTools, HousingToolBox
from app.models import User, Post
from app.forms import PostForm
from w... | pd.read_excel(f) | pandas.read_excel |
"""figures of merit is a collection of financial calculations for energy.
This module contains financial calculations based on solar power and batteries
in a given network. The networks used are defined as network objects (see evolve parsers).
TODO: Add inverters: Inverters are not considered at the momen... | pd.DataFrame() | pandas.DataFrame |
# coding: utf-8
"""Extract AA mutations from NT mutations
Author: <NAME> - Vector Engineering Team (<EMAIL>)
"""
import pandas as pd
from scripts.fasta import read_fasta_file
from scripts.util import translate
def extract_aa_mutations(
dna_mutation_file, gene_or_protein_file, reference_file, mode="gene"
):
... | pd.read_csv(dna_mutation_file) | pandas.read_csv |
import os
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import pickle
import tensorflow
from tensorflow.keras import metrics
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
import models
print('GPU', tenso... | pd.DataFrame(data, columns=['label', 'file', 'path']) | pandas.DataFrame |
"""
This module includes two types of discrete state-space formulations for biogas plants.
The anaerobic digestion model in FlexibleBiogasPlantModel is based on the work in
https://doi.org/10.1016/j.energy.2017.12.073 and ISBN: 978-3-319-16192-1
The module is designed to work with fledge: https://doi.org/10.5281/... | pd.Index([]) | pandas.Index |
# This script analyzes the csv files output by PixDistStats2.py
# Updated Feb 2021.
# PixDistStats2 separates the data into biological replicates instead of aggregating all data for each sample group.
# This script takes those data and does stats and makes plots.
# pixel_distance.py actually performs the measurement o... | pd.read_csv(dir + 'numpix_by_dist_bins.csv', index_col='distance bins') | pandas.read_csv |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2015, IBM Corp.
# All rights reserved.
#
# Distributed under the terms of the BSD Simplified License.
#
# The full license is in the LICENSE file, distributed with this software.
... | pd.Series() | pandas.Series |
import pandas as pd
import numpy as np
from pandas.api.types import is_numeric_dtype
import re
from nltk.tokenize import word_tokenize
import joblib
import pickle
def func(ser):
nans = np.count_nonzero( | pd.isnull(ser) | pandas.isnull |
"""Class for intent operations - training, predict"""
import os
import re
import json
import datetime
import joblib
import numpy as np
import pandas as pd
from typing import List, Union
from sklearn.model_selection import GridSearchCV
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeli... | pd.DataFrame({"words": [words], "contexts": ["{}"]}) | pandas.DataFrame |
# Copyright 2017-2020 Lawrence Livermore National Security, LLC and other
# Hatchet Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
import glob
import struct
import re
import os
import traceback
import numpy as np
import pandas as pd
import multiprocessing as mp
import... | pd.DataFrame.from_dict(data=self.node_dicts) | pandas.DataFrame.from_dict |
import numpy as np
import pandas as pd
from numba import njit
import pytest
from vectorbt import defaults
from vectorbt.utils import checks, config, decorators, math, array
from tests.utils import hash
# ############# config.py ############# #
class TestConfig:
def test_config(self):
conf = config.Conf... | pd.Series([1, 2, 3]) | pandas.Series |
'''
Python reducer function
Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
'''
'''
Modified by <EMAIL> for AWS lambda map-reduce test.
This reducer function takes in multiple files which are mapper phase outputs , writes back to one parquet file in s3
'''
import... | pd.to_numeric(df['tolls_amount']) | pandas.to_numeric |
# Copyright (C) 2014-2017 <NAME>, <NAME>, <NAME>, <NAME> (in alphabetic order)
#
# This file is part of OpenModal.
#
# OpenModal is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
... | pd.concat([self.tables['measurement_values'], dlist], ignore_index=True) | pandas.concat |
import pandas as pd
import re
from bs4 import BeautifulSoup
import os.path
def main():
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
#filepath = input('txt file: ')
filepath = 'goodreads.txt'
html_path = os.path.join(BASE_DIR, filepath)
with open(html_path, encodin... | pd.DataFrame(tabel) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""Copy of Lab4Rn.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Okb2MBZEdgXtPXNqA-zqZkXR5dfNqz28
"""
# !pip install wikipedia
import wikipedia
wikipedia.set_lang("en")
corpus = []
def search(topic):
summaries = ... | pd.DataFrame(columns=['x', 'y', 'document']) | pandas.DataFrame |
"""Main module."""
import csv, json, pandas as pd
import os, sys, requests, datetime, time
import zipfile, io
import lxml.html as lhtml
import lxml.html.clean as lhtmlclean
import warnings
from pandas.core.common import SettingWithCopyWarning
warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)
cla... | pd.melt(wlExport, value_vars=["ResponseID"]) | pandas.melt |
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel
from transformers import AdamW, get_cosine_with_hard_restarts_schedule_with_warmup
import gc
from tqdm import tqdm
class MyDataset(Dataset):
def __init__(self... | pd.read_csv(dataset_path) | pandas.read_csv |
import xgboost as xgb
import graphviz
import numpy as np
import pandas as pd
import random
import matplotlib
import textwrap
import scipy.spatial.distance as ssd
from scipy.stats import ks_2samp
from scipy.stats import entropy
import warnings
from sklearn import tree
from sklearn.manifold import TSNE
from sklearn.ense... | pd.pivot_table(drode_de_gene_df_2, index='gene', columns='group_2', values='posmean_2') | pandas.pivot_table |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import pandas.util.testing as pdt
import pytest
from recordlinkage.preprocessing import clean
from recordlinkage.preprocessing import phonenumbers
from recordlinkage.preprocessing import phonetic
from recordlinkage.preprocessing impo... | pdt.assert_series_equal(clean_series, expected) | pandas.util.testing.assert_series_equal |
import json
import logging
import socketio
from .constants import *
_LOGGER = logging.getLogger(__name__)
ringalarm_devices_list = []
required_columns = [DEVICE_ZID, DEVICE_NAME, DEVICE_BATTERY_STATUS, DEVICE_BATTERY_LEVEL, DEVICE_TYPE, \
DEVICE_ROOM_ID, DEVICE_TAMPER_STATUS, \
... | pd.concat([r, i], ignore_index=True, sort=False) | pandas.concat |
import os
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import json
from sklearn.metrics import accuracy_score
from src.data.strava_data_load_preprocess import (
load_week_start_times_data,
load_lgbm_model_results,
load_logreg_model_results,
load_l... | pd.DatetimeIndex(activity_df.start_date_local) | pandas.DatetimeIndex |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Licen... | pd.Timestamp(x) | pandas.Timestamp |
from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from surprise import NMF
from surprise import KNNWithMeans
from surprise import accuracy
from surprise.model_selection import K... | pd.to_numeric(data['current_year'], errors='coerce') | pandas.to_numeric |
"""
This script reads all the bootstrap performance result files, plots histograms, and calculates averages.
t-tests are done to compute p-values and confidence intervals are computed
"""
import pandas as pd
import os
import matplotlib.pyplot as plt
import matplotlib
from scipy import stats
matplotlib.rcPa... | pd.DataFrame([rnn_rmse_t1_list, rnn_rmse_t9_list, rnn_rmse_t18_list]) | pandas.DataFrame |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
NbrOfNodes = 3
key200 = ' TIME: GANDRA STEP: 200.000 FRAME: 1.000'
#--------------------------------------------------------------------------
# File for gain parameter 0.05
#----------------------------... | pd.Series(gain10) | pandas.Series |
#!/usr/bin/env python
# coding: utf-8
# ## Analyze A/B Test Results
#
#
# ## Table of Contents
# - [Introduction](#intro)
# - [Part I - Probability](#probability)
# - [Part II - A/B Test](#ab_test)
# - [Part III - Regression](#regression)
#
#
# <a id='intro'></a>
# ### Introduction
#
# A/B tests are very commonly... | pd.get_dummies(df2['group']) | pandas.get_dummies |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import dash_table
import pandas as pd
import numpy as np
import plotly.express as px
from viz.app import app
# Data Management S... | pd.read_csv('./viz/data/economic/results_summary_bycrop.csv') | pandas.read_csv |
#!/usr/bin/env python
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, ECG Sex Classification"
__credits__ = ["<NAME>"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
import numpy as np
import pandas as pd
from sklearn import preprocessing
from... | pd.read_csv(feature_path, index_col=0) | pandas.read_csv |
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
# Command line :
# python -m benchmark.S3D2.CALIB-R
import os
import logging
from config import SEED
from config import _ERROR
from... | pd.DataFrame(result_table) | pandas.DataFrame |
from time import sleep
from old.src.core import Generator_Shui5
from old.src.Model import DataModel
import multiprocessing
import pandas as pd
url_que = multiprocessing.Queue()
res_list = []
def url_put():
for i in range(1, 602):
url_que.put('https://www.shui5.cn/article/NianDuCaiShuiFaGui/108_' + str(i... | pd.DataFrame(res_list) | pandas.DataFrame |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['makeMixedDataFrame', 'getCrashes', 'is_numeric', 'drop_singletons', 'discretize']
# Cell
import pandas as pd
from pandas.api.types import is_numeric_dtype as isnum
#from matplotlib.pyplot import rcParams
# Cell
def ... | pd.to_numeric(col, errors='coerce') | pandas.to_numeric |
import pytz
import pytest
import dateutil
import warnings
import numpy as np
from datetime import timedelta
from itertools import product
import pandas as pd
import pandas._libs.tslib as tslib
import pandas.util.testing as tm
from pandas.errors import PerformanceWarning
from pandas.core.indexes.datetimes import cdate_... | cdate_range(START, END) | pandas.core.indexes.datetimes.cdate_range |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 09:49:54 2020
@author: enzo
"""
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import pandas as pd
import numpy as np
from sklearn.base import ClassifierMixin
class CombClass(ClassifierMixin):
def __init__(self):
r... | pd.Series(y_mlp_pred, index=X_test.index, name='mlp_pred') | pandas.Series |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 29 19:25:05 2017
@author: <NAME>
Data preprocessing steps
"""
import pandas as pd
import numpy as np
#Data processing
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import MinMaxScaler, MaxAbsScaler, RobustScaler, StandardScaler
from sklearn.pipel... | pd.get_dummies(X2, sparse=True) | pandas.get_dummies |
"""Tests for the sdv.constraints.tabular module."""
import uuid
from datetime import datetime
from unittest.mock import Mock
import numpy as np
import pandas as pd
import pytest
from sdv.constraints.errors import MissingConstraintColumnError
from sdv.constraints.tabular import (
Between, ColumnFormula, CustomCon... | pd.to_datetime('2020-09-03') | pandas.to_datetime |
# Copyright (c) ZenML GmbH 2021. All Rights Reserved.
# 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 applicabl... | pd.merge(X, y, left_index=True, right_index=True) | pandas.merge |
from __future__ import division
from datetime import timedelta
from functools import partial
import itertools
from nose.tools import assert_true
from parameterized import parameterized
import numpy as np
from numpy.testing import assert_array_equal, assert_almost_equal
import pandas as pd
from toolz import merge
fro... | pd.Timestamp('2015-01-09') | pandas.Timestamp |
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
__author__ = ["<NAME>"]
__all__ = [
"TEST_YS",
"TEST_SPS",
"TEST_ALPHAS",
"TEST_FHS",
"TEST_STEP_LENGTHS_INT",
"TEST_STEP_LENGTHS",
"TEST_INS_FHS",
"TEST_OOS_FHS",
"TEST_WINDOW_LENGTHS_INT",
"TEST_WINDOW_LENGTHS",
"TEST_INITI... | pd.offsets.Day(1) | pandas.offsets.Day |
from BoostInference_no_parallelization import Booster
import sys, pandas as pd, numpy as np
import glob, pickle
from sklearn.metrics import roc_auc_score, precision_recall_curve, auc
if len(sys.argv)<5:
print('python file.py df-val-PhyloPGM-input df-test-PhyloPGM-output info_tree fname_df_pgm_output')
exit(0)... | pd.DataFrame() | pandas.DataFrame |
import pytest
import pandas as pd
from pandas import Timestamp
from datetime import date
from pyramm.ops.top_surface import build_top_surface, append_surface_details_to_segments
@pytest.fixture
def original():
return pd.DataFrame.from_records(
[
{
"road_id": 100,
... | Timestamp(2020, 1, 1) | pandas.Timestamp |
# coding: utf-8
# In[213]:
import numpy as np
import pandas as pd
import random
import csv
from sklearn.utils import shuffle
# In[214]:
same = pd.read_csv(r'C:\Users\<NAME>\Desktop\ASSIGNMENTS\ML\HumanObserved-Dataset\HumanObserved-Dataset\HumanObserved-Features-Data\same_pairs.csv',usecols=['img_id_A','img_i... | pd.read_csv(r'C:\Users\<NAME>\Desktop\ASSIGNMENTS\ML\HumanObserved-Dataset\HumanObserved-Dataset\HumanObserved-Features-Data\diffn_pairs.csv') | pandas.read_csv |
import pandas as pd
def merge_cellphone_genes(cluster_counts: pd.DataFrame, genes_expanded: pd.DataFrame) -> pd.DataFrame:
"""
Merges cluster genes with CellPhoneDB values
"""
multidata_counts = pd.merge(cluster_counts, genes_expanded, left_index=True, right_on='ensembl')
return multidata_counts... | pd.DataFrame() | pandas.DataFrame |
import logging
import re
import pandas as pd
from unidecode import unidecode
from comvest.utilities.io import files, read_from_db, write_result, read_result
from comvest.utilities.logging import progresslog, resultlog
pd.options.mode.chained_assignment = None # default='warn'
def validacao_curso(df, col, date):
cu... | pd.to_numeric(emphasis['insc_cand'], errors='coerce', downcast='integer') | pandas.to_numeric |
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: all,-execution,-papermill,-trusted
# formats: ipynb,py//py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# ... | pd.option_context("display.max_rows", None, "display.max_columns", None) | pandas.option_context |
import argparse
import textwrap
import os
import pandas as pd
from glob import glob
from reframed import Environment, ModelCache
from .designmc import design
def main():
parser = argparse.ArgumentParser(description="Design microbial communities.")
parser.add_argument('models', metavar='MODELS', nargs='+',
... | pd.concat(dfs) | pandas.concat |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from scipy.special import boxcox1p
from scipy.stats import norm, skew
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.linear_model im... | pd.DataFrame({'Missing Ratio': all_data_na}) | pandas.DataFrame |
import __main__ as main
import sys
import geopandas as gpd
import pandas as pd
import numpy as np
if not hasattr(main, '__file__'):
argv = ['code', 'data/processed/geo/tiles.shp',
'data/processed/census/oa_tile_reference.csv',
'data/raw/census_lookups/engwal_OA_lsoa.csv',
'data/... | pd.merge(oa_lus['ni'], eth_data['ni'], left_on='SA2011', right_on='Code', how = 'left') | pandas.merge |
import random
import numpy as np
import pytest
import pandas as pd
from pandas import (
Categorical,
DataFrame,
NaT,
Timestamp,
date_range,
)
import pandas._testing as tm
class TestDataFrameSortValues:
def test_sort_values(self):
frame = DataFrame(
[[1, 1, 2], [3, 1, 0], ... | tm.assert_frame_equal(result, expected) | pandas._testing.assert_frame_equal |
import pandas as pd
from dsbox.ml.feature_engineering import TagEncoder
from dsbox.ml.feature_engineering.timeseries import RollingWindower, Shifter
from dsbox.utils import pandas_downcast_numeric
def concat_train_test(dataframe_list):
shop_data = dataframe_list[0]
shop_data_to_predict = dataframe_list[1]
... | pd.to_datetime(shop_data['Date'], format='%Y-%m-%d') | pandas.to_datetime |
import numpy as np
import pandas as pd
from typing import List
from sklearn.preprocessing import StandardScaler
from cytominer_eval.transform import metric_melt
from cytominer_eval.transform.util import set_pair_ids
def assign_replicates(
similarity_melted_df: pd.DataFrame, replicate_groups: List[str],
) -> pd.... | pd.Series(return_bundle) | pandas.Series |
from __future__ import division
import pytest
import numpy as np
from datetime import timedelta
from pandas import (
Interval, IntervalIndex, Index, isna, notna, interval_range, Timestamp,
Timedelta, compat, date_range, timedelta_range, DateOffset)
from pandas.compat import lzip
from pandas.tseries.offsets imp... | IntervalIndex(data, closed=closed) | pandas.IntervalIndex |
# -*- coding: utf-8 -*-
# pylint: disable=E1101,E1103,W0232
import os
import sys
from datetime import datetime
from distutils.version import LooseVersion
import numpy as np
import pandas as pd
import pandas.compat as compat
import pandas.core.common as com
import pandas.util.testing as tm
from pandas import (Categor... | pd.concat([df2, df2]) | pandas.concat |
# -*- coding: utf-8 -*-
"""
Part of slugdetection package
@author: <NAME>
github: dapolak
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.ensemble import RandomFores... | pd.Timedelta('5 h') | pandas.Timedelta |
import numpy as np
from numpy import where
from flask import Flask, request, jsonify, render_template
import pandas as pd
from sklearn.ensemble import IsolationForest
from pyod.models.knn import KNN
import json
from flask import send_from_directory
from flask import current_app
app = Flask(__name__)
class Detect:
... | pd.DataFrame(self.file) | pandas.DataFrame |
import pandas as pd
import tasks
from . import base
from models import TimeModel
from datetime import datetime, timedelta
from azrael import SnapchatReporter
from typing import Optional
class SnapchatReportFetcher(base.ReportFetcher[tasks.FetchSnapchatReportTask]):
api_start_date: Optional[datetime]
api_end_date:... | pd.DataFrame() | pandas.DataFrame |
import datetime
import os
import numpy as np
import pandas as pd
import us_state_abbrev
def LoadAllJhuData(path=None):
if not path:
path = os.path.join(os.path.dirname(__file__),
'COVID-19/csse_covid_19_data/csse_covid_19_daily_reports')
all_dfs = {}
for f in sorted(os.listdir(path)... | pd.read_csv(full_path) | pandas.read_csv |
#encoding=utf-8
import numpy as np
import pandas as pd
from activation_functions import one_hot
from build_nn import BasePath, L_layer_model,predict
import pickle
def get_data_from_kaggle(filePath):
"""
:param filePath:
:return:
X -- input data, shape of (number of features, number of exam... | pd.read_csv(filePath) | pandas.read_csv |
# -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# ... | pd.Series(['b', 'aa', '', 'b', 'o', None, 'oo']) | pandas.Series |
import pandas as pd # Library to read and write the data in structure format
import numpy as np # Library to deal with vector, array and matrices
import requests # Library to read APIs
import re # Library for regular expression
import json # Library to read and write JSON file
from bs4 import BeautifulSoup # Libra... | pd.DataFrame(Values,columns=['State_UT', 'District', 'Confirmed']) | pandas.DataFrame |
import os
from math import ceil
from concurrent.futures import ProcessPoolExecutor
import pandas as pd
class FileUtils:
ALLOWED_EXTENSIONS = ['csv', 'xls', 'xlsx', 'zip']
@staticmethod
def read_parallel(paths, workers=4, concat=True, **read_options):
""" Concat the dataframes using multiple pro... | pd.concat(temp) | pandas.concat |
# -*- coding: utf-8 -*-
import sys
import os
from pandas.io import pickle
# import pandas as pd
PROJECT_ID = "dots-stock" # @param {type:"string"}
REGION = "us-central1" # @param {type:"string"}
USER = "shkim01" # <---CHANGE THIS
BUCKET_NAME = "gs://pipeline-dots-stock" # @param {type:"string"}
PIPELINE_ROOT = f"... | pd.Timestamp.now('Asia/Seoul') | pandas.Timestamp.now |
import pandas as pd
import pyodbc
def query_to_df(sql_file, driver='upiqm110'):
# Read SQL
sql_path = 'sql/{}.sql'.format(sql_file)
sql_query = open(sql_path).read()
# Connection
print('Connecting to database ... ')
con = pyodbc.connect('DSN={driver}'.format(driver=driver))
return | pd.read_sql_query(sql_query, con) | pandas.read_sql_query |
#!/usr/bin/env python
# coding: utf-8
# # Feature_Selection
# - **Having irrelevant features in your data can decrease the accuracy of the models and makes your models learn based on irrelevant**
# ## Defination
# **Feature Selection** :
#
# - Process of selecting the best features which contribute maximum for the... | pd.read_csv(path+"\\data.csv") | pandas.read_csv |
'''
Name:HenonMapDataGen
Desriptption: It is used to generate the data of modified Henon Map
Email: <EMAIL>
OpenSource: https://github.com/yesunhuang
Msg: For quantum recurrrent neural networks
Author: YesunHuang
Date: 2022-03-26 20:45:29
'''
#import everything
import pandas as pd
import numpy as np
import torch
impor... | pd.read_csv(path) | pandas.read_csv |
from collections import namedtuple
from jug import TaskGenerator, bvalue
import ena
from cleanup import cleanup_metadata
from jug.hooks import exit_checks
exit_checks.exit_if_file_exists('jug.exit')
cleanup_metadata = TaskGenerator(cleanup_metadata)
get_sample_xml = TaskGenerator(ena.get_sample_xml)
get_data_xml = Ta... | pd.DataFrame({k:metamerged[k] for k in selected_samples if k in metamerged}) | pandas.DataFrame |
import json
from os import path
import time
import typing
import random
import sys
import itertools
import warnings
import numpy as np
import tqdm
from lazy import lazy
import pandas as pd
from docopt import docopt
import multiprocessing as mp
from multiprocessing import Pool
from rdkit import RDLogger
RDLogger.Disab... | pd.DataFrame(res, columns=["SMILES", "NAME", "FILTER", "MW", "LogP", "HBD", "HBA", "TPSA", "Rot"]) | pandas.DataFrame |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import sys, os
import pandas.io.sql as psql
import psycopg2 as pg
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
from pandas.core.frame import DataFrame
import json
import math
# Connect to database
conn = pg.connect(... | pd.DataFrame(quad_list1) | pandas.DataFrame |
import os
import numpy as np
import pandas as pd
import deflex as dflx
from holoviews_sankey import create_and_save_sankey
path = "/home/uwe/deflex/quarree100/results_cbc/"
dump = "2018-DE02-Agora.dflx"
deflx = os.path.join(path, dump)
all_results = dflx.fetch_deflex_result_tables(deflx)
# From Commo... | pd.DataFrame(data=d, columns=["From", "To", "Value"]) | pandas.DataFrame |
"""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... | sql.get_schema(self.test_frame1, "test") | pandas.io.sql.get_schema |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 21:56:08 2020
@author: <NAME>
"""
# STEP1----------------- # Importing the libraries------------
#-------------------------------------------------------------
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn a... | pd.concat([MidRT, SlowRT_upsampled, FastRT_upsampled]) | pandas.concat |
import torch
from torch.utils.data import Dataset
import os
import pandas as pd
import numpy as np
from sklearn.model_selection import StratifiedShuffleSplit
__author__ = "<NAME>"
__copyright__ = "Copyright 2018 The Aramis Lab Team"
__credits__ = ["<NAME>"]
__license__ = "See LICENSE.txt file"
__version__ = "0.1.0"
__... | pd.read_csv(data_file, sep='\t') | pandas.read_csv |
# required libraries
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from processing import train_lemma, test_lemma
# datasets
train = pd.read_csv('dataset/train.csv')
test = pd.read_csv('dataset/test.csv')
# preprocessed and final dataset dataset
train_df = pd.concat([train, | pd.DataFrame(train_lemma, columns=['resumes']) | pandas.DataFrame |
import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame, Index, Series, date_range, offsets
import pandas._testing as tm
class TestDataFrameShift:
def test_shift(self, datetime_frame, int_frame):
# naive shift
shiftedFrame = datetime_frame.shift(5)
tm.assert_inde... | tm.assert_frame_equal(unshifted, ps) | pandas._testing.assert_frame_equal |
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import matplotlib.pyplot as plt
import pandas as pd
def get_analysis(news_list):
vader = SentimentIntensityAnalyzer()
columns = ['ticker','date', 'time', 'headline']
news_df = pd.DataFrame(news_list, columns=columns)
##pd.set_option('display... | pd.to_datetime(news_df.date) | pandas.to_datetime |
import pandas as pd
import numpy as np
from copy import deepcopy
import json
from pathlib import Path
from kipoi.data import Dataset
# try:
# import torch
# from bpnet.data import Dataset
# torch.multiprocessing.set_sharing_strategy('file_system')
# except:
# print("PyTorch not installed. Using Dataset from kipoi.d... | pd.read_csv(self.tsv_file, nrows=0, sep='\t') | pandas.read_csv |
#%%
import numpy as np
import pandas as pd
import altair as alt
import anthro.io
# Generate a plot for phosphate rock production
data = pd.read_csv('../processed/IFA_phosphate_rock_public_2008_2019_processed.csv')
data['year'] = pd.to_datetime(data['Year'].astype(str), format='%Y', errors='coerce')
agg_data = | pd.DataFrame() | pandas.DataFrame |
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2019 yutiansut/QUANTAXIS
#
# 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 th... | pd.Series(macd, index=Series.index) | pandas.Series |
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
import datetime as dt
import re
import cupy as cp
import numpy as np
import pandas as pd
import pyarrow as pa
import pytest
from pandas.util.testing import (
assert_frame_equal,
assert_index_equal,
assert_series_equal,
)
import cudf
from cudf.core import Data... | pd.Series([0, 1, -1, 100, 200, 47637]) | pandas.Series |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2019, <NAME> <<EMAIL>>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# 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 with... | pd.DataFrame(data=samples, columns=model.decs) | pandas.DataFrame |
# coding: UTF-8
import numpy as np
from numpy import nan as npNaN
import pandas as pd
from pandas import Series
import talib
from src import verify_series
def first(l=[]):
return l[0]
def last(l=[]):
return l[-1]
def highest(source, period):
return pd.Series(source).rolling(period).max().values
de... | pd.Series(high) | pandas.Series |
import json
from itertools import product
from unittest.mock import ANY, MagicMock, patch
import numpy as np
import pandas as pd
import pytest
import woodwork as ww
from evalml.exceptions import PipelineScoreError
from evalml.model_understanding.prediction_explanations.explainers import (
ExplainPredictionsStage,... | pd.DataFrame(X) | pandas.DataFrame |
import pandas as pd
import requests
import numpy as np
import json
import csv
import time
import datetime
import urllib3
import sys
import os
import warnings
import pandas as pd
import os
import numpy as np
from sqlalchemy import create_engine
import psycopg2
import warnings
from datetime import datetime
from pandas.co... | pd.concat([top_5_volume, top_5_ratio]) | pandas.concat |
import pandas as pd
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
class OutlierRemover(TransformerMixin, BaseEstimator):
def __init__(self,
dependent_col=None,
esti... | pd.concat([X,Y],axis="columns") | pandas.concat |
#!/usr/bin/env python
# coding: utf-8
# # Extract Covid-19 data from website grainmart.in using BeautifulSoup
# In[1]:
# importing the libraries
from bs4 import BeautifulSoup
import requests
import csv
import pandas as pd
# In[2]:
covid_source_filename = "/home/sanjay/campaign/dev_codes/jupyter_lab/covid_19_hac... | pd.read_csv(covid_target_filename) | pandas.read_csv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.