prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
"""
Synthetic Data Generation using a Bayesian Network
Based on following paper
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>.
PrivBayes: Private Data Release via Bayesian Networks. (2017)
"""
import numpy as np
import pandas as pd
from pyhere import here
from sklearn.base import BaseEstimator, TransformerMixin
from sklear... | pd.DataFrame(Xt, columns=[c.node for c in self.network_]) | pandas.DataFrame |
from datetime import datetime, time
from itertools import product
import numpy as np
import pytest
import pytz
import pandas as pd
from pandas import (
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Series,
date_range,
period_range,
to_datetime,
)
import pandas.util.testing as tm
import... | tm.assert_frame_equal(result, expected) | pandas.util.testing.assert_frame_equal |
import pandas as pd
import numpy as np
s = | pd.Series() | pandas.Series |
import pickle
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import Normalizer
from sklearn.model_selection import train_test_split
from sklearn.preprocessi... | pd.to_datetime(test_df['Date'], format='%Y-%m-%d') | pandas.to_datetime |
# -*- coding: utf-8 -*-
"""
Methods to perform coverage analysis.
@author: <NAME> <<EMAIL>>
"""
import pandas as pd
import numpy as np
import geopandas as gpd
from typing import List, Optional
from shapely import geometry as geo
from datetime import datetime, timedelta
from skyfield.api import load, wgs84, EarthSatel... | pd.Series([], dtype="object") | pandas.Series |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# see license https://github.com/DerwenAI/kglab#license-and-copyright
"""
SPARQL query abstractions.
"""
import re
import typing
import pandas as pd # type: ignore # pylint: disable=E0401
import pyvis # type: ignore # pylint: disable=E0401
import rdflib # type: ignor... | pd.DataFrame(rows_list) | pandas.DataFrame |
import pandas as pd
from pathlib import Path
from utils.aioLogger import aioLogger
from typing import List
from config.aioConfig import CESDataConfig
from utils.aioError import aioPreprocessError
import re
import matplotlib.pyplot as plt
class CESCsvReader:
"""read data from csv file df, save it in #* ... | pd.pivot(data=df, index="idx_orig", columns="sensor", values="value") | pandas.pivot |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-07-05 16:53:19
# @Author : mayongze (<EMAIL>)
# @Link : https://github.com/mayongze
# @Version : 1.1.1.20170705
import os
import URPCrawlerDAO
import URPMain
import DBHelper
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
impor... | pd.DataFrame([s14,s15,s16]) | pandas.DataFrame |
"""
This creates Figure 4, fitting of multivalent binding model to Gc Data.
"""
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
from scipy.optimize import minimize
from copy import copy
from .figureCommon import subplotLabel, g... | pd.DataFrame(columns={"Concentration", "Valency", "Accuracy"}) | pandas.DataFrame |
import pytest
import pandas as pd
from xml.etree import ElementTree as ET
from src import *
from src.holiday import *
error_holiday_res = '''<OpenAPI_ServiceResponse>
<cmmMsgHeader>
<returnCode>500</returnCode>
<errMsg>게이트웨이 내부 서비스 오류</errMsg>
</cmmMsgHeader>
</OpenAPI_S... | pd.DataFrame(columns=['date', 'name', 'type', 'is_holiday']) | pandas.DataFrame |
import pandas as pd
import numpy as np
from datetime import timedelta, datetime
from sys import argv
dates=("2020-04-01", "2020-04-08", "2020-04-15", "2020-04-22",
"2020-04-29" ,"2020-05-06", "2020-05-13","2020-05-20", "2020-05-27", "2020-06-03",
"2020-06-10", "2020-06-17", "2020-06-24", "2020-07-01", "2020-07-08",
... | pd.to_datetime(df['data date']) | pandas.to_datetime |
import argparse, time,re, os,csv,functools, signal,sys, json
import logging,datetime, threading,concurrent.futures
from logging import handlers
from time import gmtime, strftime
from urllib.parse import urlparse
from os.path import splitext
import pandas as pd
import numpy as np
# Local Imports
from Lib.GCS.wrapper im... | pd.DataFrame(columns=columns) | pandas.DataFrame |
import streamlit as st
from ..global_data import Constants, load_data, load_pred
import pandas as pd
from pathlib import Path
import datetime
# from sklearn.preprocessing import MinMaxScaler
from covid_forecasting_joint_learning.pipeline import main as Pipeline, sird
from covid_forecasting_joint_learning.data import ... | pd.Series(target.name, index=df.index) | pandas.Series |
import pandas as pd
import numpy as np
import streamlit as st
import plotly.express as px
import folium
import base64
import xlsxwriter
from xlsxwriter import Workbook
from geopy.distance import great_circle
from io import BytesIO
from collections import... | pd.merge(m1, df3, on='zipcode', how='inner') | pandas.merge |
import unittest
import itertools
import os
import pandas as pd
import platform
import numpy as np
import numba
import hpat
from hpat.tests.test_utils import (count_array_REPs, count_parfor_REPs,
count_parfor_OneDs, count_array_OneDs, dist_IR_contains)
from hpat.hiframes.rolling import... | pd.date_range(start='1/1/2018', periods=n, freq='s') | pandas.date_range |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
import requests
import pandas as pd
import json
from tqdm import tqdm
PATH = '../../'
PATH_STATS = "../../data/france/stats/"
# In[5]:
# Download data from Santé publique France and export it to local files
def download_data_hosp_fra_clage():
data = requests.get... | pd.read_csv(PATH + 'data/data_confirmed.csv') | pandas.read_csv |
import unittest
import koleksyon.mcmc as mcmc
import pandas as pd
import numpy as np
import datetime
def artist_costs():
#Artist-Album costs (0.0 represents that you don't buy and albumn, .99 represents you buy just a song)
MichaelJackson = np.array([0.0,0.99,8.64,8.69,12.33,12.96,38.99,30.12,13.99,17.25])
... | pd.read_csv("../data/artist_wiki_page_views-20200101-20201231.csv") | pandas.read_csv |
import pandas as pd
import numpy as np
import os
import math
import random
import pickle
from typing import List, Tuple
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from lightgbm import LGBMRegressor
from progress.bar import Bar
from prismx.utils import read_... | pd.DataFrame() | pandas.DataFrame |
# Copyright 2019-2020 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS"... | pd.DataFrame(X[-n_samples:], columns=intra_nodes) | pandas.DataFrame |
import pandas as pd
import numpy as np
from .cleanning import delFromVardict
# # removed from version 0.0.8, replaced by calculating woe directly inside bitable
# def calcWOE(allGoodCnt, allBadCnt, eachGoodCnt, eachBadCnt):
#
# woe = np.log((eachGoodCnt / eachBadCnt) / (allGoodCnt / allBadCnt))
#
# return woe
... | pd.DataFrame({col: all[col], 'total': good + bad, 'good': good, 'bad': bad}) | pandas.DataFrame |
#!/usr/bin/env python
# coding: utf-8
"""
In this script, the results of the friction tests are visualised.
All visualisations are stored in /figures/
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2021, TU Delft Biomechanical Design"
__credits__ = ["<NAME>, <NAME>, <NAME>"]
__license__ = "CC0-1.0 License"
__ve... | pd.DataFrame(data=fr_s_lc) | pandas.DataFrame |
from __future__ import division
from itertools import combinations
import numpy as np
import pandas as pd
import scipy.integrate
from statsmodels.tools.tools import ECDF
from sklearn import preprocessing
import seaborn as sns
class BaseSample(object):
def __init__(self, data_frame, number_arms=2):
... | pd.DataFrame.copy(data_frame) | pandas.DataFrame.copy |
import pandas as pd
import numpy as np
import csv
import os
import matplotlib.pyplot as plt
## Written by <NAME>
def topspin_to_pd(input_filename):
###row_dict was written by <NAME> ###
Rows = dict()
with open(input_filename) as p:
reader = csv.reader(p, delimiter=" ")
for row in reader:
... | pd.DataFrame() | pandas.DataFrame |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 18:27:38 2021
@author: sergiomarconi
"""
import pandas as pd
from sklearn.preprocessing import normalize
from src.functions_brdf import *
def kld_transform(hsi_cube, kld_out):
#brick = brick.values
kld_groups = | pd.read_csv(kld_out, header=None) | pandas.read_csv |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 9 17:41:26 2020
@author: <NAME>
"""
#Import packages and functions
import pickle
import pandas as pd
import numpy as np
import joblib
from functions import create_ABseries, standardize_data
#Set random seed for replicability
np.random.seed(78937)
#Create 96,000 data se... | pd.DataFrame(svc_results) | pandas.DataFrame |
import copy
import pytest
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
from autogluon.tabular.utils.features import AbstractFeatureGenerator
class GeneratorHelper:
@staticmethod
def fit_transform_assert(input_data: DataFrame, generator: AbstractFeatureGenerator, expected_featu... | Series(['a', 'b', 'a', 'd', 'd', 'd', 'c', np.nan, np.nan]) | pandas.Series |
from PyQt5.QtWidgets import QWidget,QGridLayout, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, QLabel, QPushButton, QMessageBox
from PyQt5.QtGui import QFont, QColor
from PyQt5.QtCore import Qt
import pandas as pd
import numpy as np
class CoreStrategy(QWidget):
def __init__(self):
super(... | pd.DataFrame(index=self.etfs, columns=self.proposed_trade_rownames) | pandas.DataFrame |
import networkx as nx
import numpy as np
import pandas as pd
from quetzal.engine.pathfinder import sparse_los_from_nx_graph
from syspy.assignment import raw as raw_assignment
from tqdm import tqdm
def jam_time(links, ref_time='time', flow='load', alpha=0.15, beta=4, capacity=1500):
alpha = links['alpha'] if 'alph... | pd.merge(los, min_time, on=['origin', 'destination'], suffixes=['', '_minimum']) | pandas.merge |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 19 16:59:12 2021
@author: <NAME>
"""
#IMPORT LIBRARIES------------------------------------------------------------->
import pandas as pd
#LOAD DATA-------------------------------------------------------------------->
"""The data can be located at:
https://www.kag... | pd.read_csv("astronauts.csv") | pandas.read_csv |
'''
Utility scripts
'''
import argparse
import copy
import logging
import sys
import typing
import pandas as pd
_logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
def time_granularity_value_to_stringfy_time_format(granularity_int: int) -> str:
try:
granularity_int = int(granu... | pd.to_datetime(output_df['time']) | pandas.to_datetime |
from itertools import product
import numpy as np
import pytest
from pandas.core.dtypes.common import is_interval_dtype
import pandas as pd
import pandas._testing as tm
class TestSeriesConvertDtypes:
# The answerdict has keys that have 4 tuples, corresponding to the arguments
# infer_objects, convert_string... | pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]) | pandas.to_datetime |
## SETUP ##
## dependencies
import pandas as pd
## logging
sys.stdout = open(snakemake.log[0], 'w')
sys.stderr = open(snakemake.log[0], 'w')
## input files
input_dict = {
'taxlist' : snakemake.input['taxlist'],
'slvmap' : snakemake.input['slvmap'],
'dups' : snakemake.input['dups'],
}
## output files
ou... | pd.DataFrame([[1,"|",1,"|","no rank","|","-","|"]],columns=['taxID','dummy1','targetID','dummy1','rank','dummy1','dummy2','dummy1']) | pandas.DataFrame |
"""Module for data preprocessing.
You can consolidate data with `data_consolidation` and optimize it for example for machine learning models.
Then you can preprocess the data to be able to achieve even better results.
There are many small functions that you can use separately, but there is main function `prepr... | pd.to_datetime(data_for_predictions_df.index) | pandas.to_datetime |
import unittest
import data_profiler as dp
import numpy as np
import pandas as pd
class TestUnstructuredDataLabeler(unittest.TestCase):
# simple test for new default TF model + predict()
def test_fit_with_default_model(self):
data = [
['this is my test sentence.',
{'entities... | pd.DataFrame(data * 50) | pandas.DataFrame |
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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 a... | pd.RangeIndex(2) | pandas.RangeIndex |
'''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] <NAME>, <NAME>, <NAME>, <NAME>
Deep Residual Learning for Image Recognition. arXiv:1512.03385
Please Note that, this version is a hack, it's super hacky, never call this one for normal use
'''
import torch
import torch.nn as n... | pd.isnull(self.full_modules[mod_avail_index].bias) | pandas.isnull |
import sys
from comet_ml import Experiment
from sklearn.metrics import classification_report
from datetime import datetime
from typing import Dict
import pandas as pd
import pickle
import json
import os
import module_results
#_____________________________________________________________________________________________... | pd.DataFrame(hyperparameters_optimizer.cv_results_) | pandas.DataFrame |
import requests
import re
import pandas as pd
import json
def get_webtoon_genre_list():
url = "https://webtoon.p.rapidapi.com/originals/genres/list"
querystring = {"language":"en"}
headers = {
'x-rapidapi-host': "webtoon.p.rapidapi.com",
'x-rapidapi-key': "200898dbd8msh7effe9f4aca8119p1f... | pd.DataFrame(webtoon_json['message']['result']['titleNoListByTabCode']) | pandas.DataFrame |
from abc import ABC, abstractproperty
from collections import namedtuple
from pathlib import Path
import typing as t
import dill
import numpy as np
import pandas as pd
from loguru import logger
from sklearn.pipeline import Pipeline
SentimentType = t.NamedTuple(
"Sentiment",
[
("sentiment", str),
... | pd.DataFrame.sparse.from_spmatrix(v) | pandas.DataFrame.sparse.from_spmatrix |
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_... | DatetimeIndex(['2011-01-01', '2011-01-02'], freq='D') | pandas.DatetimeIndex |
"""
TO-DO:
1. Get all features data sets [X]
2. Add labels to the data sets[X]
3. Obtain results of the training ( of all three algos)[X]
4. Obtain the plots and confussion matrix[]
"""
from pathlib import Path
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
impo... | pd.DataFrame() | pandas.DataFrame |
import os
from multiprocessing import Pool
import pandas as pd
import numpy as np
import vcf
from pysam import AlignmentFile
class Extract:
"""
Class for extracting genotype information from alignment file using
the user supplied VCF file.
"""
def __init__(self, args):
self.db = args.dat... | pd.DataFrame(region_counts) | pandas.DataFrame |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def plot_rec_results(self, metric_name='recall'):
""" self is an instance of Experiment or ExperimentResult """
ir = pd.DataFrame(self.item_rec).T
ur = | pd.DataFrame(self.user_rec) | pandas.DataFrame |
#!/usr/bin/env python
#
# Script for 5' assignment of 5'P-Seq data
# input is BAM file must contain NH tag
# reads with the tag NH:i:1 only included
# output 1: raw counts in *_iv.h5 - single indexed
# output 2: normalised RPM in _idx_iv.h5 - double indexed
#
__author__ = "<NAME>"
__copyright__ = "Copyr... | pd.HDFStore(infile, "r") | pandas.HDFStore |
#! python3
"""Process data acquired from the Malvern Mastersizer 2000. The csv output contains lots of factor information with the numeric data towards the end. A common feature of the classes and modules is to split thse datasets into associate 'head' and 'data' subsets so that the numerical data can be processed i... | pd.concat([col1, col2], axis=1) | pandas.concat |
import operator
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays.numpy_ import PandasDtype
from .base import BaseExtensionTests
class BaseSetitemTests(BaseExtensionTests):
def test_setitem_scalar_series(self, data, box_in_series):
i... | pd.Series(data) | pandas.Series |
import anonypy
import pandas as pd
data = [
[6, "1", "test1", "x", 20],
[6, "1", "test1", "x", 30],
[8, "2", "test2", "x", 50],
[8, "2", "test3", "w", 45],
[8, "1", "test2", "y", 35],
[4, "2", "test3", "y", 20],
[4, "1", "test3", "y", 20],
[2, "1", "test3", "z", 22],
[2, "2", "test3... | pd.DataFrame(rows) | pandas.DataFrame |
"""
Function to do speed tests easily.
"""
import numpy as np
import pandas as pd
from timeit import default_timer
def speedtest(speed_inputs, speed_input_labels, funcs):
"""
Runs speed tests, and asserts outputs are all the same. Runs the first test before timing anything to make sure
numba functions... | pd.DataFrame(func_times, columns=speed_input_labels, index=[f.__name__ for f in funcs]) | pandas.DataFrame |
# Copyright (c) 2020 ING Bank N.V.
#
# 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, distr... | pd.DataFrame(columns=self.iterations_columns) | pandas.DataFrame |
# -*- 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(isolamento.data) | pandas.to_datetime |
# coding: utf-8
# Copyright (c) <NAME>.
# Distributed under the terms of the MIT License.
"""
This module implements utility functions for other modules in the package.
"""
import string
from io import StringIO
import os
import re
import math
import sys
from typing import List, Dict, Union, Tuple, Optional, Any
from... | pd.read_table(f_xyz, skiprows=2, delim_whitespace=True, names=["atom", "x", "y", "z"]) | pandas.read_table |
import pandas as pd
import numpy as np
# import tensorflow as tf
import tensorflow.compat.v1 as tf
def data_prepare():
tf.disable_v2_behavior()
ratings_df = | pd.read_csv('./ml-latest-small/ratings.csv') | pandas.read_csv |
import logging, os, time, multiprocessing, sys, signal
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
import gym
import pybullet, pybullet_envs, pybullet_data
import numpy as np
import pandas as pd
from stable_baselines.sac.policies import MlpPolicy
from stable_bas... | pd.DataFrame() | pandas.DataFrame |
#!/usr/bin/python3
import json
import sys
import subprocess
import pandas
import os
import shutil
import pprint
from deepdiff import DeepDiff
current_report = "/opt/ptx/trivy/reports_raw/current_report.json"
last_known = "/opt/ptx/trivy/last_known/last_output.json"
severity = "HIGH,CRITICAL"
def run_cmd(cmd):
cm... | pandas.DataFrame(vulnerabilities) | pandas.DataFrame |
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
import datetime
import operator
import re
import cupy as cp
import numpy as np
import pandas as pd
import pytest
import cudf
from cudf.core._compat import PANDAS_GE_120
from cudf.testing import _utils as utils
from cudf.testing._utils import assert_eq, assert_exceptions... | pd.Timedelta(days=i) | pandas.Timedelta |
import pandas as pd
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
from collections import Counter
import csv
import itertools as IT
import operator
def preprocessing():
train = pd.read_csv('original_dataset.csv')
newdict = {'status... | pd.DataFrame(newdict) | pandas.DataFrame |
import numpy as np
import pandas as pd
from decisionengine.framework.modules import Source
PRODUCES = ["provisioner_resources"]
class ProvisionerResourceList(Source.Source):
def __init__(self, *args, **kwargs):
pass
def produces(self, schema_id_list):
return PRODUCES
# The DataBlock g... | pd.DataFrame(pandas_data) | pandas.DataFrame |
"""
Updated on Thursday December 10th, 2020
@author: <NAME>
The object of this script is to perform the following tasks:
1. Grab the current List of S&P 500 Company Tickers
2. Using the Yahoo Finance API, Download all the data for a given time period
and save them to a csv. (open, high, low, close,volume, dividend... | pd.DataFrame(tickers) | pandas.DataFrame |
# %load training_functions.py
import pandas as pd
import os
import numpy as np
from datetime import datetime
import json
from os import listdir
from os.path import isfile, join
def pdf(data):
return pd.DataFrame(data)
def read_csv_power_file(file_path, filename):
csv_path = os.path.join(file_path, filename)
... | pd.read_csv(csv_path) | pandas.read_csv |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
from copy import deepcopy
from sklearn.utils import shuffle
from tqdm import tqdm
############ Make test networks ############
def make_triangonal_net():
"""
Make a triangonal network.
"""
dict_node... | pd.DataFrame(data=None, index=uniq, columns=uniq) | pandas.DataFrame |
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtWidgets import QTabWidget
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWid... | pd.read_csv('../../data/studentAssessment.csv') | pandas.read_csv |
from .base import Controller
from .base import Action
import numpy as np
import pandas as pd
import logging
from collections import namedtuple
from tqdm import tqdm
logger = logging.getLogger(__name__)
CONTROL_QUEST = 'simglucose/params/Quest.csv'
PATIENT_PARA_FILE = 'simglucose/params/vpatient_params.csv'
ParamTup = ... | pd.read_csv(CONTROL_QUEST) | pandas.read_csv |
import datetime as dt
import pandas as pd
import numpy as np
def OpenFace(openface_features, PID, EXP):
"""
Tidy up OpenFace features in pandas data.frame to be stored in sqlite
database:
- Participant and experiment identifiers are added as columns
- Underscores in column names are removed, becaus... | pd.to_datetime(t) | pandas.to_datetime |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import normalize
from xgboost import XGBClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import confusion_matrix
# read data sets
train = pd.r... | pd.read_csv(r"E:\MyDrive-2\DataScience\av-amexpert\item_data.csv") | pandas.read_csv |
#!/usr/bin/env python
# coding: utf-8
# # Scenario
#
# As an analyst for OilyGiant mining company our task is to find the best place for a new well.
#
# We will use several techniques, including machine learning and bootstrapping, to select the region with the highest profit margin.
#
# Machine learning prediction... | pd.read_csv('/datasets/geo_data_2.csv') | pandas.read_csv |
__author__ = "<NAME>"
__license__ = 'MIT'
# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS
# Modules
import pandas as pd
import os
from matplotlib import pyplot as plt
import numpy as np
from scipy.stats import linregress
import datetim... | pd.read_hdf(temperature_file, key=acro_key) | pandas.read_hdf |
import datetime
import numpy as np
import pytest
import pytz
import pandas as pd
from pandas import Timedelta, merge_asof, read_csv, to_datetime
import pandas._testing as tm
from pandas.core.reshape.merge import MergeError
class TestAsOfMerge:
def read_data(self, datapath, name, dedupe=False):
path = da... | merge_asof(trades, quotes, on="time", by="ticker") | pandas.merge_asof |
# pylint: disable=E1101
from datetime import datetime
import datetime as dt
import os
import warnings
import nose
import struct
import sys
from distutils.version import LooseVersion
import numpy as np
import pandas as pd
from pandas.compat import iterkeys
from pandas.core.frame import DataFrame, Series
from pandas.c... | DataFrame([["1"], [""]], columns=["foo"]) | pandas.core.frame.DataFrame |
# Copyright (c) 2018-2021, NVIDIA CORPORATION.
import array as arr
import datetime
import io
import operator
import random
import re
import string
import textwrap
from copy import copy
import cupy
import numpy as np
import pandas as pd
import pyarrow as pa
import pytest
from numba import cuda
import cudf
from cudf.c... | pd.Series([], dtype="str") | pandas.Series |
from .vcfwrapper import VCFWrapper, get_samples_from_vcf
from .annotation_parser import VEPAnnotation
from .cli import InputFile, error, warning, info
from .filters import VariantFilter, AnnotationFilter
from cyvcf2 import VCF
from scipy import stats, mean
import pandas as pd
import numpy as np
import matplotlib.pyplo... | pd.DataFrame(vtypes_hist) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 29 10:57:09 2021
@author: luis
"""
# Regresión lineal múltiple en Spyder con Python
# Cómo importar las librerías
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
print("LIBRERÍAS IMPORTADAS")
# Importar el data set
dataset = pd.read_csv('50_Start... | pd.DataFrame({'Actual': y_test, 'Predicted': y_pred}) | pandas.DataFrame |
from datetime import datetime
import numpy as np
from pandas.tseries.frequencies import get_freq_code as _gfc
from pandas.tseries.index import DatetimeIndex, Int64Index
from pandas.tseries.tools import parse_time_string
import pandas.tseries.frequencies as _freq_mod
import pandas.core.common as com
import pandas.core... | _gfc(self.freq) | pandas.tseries.frequencies.get_freq_code |
from collections import OrderedDict
import datetime
from datetime import timedelta
from io import StringIO
import json
import os
import numpy as np
import pytest
from pandas.compat import is_platform_32bit, is_platform_windows
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame... | pd.read_json(v12_json) | pandas.read_json |
import pathlib
import pytest
import pandas as pd
import numpy as np
import gradelib
EXAMPLES_DIRECTORY = pathlib.Path(__file__).parent / "examples"
GRADESCOPE_EXAMPLE = gradelib.Gradebook.from_gradescope(
EXAMPLES_DIRECTORY / "gradescope.csv"
)
CANVAS_EXAMPLE = gradelib.Gradebook.from_canvas(EXAMPLES_DIRECTORY ... | pd.Series(data=[1, 30, 90, 20], index=columns, name="A1") | pandas.Series |
import pandas
from bokeh.plotting import figure, gridplot
from bokeh.embed import components
from bokeh.models import HoverTool, TapTool, OpenURL, WheelZoomTool
from bokeh.models import GMapPlot, GMapOptions
from bokeh.tile_providers import CARTODBPOSITRON, get_provider
from cached_property import cached_property_wit... | pandas.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv') | pandas.read_csv |
import pandas as pd
import numpy as np
csv_path = "./tweets.csv"
save_path = "./fixed_tweets.csv"
df = | pd.read_csv(csv_path, header=None) | pandas.read_csv |
import os
import sys
import inspect
from copy import deepcopy
import numpy as np
import pandas as pd
from ucimlr.helpers import (download_file, download_unzip, one_hot_encode_df_, xy_split,
normalize_df_, split_normalize_sequence, split_df, get_split, split_df_on_column)
from ucimlr.datase... | pd.read_csv(file_path) | pandas.read_csv |
from distutils.version import LooseVersion
from warnings import catch_warnings
import numpy as np
import pytest
from pandas._libs.tslibs import Timestamp
import pandas as pd
from pandas import (
DataFrame,
HDFStore,
Index,
MultiIndex,
Series,
_testing as tm,
bdate_range,
concat,
d... | tm.assert_frame_equal(result, expected) | pandas._testing.assert_frame_equal |
"""A collection of Methods to support the Change History feature in DFCX."""
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licens... | pd.DataFrame.from_records(data=change_logs) | pandas.DataFrame.from_records |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2014-2019 OpenEEmeter contributors
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/LIC... | pd.date_range("2017-01-01", periods=100, freq="MS", tz="UTC") | pandas.date_range |
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... | pd.to_datetime(futures_chain_tickers.index) | pandas.to_datetime |
import pandas as pd
from conftest import assert_frame_equal
import numpy as np
from numpy import dtype, nan
import pytest
from pvlib.iotools import crn
from conftest import DATA_DIR
@pytest.fixture
def columns():
return [
'WBANNO', 'UTC_DATE', 'UTC_TIME', 'LST_DATE', 'LST_TIME', 'CRX_VN',
'longitu... | pd.DataFrame(values, columns=columns, index=index) | pandas.DataFrame |
'''
This script exctracts training variables from all logs from
tensorflow event files ("event*"), writes them to Pandas
and finally stores in long-format to a CSV-file including
all (readable) runs of the logging directory.
The magic "5" infers there are only the following v.tags:
[lr, loss, acc, val_loss, val_acc]
... | pd.DataFrame() | pandas.DataFrame |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# In[2]:
def load_and_process(path):
data = pd.read_csv(path)
newdf = (
pd.DataFrame(data)
.rename(columns={"alcohol": "Alc"}) #Abbreviating lo... | pd.read_csv(path) | pandas.read_csv |
"""
Trading environment class
data: 12/10/2017
author: Tau
"""
from ..datafeed import *
from ..spaces import *
from .utils import *
from ..utils import *
from ..core import Env
import os
import smtplib
from socket import gaierror
from datetime import datetime, timedelta, timezone
from decimal import localcontext, ROUN... | pd.concat(obs_list, keys=keys, axis=1) | pandas.concat |
## parse TCGA data
import pandas as pd
from collections import defaultdict
import numpy as np
import scipy.stats as stat
import os, time
def TCGA_ssGSEA(cancer_type, parse_reactome=True, simplify_barcode=True):
'''
Input
cancer_type: 'BLCA', 'SKCM' (melanoma), 'STAD' (gastric cancer)
simplify_barcode: if True, dup... | pd.read_csv('%s/TCGA-%s/TMM_rna_seq.txt'%(fi_dir, cancer_type), sep='\t') | pandas.read_csv |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2021/12/31 13:19
Desc: 股票指数成份股数据, 新浪有两个接口, 这里使用老接口:
新接口:http://vip.stock.finance.sina.com.cn/mkt/#zhishu_000001
老接口:http://vip.stock.finance.sina.com.cn/corp/view/vII_NewestComponent.php?page=1&indexid=399639
"""
import math
from io import BytesIO
import pandas as... | o_datetime(temp_df['日期'], format="%Y%m%d") | pandas.to_datetime |
#!/usr/bin/env python
# coding: utf-8
import os
import copy
import pandas
from os.path import join
from pandas.core.frame import DataFrame
from MyPythonDocx import *
def cal_va(df):
# df = DataFrame(page[1:], columns=page[0])
severity = ['嚴重', '高', '中', '低', '無']
vas = []
for idx in range(5):
... | DataFrame(page[1:], columns=page[0]) | pandas.core.frame.DataFrame |
# -*- coding: utf-8 -*-
# Arithmetc tests for DataFrame/Series/Index/Array classes that should
# behave identically.
from datetime import timedelta
import operator
import pytest
import numpy as np
import pandas as pd
import pandas.util.testing as tm
from pandas.compat import long
from pandas.core import ops
from pan... | tm.box_expected(tdser, box) | pandas.util.testing.box_expected |
import os
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
# from sklearn.preprocessing import StandardScaler
from utils.tools import StandardScaler
from utils.timefeatures import time_features
import warnings
warnings.filterwarnings('ignore')
class Dataset_ETT_ho... | pd.date_range(tmp_stamp.date.values[-1], periods=self.pred_len+1, freq=self.freq) | pandas.date_range |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
NAME:
debug_inp.py
DESCRIPTION:
debugs and fixes with user input .inp format files of CIT (sam file) type data.
SYNTAX:
~$ python debug_inp.py $INP_FILE
FLAGS:
-h, --help:
prints this help message
-dx, --dropbox:
Prioritize user's... | pd.Series([t[0:-1] for t in the_rest]) | pandas.Series |
# -*- coding: utf-8 -*-
import pytest
import os
import numpy as np
import pandas as pd
from pandas.testing import assert_frame_equal, assert_series_equal
import numpy.testing as npt
from numpy.linalg import norm, lstsq
from numpy.random import randn
from flaky import flaky
from lifelines import CoxPHFitter, WeibullA... | pd.DataFrame([[40, 28], [25, 15]], index=[0.2, 0.5], columns=["sf", "sf**2"]) | pandas.DataFrame |
'''
1. 자음,모음,특수문자 제거 (온점, 쉼표 포함)
2. 띄어쓰기 교정
3. 단어 수정
4. 형태소분석기로 명사 and 형용사 추출
5. Fasttext embedding
- 사전 추가
'''
from chatspace import ChatSpace
from gensim.models import FastText
from konlpy.tag import Kkma
import json
import re
import pandas as pd
import numpy as np
class GlowpickPreprocessing(object):
def ... | pd.Series(x) | pandas.Series |
import glob
import math
import brewer2mpl
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.lines import Line2D
from matplotlib.ticker import MultipleLocator
SPINE_COLOR = 'gray'
#####################################################
# Process average from fi... | pd.concat(dfs3, axis=1) | pandas.concat |
import numpy as np
import pytest
from pandas import DataFrame, Series, concat, isna, notna
import pandas._testing as tm
import pandas.tseries.offsets as offsets
@pytest.mark.parametrize(
"compare_func, roll_func, kwargs",
[
[np.mean, "mean", {}],
[np.nansum, "sum", {}],
[lambda x: np... | Series([np.NaN] * 9) | pandas.Series |
"""Tests suite for Period handling.
Parts derived from scikits.timeseries code, original authors:
- <NAME> & <NAME>
- pierregm_at_uga_dot_edu - mattknow_ca_at_hotmail_dot_com
"""
from unittest import TestCase
from datetime import datetime, timedelta
from numpy.ma.testutils import assert_equal
from pandas.tseries.p... | PeriodIndex(freq='M', start='1/1/2001', end='12/1/2009') | pandas.tseries.period.PeriodIndex |
import json
import pandas as pd
import os
test_score = "tianchi_datasets/test.json"
train_data = "tianchi_datasets/track3_round1_train.tsv"
test_data = "tianchi_datasets/track3_round1_testA.tsv"
def create_new_traindata(test_score, train_data, test_data):
tmp = []
dir_path = os.getcwd()
with open(os.path.... | pd.concat([train, test], axis=0) | pandas.concat |
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns##data visualization資料視覺化
import warnings
import gc##garbage collector interface
warnings.simplefilter('ignore')
matplotlib.rcParams['figure.dpi'] = 100
sns.set()
building = pd.read_csv(r'C:\Users\Lab408\Deskto... | pd.read_csv(r'C:\Users\Lab408\Desktop\try_model_ashrae_energy_prediction_kaggle/test_smallest_data.csv') | pandas.read_csv |
import pickle
from datetime import datetime
import re
import time
import getpass
import os
import sys
import re
#requirements
import json
import pandas as pd
import helium as h
from selenium.common.exceptions import NoSuchElementException
import pathlib
pd.set_option("max_rows",100)
#pd.set_option("display.max_column... | pd.read_html(browser.page_source,attrs={'class':'table'}) | pandas.read_html |
import pandas as pd
import numpy as np
from scipy import sparse
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import patches
import matplotlib.colors as colors
import textwrap
import re
class DrawGroup:
def __init__(self):
self.theta_1 = np.pi * 0.7
self.angle_margin = 3 * ... | pd.DataFrame({"src": src, "trg": trg, "w": w}) | pandas.DataFrame |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.