prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__all__ = ['load_data', 'shape_shower', 'location_max_finder', 'differentiate', 'intensity_direction_shower', 'write_data', 'mix_pics']
import io
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
sys.stdout = io.TextIOWrapper(sys.stdout.bu... | pd.ExcelWriter(address) | pandas.ExcelWriter |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pandas as pd
import requests
UTAHAQ_API_BASE_URI = 'http://meso2.chpc.utah.edu/aq/cgi-bin/download_mobile_archive.cgi'
UTAHAQ_API_TOKEN = os.getenv('UTAHAQ_API_TOKEN')
def _utahaq_batch_get(stid: str,
yr: int,
... | pd.read_csv(uri, skiprows=True) | pandas.read_csv |
__author__ = '<NAME>'
__email__ = '<EMAIL>'
########################################
# imports
########################################
import networkx as nx
from tqdm.autonotebook import tqdm
import pandas as pd
from itertools import product
########################################
# Feature Extractor
############... | pd.DataFrame.from_dict(edges_dict, orient='index') | pandas.DataFrame.from_dict |
import pandas as pd
import numpy as np
import pycountry_convert as pc
import pycountry
import os
from iso3166 import countries
PATH_AS_RELATIONSHIPS = '../Datasets/AS-relationships/20210701.as-rel2.txt'
NODE2VEC_EMBEDDINGS = '../Check_for_improvements/Embeddings/Node2Vec_embeddings.emb'
DEEPWALK_EMBEDDINGS_128 = '../... | pd.read_csv(DEEPWALK_EMBEDDINGS_128, sep=',') | pandas.read_csv |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 4 10:30:17 2018
@author: avelinojaver
"""
from tierpsy.features.tierpsy_features.summary_stats import get_summary_stats
from tierpsy.summary.helper import augment_data, add_trajectory_info
from tierpsy.summary.filtering import filter_trajectories
fr... | pd.DataFrame(worm_feats) | pandas.DataFrame |
from collections import namedtuple
from pathlib import Path
import logging
import numpy as np
import pandas as pd
import scipy
from . import (
ctd_plots,
get_ctdcal_config,
flagging,
process_ctd,
oxy_fitting,
)
cfg = get_ctdcal_config()
log = logging.getLogger(__name__)
RinkoO2Cal = namedtuple("... | pd.DataFrame(columns=["c0", "c1", "c2", "d0", "d1", "d2", "cp"]) | pandas.DataFrame |
'''
@author : <NAME>
ML model for foreign exchange prediction
'''
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import joblib
def getFxRatesForPairs(pairName):
df = pd.read_csv("C:\\Users\\Srivastava_Am\\PycharmProjects\\exchange-rate-prediction\\data_source\\fx_rates_a... | pd.merge(aus_gdp, usa_gdp, on="month_year", how="inner") | pandas.merge |
##? not sure what this is ...
from numpy.core.numeric import True_
import pandas as pd
import numpy as np
## this function gives detailed info on NaN values of input df
from data_clean import perc_null
#these functionas add a date column (x2) and correct mp season format
from data_fix_dates import game_add_mp_date... | pd.read_excel(io = betting_path+'nhl odds 2010-11.xlsx') | pandas.read_excel |
'''
Scripts for loading various experimental datasets.
Created on Jul 6, 2017
@author: <NAME>
'''
import os
import re
import sys
import pandas as pd
import numpy as np
import glob
from sklearn.feature_extraction.text import CountVectorizer
from evaluation.experiment import Experiment
def convert_argmin(x):
... | pd.read_csv(savepath + './text.csv', skip_blank_lines=False, header=None) | pandas.read_csv |
import requests
import pandas as pd
import world_bank_data as wb
import lxml
def wb_corr(data, col, indicator, change=False):
pd.options.mode.chained_assignment = None # Change option within function to avoid warning of value being placed on a copy of a slice.
"""
Returns the relationship that an input v... | pd.DataFrame() | pandas.DataFrame |
# To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting
# ms-python.python added
import os
try:
os.chdir(os.path.join(os.getcwd(), 'as... | pd.DataFrame(dct) | pandas.DataFrame |
import numpy as np
import anndata as ad
import pandas as pd
def load_met_noimput(matrix_file, path='', save=False):
"""
read the raw count matrix and convert it into an AnnData object.
write down the matrix as .h5ad (AnnData object) if save = True.
Return AnnData object
"""
matrix = []
cell... | pd.DataFrame(index=name_windows_covered) | pandas.DataFrame |
from __future__ import division
import configparser
import logging
import os
import re
import time
from collections import OrderedDict
import numpy as np
import pandas as pd
import scipy.interpolate as itp
from joblib import Parallel
from joblib import delayed
from matplotlib import pyplot as plt
from pyplanscoring.... | pd.DataFrame(self.delta_dvh_pp, columns=['delta_pp']) | pandas.DataFrame |
import gc
import warnings
import numpy as np
import pandas as pd
warnings.simplefilter(action='ignore', category=FutureWarning)
# One-hot encoding for categorical columns with get_dummies
def one_hot_encoder(df, nan_as_category=True):
original_columns = list(df.columns)
categorical_columns = [col for col in... | pd.factorize(df[bin_feature]) | pandas.factorize |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# *****************************************************************************/
# * Authors: <NAME>
# *****************************************************************************/
"""transformCSV.py
This module contains the basic functions for creating the content of... | pandas.StringDtype() | pandas.StringDtype |
"""Miscellaneous internal PyJanitor helper functions."""
import functools
import os
import sys
import warnings
from typing import Callable, Dict, List, Union
import numpy as np
import pandas as pd
from .errors import JanitorError
def check(varname: str, value, expected_types: list):
"""
One-liner syntactic... | pd.DataFrame(value) | pandas.DataFrame |
# pylint: disable-msg=E1101,W0612
from datetime import datetime, time, timedelta, date
import sys
import os
import operator
from distutils.version import LooseVersion
import nose
import numpy as np
randn = np.random.randn
from pandas import (Index, Series, TimeSeries, DataFrame,
isnull, date_ran... | assert_series_equal(result, s.ix[:60]) | pandas.util.testing.assert_series_equal |
import numpy as np
import pandas as pd
from sklearn import preprocessing
from keras.layers.core import Dense, Dropout, Activation
from keras.activations import linear
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from matplotlib import pyplot
#read and prepare data from datafile
data_fil... | pd.DataFrame(pred1) | pandas.DataFrame |
#!/usr/bin/env python
# PROGRAM: plot_sst.py
# ----------------------------------------------------------------------------------
# Version 0.18
# 19 August, 2019
# michael.taylor AT reading DOT ac DOT uk
# PYTHON DEBUGGER CONTROL:
#------------------------
# import os; os._exit(0)
# import ipdb
# ipdb.set_trace()
i... | pd.Series(ds['n_sst_q4'].values[idx], index=t) | pandas.Series |
import unittest
import pandas as pd
import pandas.util.testing as pt
import tia.util.fmt as fmt
def tof(astr):
return float(astr.replace(",", ""))
class TestFormat(unittest.TestCase):
def ae(self, expected, fct, value, **kwargs):
cb = fct(**kwargs)
actual = cb(value)
self.assertEqual... | pd.Series([2.1 * m, -20.1 * m, 200.1 * m]) | pandas.Series |
# coding: utf-8
# author: wamhanwan
"""Tushare API"""
import tushare as ts
import pandas as pd
import numpy as np
from time import sleep
from FactorLib.utils.tool_funcs import get_members_of_date
from functools import update_wrapper
_token = '6135b90bf40bb5446ef2fe7aa20a9467ad10023eda97234739743f46'
SHEXG... | pd.concat(df) | pandas.concat |
def ConvMAT2CSV(rootDir, codeDir):
"""
Written by <NAME> and <NAME> to work with macOS/Unix-based systems
Purpose: Extract data from .mat files and format into DataFrames
Export as csv file
Inputs: PythonData.mat files, animalNotes_baselines.mat file
Outputs: .csv files
... | pd.DataFrame() | pandas.DataFrame |
"""Yahoo Finance view"""
__docformat__ = "numpy"
import os
import pandas as pd
from matplotlib import pyplot as plt
from tabulate import tabulate
from gamestonk_terminal.etf import yfinance_model
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_ter... | pd.DataFrame(sectors, index=[0]) | pandas.DataFrame |
import datetime as dt
import pandas as pd
from .. import AShareDataReader, DateUtils, DBInterface, utils
from ..config import get_db_interface
class IndustryComparison(object):
def __init__(self, index: str, industry_provider: str, industry_level: int, db_interface: DBInterface = None):
if not db_interf... | pd.concat([ratio, industry_info], join='inner', axis=1) | pandas.concat |
# --------------
#Importing header files
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Code starts here
#Code ends here
data=pd.read_csv(path)
#Plotting histogram of Rating
data['Rating'].plot(kind='hist')
plt.show()
#Subsetting the dataframe based on `Rating` column
data=data[da... | pd.DataFrame({'Total':total_null_1,'Percent':percent_null_1}) | pandas.DataFrame |
import os
import re
import warnings
import matplotlib.pyplot as plt
from numpy import array, isnan
import pandas as pd
import pyflux as pf
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.stattools import kpss
warnings.simplefilter("ignore")
from datetime import datetime
def adf_test(timeseries):... | pd.set_option('display.max_columns', None) | pandas.set_option |
"""
Base and utility classes for pandas objects.
"""
import textwrap
import warnings
import numpy as np
import pandas._libs.lib as lib
import pandas.compat as compat
from pandas.compat import PYPY, OrderedDict, builtins, map, range
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMetho... | compat.OrderedDict() | pandas.compat.OrderedDict |
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
import pandas as pd
import numpy as np
pio.templates.default = "simple_white"
EXPECTED_VALUE = 10
VARIANCE = 1
NUM_OF_SAMPLES = 1000
SAMPLES_DIFF = 10
DIFF_COL = '... | pd.DataFrame(results, columns=[F1_COL, F3_COL, LOG_LIKELIHOOD_COL]) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 09:40:28 2022
@author: Featherine
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as md
df = pd.read_csv('features - Final.csv')
df = df.fillna(0)
# df = df[0:48]
df['DateTime'] = pd.to_datetime(... | pd.Timedelta(1,'h') | pandas.Timedelta |
import pytest
import pytz
import dateutil
import numpy as np
from datetime import datetime
from dateutil.tz import tzlocal
import pandas as pd
import pandas.util.testing as tm
from pandas import (DatetimeIndex, date_range, Series, NaT, Index, Timestamp,
Int64Index, Period)
class TestDatetimeInd... | DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN]) | pandas.DatetimeIndex |
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/04_Create_Acs_Indicators.ipynb (unless otherwise specified).
__all__ = ['getColName', 'getColByName', 'addKey', 'nullIfEqual', 'sumInts', 'age5', 'age18', 'age24', 'age64', 'age65',
'bahigher', 'carpool', 'drvalone', 'elheat', 'empl', 'fam', 'female', 'f... | pd.DataFrame() | pandas.DataFrame |
# # Explore overfitting and underfitting
# # (https://www.tensorflow.org/alpha/tutorials/keras/overfit_and_underfit)
import altair as alt
import numpy as np
import pandas as pd
from tensorflow import keras
# ## Download the IMDB dataset
# !Multi-hot-encoding
NUM_WORDS = 10000
(train_data, train_labels), (test_data,... | pd.DataFrame({"label": train_data[0]}) | pandas.DataFrame |
#definition of add_dataset that creates the meta-dataset
import pandas as pd
from pandas.core.dtypes.common import is_numeric_dtype
from scipy.stats import pearsonr
from sklearn.model_selection import train_test_split
from supervised.automl import AutoML
import os
import pandas as pd
from sklearn.preprocessing import L... | pd.concat([df, df_automl_results]) | pandas.concat |
import pandas as pd
def cat_lump(x, n=5, prop=None, other_level="Other"):
"""
Lump together least common categories into an "Other" category
Parameters
----------
x : pd.Series
series to be modified
n : int
number of levels to preserve
prop : float
optional instead of n. ... | pd.Series(x) | pandas.Series |
import act
import requests
import json
import glob
import pandas as pd
import datetime as dt
import numpy as np
import xarray as xr
import dask
import matplotlib.pyplot as plt
import textwrap
from matplotlib.dates import DateFormatter
from matplotlib.dates import HourLocator
def get_doi(site, dsname, c_start, c_end)... | pd.to_datetime(obj['time'].values[-1]) | pandas.to_datetime |
'''
Functions for calculating soiling metrics from photovoltaic system data.
The soiling module is currently experimental. The API, results,
and default behaviors may change in future releases (including MINOR
and PATCH releases) as the code matures.
'''
import warnings
import pandas as pd
import numpy as np
from sci... | pd.date_range(start, end) | pandas.date_range |
import pandas as pd
from texthero import representation
from texthero import preprocessing
from . import PandasTestCase
import doctest
import unittest
import string
"""
Test doctest
"""
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(representation))
return tests
class TestRepr... | pd.Series([[1, 0], [0, 1]]) | pandas.Series |
from __future__ import division
import pytest
import numpy as np
from pandas import (Interval, IntervalIndex, Index, isna,
interval_range, Timestamp, Timedelta,
compat)
from pandas._libs.interval import IntervalTree
from pandas.tests.indexes.common import Base
import pandas.uti... | IntervalIndex.from_arrays([0, 2], [1, 3]) | pandas.IntervalIndex.from_arrays |
#!/usr/bin/env python
# coding: utf-8
# usage:
# python gen_csv_denoised_pad_train_val.py 200015779
import sys
import pandas as pd
import numpy as np
try:
val_label = sys.argv[1]
except:
print("specify book name for validation")
sys.exit(1)
df_train = pd.read_csv('./input/train_characters.csv', header=N... | pd.concat(add_val_df_list) | pandas.concat |
# Copyright 2020, <NAME>, <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
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF A... | pd.DataFrame() | pandas.DataFrame |
import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import urlopen
import pandas as pd
from pandas.tseries.offsets import DateOffset
def from_download(tok, start_date, end_date, offset_days, series_list):
"""Download and assemble dataset of demand data per balancing authority f... | pd.to_datetime(df["Date"]) | pandas.to_datetime |
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
import random
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('3.142.167.4', 15271))
# client.connect(('127.0.0.1', 60000))
import rss22
p... | pd.DataFrame(columns=[0,1,2,3]) | pandas.DataFrame |
from __future__ import print_function
import pandas as pd
import numpy as np
import tensorflow as tf
import os
import shutil
import copy
from time import time
from datetime import timedelta
import h5py
tf.compat.v1.disable_eager_execution()
'''
CHRONOS: population modeling of CRISPR readcount data
<NAME> (<EMAIL>)
T... | pd.DataFrame({self.pDNA_unique[key][0]: batch.iloc[0]}) | pandas.DataFrame |
'''
Run this to get html files
This file contains code to obtain html data from oslo bors and yahoo finance
'''
import argparse
import re
import threading
import time
from pprint import pprint
from typing import List
import sys
import pathlib
import os
import numpy as np
import pandas as pd
import pypatconsole as ppc... | to_numeric(df.last_, errors='coerce') | pandas.to_numeric |
#!/usr/bin/python
from threading import Thread
from threading import Lock
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
import json
from urllib import parse
import pandas as pd
import csv
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas imp... | pd.read_csv('./data/' + job + '.csv', usecols=['seq', 'value']) | pandas.read_csv |
from collections import OrderedDict
from datetime import datetime, timedelta
import numpy as np
import numpy.ma as ma
import pytest
from pandas._libs import iNaT, lib
from pandas.core.dtypes.common import is_categorical_dtype, is_datetime64tz_dtype
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
Da... | pd.period_range("2012Q1", periods=3, freq="Q") | pandas.period_range |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from kneed import KneeLocator
from jupyter_utils import AllDataset
data_dir = '../drp-data/'
GDSC_GENE_EXPRESSION = 'preprocessed/gdsc_tcga/gdsc_rma_gene_expr.csv'
TCGA_GENE_EXPRESSION = 'preprocessed/gdsc_tcga/tcga_log2_gene_expr.csv'
TCGA_CANCER... | pd.DataFrame(columns=drugs) | pandas.DataFrame |
import math
import numpy as np
import matplotlib.pyplot as plt
import argparse
import logging
import sys
import pandas as pd
from scipy import integrate
def parse_args():
parser = argparse.ArgumentParser("Compute precession of orbits")
parser.add_argument('--config', type=str, default="config.yml",
... | pd.DataFrame(solution.y) | pandas.DataFrame |
__author__ = "<NAME>"
import os
import re
import gzip
import logging
import pandas
import csv
from .Exceptions import ReportableException
def folder_contents(folder, pattern=None):
regexp = re.compile(pattern) if pattern else None
p = os .listdir(folder)
if regexp: p = [x for x in p if regexp.search(x)]
... | pandas.to_numeric(data[k]) | pandas.to_numeric |
import warnings
import pandas_datareader as web
import numpy as np
import pandas as pd
from sklearn import metrics # for the check the error and accuracy of the model
from sklearn.metrics import (
confusion_matrix,
classification_report,
r2_score,
accuracy_score,
r2_score,
)
from sklearn.model_sele... | pd.set_option("display.width", 150) | pandas.set_option |
import pandas as pd
from collections import Counter
from natsort import index_natsorted
import numpy as np
ids = []
text = []
ab_ids = []
ab_text = []
normal_vocab_freq_dist = Counter()
ab_vocab_freq_dist = Counter()
# keywords that most likely associated with abnormalities
KEYWORDS = ['emphysema', 'cardiomegaly', '... | pd.DataFrame(normal) | pandas.DataFrame |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2018 Open Energy Efficiency, 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/LICE... | pd.notnull(ts[-1]) | pandas.notnull |
import numpy as np
import pandas as pd
from numba import njit
import pytest
import os
from collections import namedtuple
from itertools import product, combinations
from vectorbt import settings
from vectorbt.utils import checks, config, decorators, math, array, random, enum, data, params
from tests.utils import hash... | pd.DataFrame([1, 2, 3], index=index) | pandas.DataFrame |
import tempfile
import pytest
import pandas as pd
from fuzzyfinder.database import SearchDatabase
def test_build_and_search():
db_filename = tempfile.NamedTemporaryFile().name
db = SearchDatabase(db_filename)
rec1 = {"unique_id": 1, "first_name": "robin", "surname": "linacre"}
rec2 = {"unique_id": ... | pd.Int64Dtype() | pandas.Int64Dtype |
__all__ = [
"add_net_meta", "convert_column", "and_filter", "get_outlier_bounds", "avg_over_net", "normalize",
"add_topo", "add_median_lh", "add_split_label", "remove_outliers", "calc_paired_diff", "calc_percentage_change",
"calc_icc", "normalize_series", "concat_dfs", "long_column_to_wide",
]
import itert... | pd.DataFrame(columns=("left", "right", "difference")) | pandas.DataFrame |
import pandas as pd
import numpy as np
import os
import requests
import json
import datetime
import time
MIN_FINAL_RATING = 1500 # top submission in a match must have reached this score
num_api_calls_today = 0
all_files = []
for root, dirs, files in os.walk('../input/', topdown=False):
all_files.extend(files)
see... | pd.DataFrame(rj['result']['teams']) | pandas.DataFrame |
from os.path import dirname, join as pjoin
import scipy.io as sio
import numpy as np
import pandas as pd
import sys
import os
import argparse
import shutil
# Globally accessible:
csv_folderpath = os.path.join(sys.path[0], 'csvIndexes')
class ADEIndex():
def __init__(self):
self.image_index = None
self.obj... | pd.DataFrame(matindex['objectnames'].T, columns=['objectnames']) | pandas.DataFrame |
# Overcommented for explanatory reasons
import re
import os
# Type annotations
from typing import IO, Text
# Reading pdf
from io import StringIO
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout impor... | pd.DataFrame(references) | pandas.DataFrame |
import streamlit as st
import pandas as pd
import base64
import numpy as np
from PIL import Image
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score, mean_squared_error
# pre... | pd.read_csv(uploaded_test) | pandas.read_csv |
import pandas as pd
import mlflow
import click
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
def human_readable(value):
if value == ['1']:
return "FAKE NEWS!"
return "REAL NEWS"
def predict(text):
print(f"Accepted payload: {text}")
my_data = {
"text": {... | pd.DataFrame(data) | pandas.DataFrame |
import pandas as pd
import numpy as np
import os
import datetime
import re
from tqdm import tqdm
# Run the create dataframe and clean data function
file = "../data_scheme_w.csv"
def windows_folder(folder):
"""
Modify foders from files in a dataframe\
To be used with pandas .apply()
"""
folder = s... | pd.read_csv(file) | pandas.read_csv |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 11:32:12 2020
@authors: <NAME> and <NAME>
"""
#Import Python core modules
import os
import pandas as pd
import numpy as np
#Import custom modules
import dataextract
import analyzer
path=os.getcwd()
os.chdir(path)
#defining file names
netVehic... | pd.DataFrame() | pandas.DataFrame |
import pandas as pd
def nasa_weather(df):
year = df['YEAR'].astype(str)
month = df['MO'].astype(str)
day = df['DY'].astype(str)
month = month.apply(lambda x: '0'+x if len(x) == 1 else x)
day = day.apply(lambda x: '0'+x if len(x) == 1 else x)
df['date'] = | pd.to_datetime(year + "-" + month + "-" + day) | pandas.to_datetime |
#!/usr/bin/env python3
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# This file is part of Salus
# (see https://github.com/SymbioticLab/Salus).
#
# 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
#
#... | pd.Timedelta(1, 's') | pandas.Timedelta |
import pandas as pd
from sklearn import linear_model
import statsmodels.api as sm
import numpy as np
from scipy import stats
# df_2018 = pd.read_csv("/mnt/nadavrap-students/STS/data/2018_2019.csv")
# df_2016 = pd.read_csv("/mnt/nadavrap-students/STS/data/2016_2017.csv")
# df_2014 = pd.read_csv("/mnt/nadavrap-students... | pd.merge(d5, df_comp, left_on=['hospid', 'surgyear'], right_on=['hospid', 'surgyear'], how='outer') | pandas.merge |
from unittest import TestCase
import definitions
from src.Swell import Swell
from src.SwellDAO import SwellDAO
import pandas as pd
import os
class TestSwellDAO(TestCase):
def test_create_table(self):
swellDAO = SwellDAO()
swellDAO.create_table()
tables = swellDAO.show_tables()
t... | pd.read_csv(test_data_path, encoding='unicode_escape') | pandas.read_csv |
import numpy as np
import pandas as pd
from asset_model import geometric_brownian_motion
#TODO
# class CcpiStrategy(InvestmentStrategy):
#
# def __init__(self, drawdown=None, multiplier=3):
# self.drawdown = drawdown
# self.multiplier = multiplier
#
# def update_portfolio_weighs(self, current_... | pd.DataFrame() | pandas.DataFrame |
import pandas as pd
import requests
import os
class extract_as_csv(object):
def extract_f1_json(url__f1_tv, url__drivers):
page = requests.get(url__f1_tv)
json__f1_tv = page.json()
# ergast data
page = requests.get(url__drivers)
json__drivers = page.json()
def db_n... | pd.DataFrame(data=DataFrame) | pandas.DataFrame |
# General Packages
from math import atan2, degrees
from datetime import datetime
from pathlib import Path
import time
import pprint
import numpy as np
import pandas as pd
import pickle
# Plotting
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.dates import date2num
import seaborn as s... | pd.set_option('display.max_columns', 30) | pandas.set_option |
import os
from collections import Counter
from os import listdir
from os.path import isfile, join
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure
from matplotlib import style
style.use('ggplot')
import scipy
from matplotlib.ticker import M... | pd.read_csv(filename) | pandas.read_csv |
#
# Copyright (c) 2015 - 2022, Intel Corporation
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... | pandas.DataFrame(unmarked_row, index=[0]) | pandas.DataFrame |
#!/usr/bin/env python
"""Script for generating figures of catalog statistics. Run `QCreport.py -h`
for command line usage.
"""
import os
import sys
import errno
import argparse
from datetime import date, datetime
from math import sqrt, radians, cos
import markdown
import numpy as np
import pandas as pd
import cartopy.... | pd.Timedelta(days=barwidth/2.) | pandas.Timedelta |
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
def get_soup(url):
headers = {'User-Agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/39.0.2171.95 Safari/537.36')}
r = requests.get(url, h... | pd.concat([df_arrival, df_departure]) | pandas.concat |
import pandas as pd
def model(buffer):
df = | pd.DataFrame.from_dict(buffer) | pandas.DataFrame.from_dict |
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 12:52:53 2020
This script plots the boxplots of the distributions
@author: acn980
"""
import os, glob, sys
import pandas as pd
import numpy as np
import warnings
import matplotlib.pyplot as plt
sys.path.insert(0,r'E:\github\seasonality_risk\Functions')
from Functions... | pd.read_csv(fn_skew, parse_dates = True, date_parser= date_parser, index_col = 'Date') | pandas.read_csv |
import pandas as pd
import os
import time
try:from ethnicolr import census_ln, pred_census_ln,pred_wiki_name,pred_fl_reg_name
except: os.system('pip install ethnicolr')
import seaborn as sns
import matplotlib.pylab as plt
import scipy
from itertools import permutations
import numpy as np
import matplotlib.gridspe... | pd.DataFrame(columns=['bias type','bias amount','boot','race']) | pandas.DataFrame |
"""Plotting functions for linear models (broadly construed)."""
from __future__ import division
import copy
import itertools
import warnings
import numpy as np
import pandas as pd
from scipy.spatial import distance
import matplotlib as mpl
import matplotlib.pyplot as plt
try:
import statsmodels.api as sm
impor... | pd.DataFrame(data, columns=names, dtype=np.float) | pandas.DataFrame |
import numpy as np
import pandas as pd
import random
import tensorflow.keras as keras
from sklearn.model_selection import train_test_split
def read_data(random_state=42,
otu_filename='../../Datasets/otu_table_all_80.csv',
metadata_filename='../../Datasets/metadata_table_all_80.csv'):
... | pd.read_csv(otu_filename, index_col=0, header=None, sep='\t') | pandas.read_csv |
""" test fancy indexing & misc """
from datetime import datetime
import re
import weakref
import numpy as np
import pytest
import pandas.util._test_decorators as td
from pandas.core.dtypes.common import (
is_float_dtype,
is_integer_dtype,
)
import pandas as pd
from pandas import (
DataFrame,
Index,... | DataFrame(index=[0, 1], columns=[0]) | pandas.DataFrame |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pandas as pd
from astropy.coordinates import SkyCoord
from astropy.io.votable import parse
from sh import bzip2
from ...lib.context_managers import cd
# =============================================================================
# CONSTANTS
# =====... | pd.Series("OGLE-4", index=df.index) | pandas.Series |
# -*- coding: utf-8 -*-
"""
Joining files script, to be used prior to uploading the data on DataBricks
"""
import pandas as pd
import glob
# Name of the sensors whch files need to be joined
sensors = ["well_wh_p_", "well_dh_p_", "well_wh_t_", "well_dh_t", "well_wh_choke_"]
# loop through each sensor and... | pd.concat(li, axis=0, ignore_index=True, sort=False) | pandas.concat |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 4 09:34:08 2017
@author: <NAME>
Answer query script: This script contains functions to query and manipulate DLR survey answer sets. It references datasets that must be stored in a /data/tables subdirectory in the parent directory.
"""
... | pd.DataFrame(columns=missing_cols) | pandas.DataFrame |
# Created by <NAME>
import numpy as np
import pandas as pd
from hics.scored_slices import ScoredSlices
class AbstractResultStorage:
def update_relevancies(self, new_relevancies: pd.DataFrame):
raise NotImplementedError()
def update_redundancies(self, new_redundancies: pd.DataFrame):
raise N... | pd.DataFrame(columns=['redundancy', 'iteration']) | pandas.DataFrame |
import torch
import numpy as np
import pandas as pd
import time
import h5py
from tensorboardX import SummaryWriter
class DeepLogger(object):
def __init__(self, time_to_track, what_to_track, log_fname=None,
network_fname=None, seed_id=0, tboard_fname=None,
time_to_print=None, wha... | pd.DataFrame(columns=self.what_to_track) | pandas.DataFrame |
import sys
import argparse
from functools import reduce
from collections import OrderedDict
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import xgboost as xgb
from sklearn.metrics import roc_auc_score
from sklearn.linear_model import Ridge, LinearRegression
import torch
import torch.nn as nn
... | pd.DataFrame(x, columns=scaler.columns) | pandas.DataFrame |
import re
import os
import pandas as pd
import numpy as np
from .extract_tools import default_tokenizer as _default_tokenizer
def _getDictionnaryKeys(dictionnary):
"""
Function that get keys from a dict object and flatten sub dict.
"""
keys_array = []
for key in dictionnary.keys():
... | pd.concat((current_relations, df[current_relations.columns])) | pandas.concat |
import os
import torch
from tqdm import tqdm
import argparse
import multiprocessing as mp
import pandas as pd
from moses.models_storage import ModelsStorage
from moses.metrics.utils import average_agg_tanimoto, fingerprints, fingerprint
from rdkit import DataStructs, Chem
from scipy.spatial.distance import jaccard
impo... | pd.DataFrame(result_list) | pandas.DataFrame |
import pandas as pd
from sklearn.decomposition import TruncatedSVD, NMF
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, f1_score, confusion_matrix
... | pd.merge(df, demographics, on='username') | pandas.merge |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class Visualizer:
def __init__(self, action_labels):
self.n_action = len(action_labels)
self.action_labels = action_labels
def visualise_episode(self, env, cum_rewards, actions, pqs, ideal, fig_path):
_, (ax_price, ax_action, ax_Q) = pl... | pd.DataFrame(pqs, columns=['cash', 'open', 'keep']) | pandas.DataFrame |
# -*- coding: utf-8 -*-
import warnings
from datetime import datetime, timedelta
import pytest
import numpy as np
import pandas as pd
import pandas.util.testing as tm
from pandas.errors import PerformanceWarning
from pandas import (Timestamp, Timedelta, Series,
DatetimeIndex, TimedeltaIndex,
... | date_range('20130101', periods=3) | pandas.date_range |
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import copy
import math
from shapely.geometry.polygon import Polygon
# A shared random state will ensure that data is split in a same way in both train and test function
RANDOM_STATE = 42
def... | pd.merge(join_df, tabular_features_df, left_on='dataset2', right_on='dataset_name') | pandas.merge |
import recordlinkage
import pandas as pd
import csv
import re
import pymongo
from pymongo import MongoClient
#path to our datasets
ORIGINAL = "restaurants.tsv"
DUPLICATES = "restaurants_DPL.tsv"
#parse to tsv files into a dataframe
df = | pd.read_csv(ORIGINAL, sep='\t') | pandas.read_csv |
# *****************************************************************************
# 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:
#
# Redistributions of sou... | pd.Series(data) | pandas.Series |
# Reference: https://learndataanalysis.org/how-to-download-photos-from-google-photos-in-python/
import os
from Google import Create_Service
import pandas as pd # pip install pandas
import requests # pip install requests
pd.set_option('display.max_columns', 100)
pd.set_option('display.max_rows', 150)
| pd.set_option('display.max_colwidth', 150) | pandas.set_option |
#!/usr/bin/env python -B
#==============================================================================
#title :phenorank.py
#description :main function for running PhenoRank
#author :<NAME>
#date_created :12 May 2015
#version :0.1.2
#usage :
#python_version :2.7.9
#=============... | pd.Series(score_unranked_prop, index=genes) | pandas.Series |
# © All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE,
# Switzerland, Laboratory of Experimental Biophysics, 2016
# See the LICENSE.txt file for more details.
import pandas as pd
import trackpy as tp
import numpy as np
import matplotlib.pyplot as plt
import re
from abc import ABCMeta, abstractmethod, abstr... | pd.concat(temp) | pandas.concat |
'''
Model training with the entire training data
'''
# Libraries
import pandas as pd
import numpy as np
import keras
import tensorflow as tf
from keras.models import Model
from tensorflow.keras.models import load_model
import keras.backend as K
from keras import optimizers
from keras.layers import Dense, Dropout, Batc... | pd.DataFrame(nf4_13) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 12:11:33 2020
@author: Andrew
"""
import numpy as np
import pandas as pd
import src.features as features
import json
import os
#### methods for reading in or creating parameter files in params/
def read_ignoring_comments(filepath):
"""read in a file and return a ... | pd.DataFrame() | pandas.DataFrame |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python [conda env:.conda-bandit_nhgf]
# language: python
# name: conda-... | pd.read_csv(calib_file, sep='\s+', index_col=['Parameter']) | pandas.read_csv |
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import warnings
import seaborn as sns
warnings.filterwarnings('ignore')
| pd.set_option('display.max_rows',100,'display.max_columns', 10000,"display.max_colwidth",10000,'display.width',10000) | pandas.set_option |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.