prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*--
# Copyright (c) 2021, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
"""
The ADS accessor for the Pandas DataFrame.
The accessor will be initialized with the pandas object the us... | is_list_like(exclude) | pandas.core.dtypes.common.is_list_like |
import logging
import numpy as np
import pandas as pd
import scipy.stats as ss
from scipy.linalg import eig
from numba import jit
import sg_covid_impact
# from mi_scotland.utils.pandas import preview
logger = logging.getLogger(__name__)
np.seterr(all="raise") # Raise errors on floating point errors
def process_c... | pd.DataFrame(v[:, 1].real, index=X.index, columns=["eci"]) | pandas.DataFrame |
import pandas as pd
import numpy as np
import scipy as sp
from scipy.special import expit as sigmoid_function
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use('ggplot')
def load_data(location):
""" Given a directory string, returns a pandas dataframe containing hw data."""
# diction... | pd.get_dummies(response, columns=['digit_class']) | pandas.get_dummies |
"""
๊ตญํ ๊ตํต๋ถ Open API
molit(Ministry of Land, Infrastructure and Transport)
1. Transaction ํด๋์ค: ๋ถ๋์ฐ ์ค๊ฑฐ๋๊ฐ ์กฐํ
- AptTrade: ์ํํธ๋งค๋งค ์ค๊ฑฐ๋์๋ฃ ์กฐํ
- AptTradeDetail: ์ํํธ๋งค๋งค ์ค๊ฑฐ๋ ์์ธ ์๋ฃ ์กฐํ
- AptRent: ์ํํธ ์ ์์ธ ์๋ฃ ์กฐํ
- AptOwnership: ์ํํธ ๋ถ์๊ถ์ ๋งค ์ ๊ณ ์๋ฃ ์กฐํ
- OffiTrade: ์คํผ์คํ
๋งค๋งค ์ ๊ณ ์กฐํ
- OffiRent: ์คํผ์คํ
์ ์์ธ ์ ๊ณ ์กฐํ
- RHTrad... | pd.DataFrame() | pandas.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... | timedelta_range('1 day', periods=3) | pandas.timedelta_range |
from datetime import datetime
import operator
import numpy as np
import pytest
from pandas import DataFrame, Index, Series, bdate_range
import pandas._testing as tm
from pandas.core import ops
class TestSeriesLogicalOps:
@pytest.mark.parametrize("bool_op", [operator.and_, operator.or_, operator.xor])
def te... | tm.assert_series_equal(result, expected) | pandas._testing.assert_series_equal |
"""
@file
@brief Command line about validation of prediction runtime.
"""
import os
from logging import getLogger
import warnings
import json
from multiprocessing import Pool
from pandas import DataFrame
from sklearn.exceptions import ConvergenceWarning
def validate_runtime(verbose=1, opset_min=-1, opset_max="",
... | DataFrame(rows) | pandas.DataFrame |
# This script is used to read the binary file produced by the DCA1000 and Mmwave Studio
import numpy as np
import pandas as pd
def readTIdata(filename,csvname):
"""
Reads in a binary file and outputs the iq complex data to a csv file specified by csvname.
Parameter:
filename: str
fil... | pd.DataFrame(adcData) | pandas.DataFrame |
# -*- coding: utf-8 -*-
'''
McFlyin API example.
Take data from Python to send to an API in Python to transform data in Python to receive in Python to transform in Python.
But you can take data from ___ to send to an API in Python to transform data in Python to recieve in ____ to transform in ____
'''
import pandas... | pd.read_csv('AllPandas.csv') | pandas.read_csv |
import asyncio
import sys
import random as rand
import os
from .integration_test_utils import setup_teardown_test, _generate_table_name, V3ioHeaders, V3ioError
from storey import build_flow, CSVSource, CSVTarget, SyncEmitSource, Reduce, Map, FlatMap, AsyncEmitSource, ParquetTarget, ParquetSource, \
DataframeSource... | pd.Timestamp('2020-12-31 23:59:59.999999') | pandas.Timestamp |
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import sys
from yellowbrick.cluster import KElbowVisualizer
import numpy as np
def my_tokenizer(text):
tokens = text.split(",")
return tokens
def cluster_synsetframe_communities(filtered_enr... | pd.read_csv(filtered_enriched_synsetframe_csv, skiprows=[0], names=colnames) | pandas.read_csv |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 22 09:13:58 2019
@author: rocco
"""
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
files = [i for i in os.listdir("../data/mipas_pd")]
files = files[19:24]
classifier_type = "labels_svm_pc_rf_2"
def plot_bar(files, classifier... | pd.value_counts(df_reduced[df_reduced[cl] == i][classifier_type]) | pandas.value_counts |
# import libraries
import sys
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''
INPUT:
'message_filepath' : path to a csv file
'categories_filepath' : path to a csv file
OUTPUT:
transformed pandas ... | pd.merge(messages, categories, on='id') | pandas.merge |
#!/usr/bin/python
# <NAME>
# The University of Sheffield
# 06.03.2021
# NOTES
# AGENT class uses some parts of https://github.com/PacktPublishing/PyTorch-1.x-Reinforcement-Learning-Cookbook/blob/master/Chapter08/chapter8/reinforce.py for REINFORCE implementation
# TODO: documentation
from env import gyMBlocks
import ... | pd.DataFrame(logs, columns=['ep', 'done', 'reward', 'epLength', 'bbox']) | pandas.DataFrame |
'''
CIS 419/519 project: Using decision tree ensembles to infer the pathological
cause of age-related neurodegenerative changes based on clinical assessment
nadfahors: <NAME>, <NAME>, & <NAME>
This file contains code for preparing NACC data for analysis, including:
* synthesis of pathology data to create pat... | pd.DataFrame(pickle_list[5]) | pandas.DataFrame |
"""
This script is for finding the optimal distribution to be used in GluonTS
"""
import warnings
import numpy as np
import pandas as pd
import streamlit as st
from scipy import stats
import statsmodels as sm
import matplotlib.pyplot as plt
import autodraft.gluonts as glu
@st.cache
def get_data(path='../../data/input/... | pd.DataFrame() | pandas.DataFrame |
# Copyright (C) 2020 <NAME>, <NAME>
# Code -- Study 1 -- What Personal Information Can a Consumer Facial Image Reveal?
# https://github.com/computationalmarketing/facialanalysis/
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.patches as mpa... | pd.read_csv(p) | pandas.read_csv |
'''
This script contains examples of functions that can be used from the Pandas
module.
'''
# Series ---------------------------------------------------------------------
import pandas as pd
import numpy as np
# Creating series
pd.Series(data=[1,2,3,4]) # list
pd.Series(data=[... | pd.DataFrame({'A':[1,2,np.nan], 'B':[5,np.nan,np.nan], 'C':[1,2,3]}) | pandas.DataFrame |
import collections
import copy
import os
import random
import string
import sys
from argparse import ArgumentParser
import matplotlib
import matplotlib.colors as pltc
import numpy as np
import pandas as pd
import plotly.figure_factory as ff
import plotly.graph_objects as go
import pyranges as pr
import pysam
import sc... | pd.DataFrame(rows, columns=["cov_value", "cov_count"]) | pandas.DataFrame |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | pd.Index(['feat1', 'feat2'], name='id') | pandas.Index |
'''
Collect computational performance from a collection of GNU time reports.
Usage:
```
python collect_perf.py -a bt2_all.time_log -l lift.time_log -l collate.time_log \
-l to_fastq.time_log -l aln_paired.time_log -l aln_unpaired.time_log \
-l merge.time_log -l sort_all.time_log
```
<NAME>
Johns Hopkins University
2... | pd.DataFrame(ls_perf, columns=cols) | pandas.DataFrame |
import pandas as pd
from sklearn import preprocessing
from scipy.sparse import coo_matrix
import numpy as np
def quora_leaky_extracting(concat):
tid1 = concat['q1_id'].values
tid2 = concat['q2_id'].values
doc_number = np.max((tid1.max(), tid2.max())) + 1
adj = coo_matrix((np.ones(len(tid1) * 2), (np.c... | pd.read_csv(path + '/train.tsv', delimiter='\t', header=None) | pandas.read_csv |
import pandas as pd
from itertools import combinations
import seaborn as sns
import matplotlib.pyplot as plt
path_to_data = '../data/preprocess.csv'
data = pd.read_csv(path_to_data)
data.utc_event_time = | pd.to_datetime(data.utc_event_time) | pandas.to_datetime |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import defaultdict, OrderedDict
from itertools import chain
from pathlib import Path
from typing import Dict, Tuple, List, Union, Optional
import numpy
import pandas
from pyutils.list_utils import _
from sklearn.linear_model import LogisticRegression
from skl... | pandas.DataFrame(raw_X_test) | pandas.DataFrame |
from datetime import datetime
import numpy as np
import pandas as pd
import pytest
from numba import njit
import vectorbt as vbt
from tests.utils import record_arrays_close
from vectorbt.generic.enums import range_dt, drawdown_dt
from vectorbt.portfolio.enums import order_dt, trade_dt, log_dt
day_dt = np.timedelta64... | pd.Timedelta('0 days 00:00:00') | pandas.Timedelta |
# -*- coding: utf-8 -*-
"""
@author: Elie
"""
# Libraries
import datetime
import numpy as np
import pandas as pd
#plotting
import matplotlib as mpl
from matplotlib import pyplot as plt
import seaborn as sns
import os
#sklearn
from sklearn.metrics import auc, roc_curve
from sklearn.model_selection import (GridSearchCV,... | pd.merge(df_good, all_preds_df, left_index=True, right_index=True) | pandas.merge |
'''
THIS IS THE BEATAML ONLY TEST FILE
'''
import sys
sys.path.append(r'C:\Users\natha\Documents\DEEP_DRUG_SH\python\UTILS')
import pickle
from matplotlib import pyplot as plt
import numpy as np
from config import * # params stored here
import utils
import pandas as pd
from torch.utils import data
if __name__ == ... | pd.DataFrame({'y':ys, 'yhat':yhats}) | pandas.DataFrame |
# -----------------------------------------------------------------------------
# WSDM Cup 2017 Classification and Evaluation
#
# Copyright (c) 2017 <NAME>, <NAME>, <NAME>, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ... | pd.Series() | pandas.Series |
import pandas as pd
import urllib
from bs4 import BeautifulSoup
#creates a list of the word that needs to be searched in dictionary.com
word = ['handy','whisper','lovely','scrape']
List = []
#creates a for loop to pull the definitions for each word in the list
for i in range(0,4):
url = "https://www.dictionary.... | pd.DataFrame(List, columns=["Word", "Definition"]) | pandas.DataFrame |
import pandas as pd
import os
import portalocker
import contextlib
import yaml
import subprocess
from gnn_acopf.experimental.opf_dataset import OPFDataset
from gnn_acopf.training.training_run import QualityMetric
from gnn_acopf.utils.timer import Timer
from pathlib import Path
import copy
from gnn_acopf.utils.observers... | pd.DataFrame() | pandas.DataFrame |
from pytools4p.transformer import reshaper
import pandas as pd
import pandas.testing as tm
from pandas.testing import assert_frame_equal
import numpy as np
def test_pivot_reshaper():
"""Test for normal arguments
"""
def unpivot(frame):
N, K = frame.shape
data = {
"value": frame.... | pd.DataFrame(data, columns=["date", "variable", "value"]) | pandas.DataFrame |
# -*- 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.date_range('2014-01-01', periods=3) | pandas.date_range |
import numpy as np
import pandas as pd
from open_quant.labeling.multi_processing import mp_pandas
import sys
def test(a, b):
return a + b
def triple_barrier_method(close, events, pt_sl, molecule):
"""
Advances in Financial Machine Learning, Snippet 3.2, page 45.
Triple Barrier Labeling Method
Ap... | pd.Timedelta(days=num_days) | pandas.Timedelta |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import numpy as np
import pandas as pd
import pandas.testing as pdt
import pyarrow as pa
import pytest
from pyarrow.parquet import ParquetFile
from kartothek.serialization import (
CsvSerializer,
DataFrameSerializer,
ParquetSerializer,
de... | pd.Series([np.nan, 1.0, np.nan], dtype=float) | pandas.Series |
from unittest import TestCase
import pandas as pd
from moonstone.utils.taxonomy import TaxonomyCountsBase
class TestTaxonomyCountsBase(TestCase):
def setUp(self):
self.taxonomy_instance = TaxonomyCountsBase()
def test_fill_none(self):
taxa_df = pd.DataFrame(
[
[... | pd.testing.assert_frame_equal(tested_df, expected_df) | pandas.testing.assert_frame_equal |
from config import *
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from getpass import getpass
from os import remove
import zipfile
import pandas as pd
import numpy as np
from lxml import etree as et
def _parseBgeXml(f):
timestamp = []
consumed = []
... | pd.Series(nc,index=nt) | pandas.Series |
from textwrap import dedent
import numpy as np
import pytest
from pandas import (
DataFrame,
MultiIndex,
option_context,
)
pytest.importorskip("jinja2")
from pandas.io.formats.style import Styler
from pandas.io.formats.style_render import (
_parse_latex_cell_styles,
_parse_latex_css_conversion,
... | _parse_latex_header_span(cell, "X", "Y") | pandas.io.formats.style_render._parse_latex_header_span |
import sys, os, re
import numpy as np
import json
import csv
import matplotlib.pyplot as plt
import pandas as pd
class PARAMETERS_EXTRACTOR:
"""
This class is used to extract and analyze data from log files, which are generated by running management.py
"""
def __init__(self, dir, problem_set):
... | pd.Series.as_matrix(y) | pandas.Series.as_matrix |
import random
import unittest
from collections import namedtuple
from copy import deepcopy
from itertools import chain, product
from unittest.mock import MagicMock
import modAL.acquisition
import modAL.batch
import modAL.density
import modAL.disagreement
import modAL.dropout
import modAL.expected_error
import modAL.mo... | pd.DataFrame(X_pool) | pandas.DataFrame |
"""
"""
"""
>>> # ---
>>> # SETUP
>>> # ---
>>> import os
>>> import logging
>>> logger = logging.getLogger('PT3S.Rm')
>>> # ---
>>> # path
>>> # ---
>>> if __name__ == "__main__":
... try:
... dummy=__file__
... logger.debug("{0:s}{1:s}{2:s}".format('DOCTEST: __main__ Context: ','path = os.p... | pd.merge(V3_DPKT,V3_KNOT,left_on='fkOBJTYPE',right_on='pk',suffixes=('','_KNOT')) | pandas.merge |
from __future__ import print_function, division
#from nilmtk.stats import intersect_many_fast
import matplotlib.pyplot as plt
import pandas as pd
from datetime import timedelta
import matplotlib.dates as mdates
from copy import deepcopy
import numpy as np
# NILMTK imports
from nilmtk.consts import SECS_PER_DAY
from ni... | pd.DataFrame({'section_start': starts, 'section_end':ends}) | pandas.DataFrame |
import os
import time
import pandas as pd
from geopy.exc import GeocoderTimedOut
from geopy.geocoders import Nominatim
def straat2coord(file_path: str, woonplaats: str, woonplaats_header: str, adres_header: str, sep: str = ";") -> None:
"""Berekend aan de hand van een CSV-bestand de breedte- en hoogtegraad.
... | pd.read_csv(file_path, sep=";") | pandas.read_csv |
"""
Functions for comparing and visualizing model performance. Most of these functions rely on ATOM's model tracker and
datastore services, which are not part of the standard AMPL installation, but a few functions will work on collections of
models saved as local files.
"""
import os
import sys
import pdb
import panda... | pd.DataFrame(np.nan, index=nai, columns=tempdf.columns) | pandas.DataFrame |
#########################################
# "LaZy Bot" for Discord #
# Author: <NAME> #
# www.brick.technology #
#########################################
## To run at its best, follow the advice below ##
# 1. Works well with XavinBot. Users can Emoji react to ... | pd.DataFrame(csv_open) | pandas.DataFrame |
import sys
import pandas as pd
sys.path.append('../minvime')
import estimator_classification as esti # The file ../minvime/estimator_classification.py
tps = [20000,10000,8000,6000,4000,2000,1000]
fps = [-900,-800,-600,-500,-400,-200,-100]
tn = 0
fn = 0
minroi = 100000
cases = 1000000
baserate = 0.001
rez = | pd.DataFrame() | pandas.DataFrame |
import os
import tempfile
import pandas as pd
import pytest
from pandas.util import testing as pdt
from .. import simulation as sim
from ...utils.testing import assert_frames_equal
def setup_function(func):
sim.clear_sim()
sim.enable_cache()
def teardown_function(func):
sim.clear_sim()
sim.enable_... | pd.Series([7, 8, 9], index=df.index) | pandas.Series |
# Visualize streamflow time series and fill missing data
# Script written in Python 3.7
import config as config
import numpy as np
import pandas as pd
import tempfile
import datetime
from sklearn.svm import SVR
import geopandas as gpd
from sklearn.metrics import mean_squared_error as mse
import matplotlib.pyplot as pl... | pd.to_datetime('01-01-2004') | pandas.to_datetime |
import numpy as np
import pandas as pd
import os
from dataV3 import make_directory
from dataV3 import get_indices_hard
import json
import math
def pointSort(scoring_directory, input_dir = None, weights = None,
scale_guide_dir = "./config/point_assignment_scaling_guide.csv", reporting = False, rep_direc =... | pd.read_csv(tua_location) | pandas.read_csv |
import collections
import fnmatch
import os
from typing import Union
import tarfile
import pandas as pd
import numpy as np
from pandas.core.dtypes.common import is_string_dtype, is_numeric_dtype
from hydrodataset.data.data_base import DataSourceBase
from hydrodataset.data.stat import cal_fdc
from hydrodataset.utils im... | pd.read_csv(attr_all_file, sep=";") | pandas.read_csv |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import sys
import os
import shutil
import scanpy as sc
from ..utility import exec_process
rscript_folder = os.path.abspath(os.path.dirname(__file__))
# this is a function to integrate matrix and meta data and make AnnData object
def _constructAnnDat... | pd.concat([mat.obs.tsne_1, mat.obs.tsne_2],axis=1) | pandas.concat |
"""
$ pip install streamlit streamlit-option-menu streamlit-aggrid
- Bootstrap icons:
https://icons.getbootstrap.com/
- This app builds on the following streamlit contributions, Thank you!
- streamlit-option-menu
- streamlit-aggrid
## TODO
- parse table schema to get column name/type and build create/... | pd.read_sql(sql_stmt, conn) | pandas.read_sql |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 9 23:41:26 2020
@author: <NAME>
"""
import pandas as pd
import numpy as np
movie =pd.read_csv("IMDB-Dataset//movies.csv")
rating = pd.read_csv("IMDB-Dataset//ratings.csv")
df = | pd.merge(movie, rating, on='movieId') | pandas.merge |
# -*- coding: utf-8 -*-
import os
from datetime import datetime
from numerapi.numerapi import NumerAPI
import luigi
import pandas as pd
from sklearn import metrics, preprocessing, linear_model
from .numerai_fetch_training_data import FetchAndExtractData
class TrainAndPredict(luigi.Task):
"""
Trains a naรฏve ... | pd.DataFrame(data={'probability': results}) | pandas.DataFrame |
import unittest
import qteasy as qt
import pandas as pd
from pandas import Timestamp
import numpy as np
from numpy import int64
import itertools
import datetime
from qteasy.utilfuncs import list_to_str_format, regulate_date_format, time_str_format, str_to_list
from qteasy.utilfuncs import maybe_trade_day, is_market_tr... | Timestamp('2021-12-31') | pandas.Timestamp |
import os
import json
import re
from pathlib import Path
from typing import Dict, List, Union
import pandas as pd
import numpy as np
from npmrd_curator.parsers.html_table_parser import csv_to_json, parser
from npmrd_curator.exceptions import HtmlReadError
Pathlike = Union[Path, str]
def parse_html_str(input_html: ... | pd.DataFrame(data) | pandas.DataFrame |
from sklearn.datasets import load_iris
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
data = load_iris(as_frame=True)
print(data["DESCR"])
data["filename"]
data["target_names"]
data["feature_names"]
data["frame"]
x, y = load_iris(return_X_y=True, as_frame=True)
df = | pd.concat([x, y], axis=1) | pandas.concat |
"""
Peak and plot simultaneously
Grant 2016, double potentials, EVI and my peak finder
"""
import csv
import numpy as np
import pandas as pd
# import geopandas as gpd
from IPython.display import Image
# from shapely.geometry import Point, Polygon
from math import factorial
import datetime
import time
import scipy
impo... | pd.concat([WSDA_df]*spline_max_df.shape[0]) | pandas.concat |
import os
import time
import math
import json
import hashlib
import datetime
import pandas as pd
import numpy as np
from run_pyspark import PySparkMgr
graph_type = "loan_agent/"
def make_md5(x):
md5 = hashlib.md5()
md5.update(x.encode('utf-8'))
return md5.hexdigest()
def make... | pd.DataFrame({"identity_no": overday_gp.index, "overdue_days_now": overday_gp.values}) | pandas.DataFrame |
#!/usr/bin/python
# <NAME>, <EMAIL>
# v1.0, 09/13/2021
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import mannwhitneyu, norm, kruskal, spearmanr
from scipy.optimize import minimize_scalar
import scikit_posthocs as sp
from statsmodels.stats.mul... | pd.read_pickle(pickl) | pandas.read_pickle |
from typing import (
Any,
Dict,
List,
Tuple,
Union,
TypeVar,
Callable,
Hashable,
Iterable,
Optional,
Sequence,
)
from typing_extensions import Literal
import os
import wrapt
import warnings
from itertools import tee, product, combinations
from statsmodels.stats.multitest imp... | pd.DataFrame(corr, index=gene_names, columns=[f"{c}_corr" for c in Y.names]) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Project: Psychophysics_exps
Creator: Miao
Create time: 2021-01-05 19:14
IDE: PyCharm
Introduction:
"""
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from src.analysis.exp1_local_density_analysis import dict_pix_to_deg, get_result_dict, int... | pd.DataFrame(datac_ttest) | pandas.DataFrame |
"""This file contains functions which are used to generate the log-likelihood
for different memory models and other code required to run the experiments in
the manuscript."""
import multiprocessing as MP
import warnings
from collections import defaultdict
import numpy as np
import pandas as pd
import matplotlib.patc... | pd.Series(perf[u_id][l_id] for _, u_id, l_id in bottom_memorize_LL) | pandas.Series |
"""
This script save the direct/indirect effects for each neuron averaging across different groups depending
on negation type and correctness category.
Usage:
python compute_and_save_neuron_agg_effect.py $result_file_path $model_name $negation_test_set_file
"""
import os
import sys
import json
import pandas as pd... | pd.read_csv(fname) | pandas.read_csv |
# -*- coding: utf-8 -*-
# edited from https://github.com/carpenterlab/unet4nuclei/blob/master/unet4nuclei/utils/evaluation.py and
# stardist's matching.py
import numpy as np
import pandas as pd
from scipy.optimize import linear_sum_assignment
def intersection_over_union(ground_truth, prediction):
# Count ob... | pd.DataFrame() | pandas.DataFrame |
# %%
'''
'''
## Se importan las librerias necesarias
import pandas as pd
import numpy as np
import datetime as dt
from datetime import timedelta
pd.options.display.max_columns = None
pd.options.display.max_rows = None
import glob as glob
import datetime
import re
import jenkspy
import tkinter as tk
... | pd.read_csv('C:/Users/scadacat/Desktop/TIGO (Cliente)/Cobranzas/Notebooks/Bds/seguimiento.csv',sep=';',encoding='utf-8',dtype='str') | pandas.read_csv |
import pandas as pd
import sys,os,io,re
import numpy as np
path=sys.argv[1]
outName=sys.argv[2]
thresh=int(sys.argv[3])
anno_file=sys.argv[4]
anno_table=pd.read_csv(anno_file)
anno_col=["event_cat","group_increased_alt","aa_change_type","effect_cat"]
anno_col=list(np.intersect1d(anno_col,anno_table.columns))
filelis... | pd.DataFrame(index=total_counts.index,columns=data_col,data=0) | pandas.DataFrame |
# With this script, previosuly omitted rows are added again (my bad).
# post_id is a 1 to 1 connection because they are unique.
import pandas as pd
df_a = pd.read_csv("filtered_messages_subforum_and_keyword_with_spellcheck_all.csv", encoding="utf-8", sep=';')
df_b = | pd.read_csv("crawling_results/posts_and_threads_all.csv", encoding="utf-8", sep=';') | pandas.read_csv |
# -*- coding: utf-8 -*-
# Copyright (c) 2019 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
import codecs
import datetime
import logging
import logging.config
import os
import re
import time
import numpy as np
import sharkpylib
... | pd.to_datetime(f) | pandas.to_datetime |
"""
Copyright 2018 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distribut... | assert_series_equal(expected, result, obj="Compare series intersect") | pandas.util.testing.assert_series_equal |
# Question 07, Lab 07
# AB Satyaprakash, 180123062
# imports
import pandas as pd
import numpy as np
# functions
def f(t, y):
return y - t**2 + 1
def F(t):
return (t+1)**2 - 0.5*np.exp(t)
def RungeKutta4(t, y, h):
k1 = f(t, y)
k2 = f(t+h/2, y+h*k1/2)
k3 = f(t+h/2, y+h*k2/2)
k4 = f(t+h, y+... | pd.Series(y) | pandas.Series |
# 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... | date_range('1/1/2000', periods=10) | pandas.date_range |
import os
import tempfile
import glob
import tqdm
import pandas as pd
import geopandas as gpd
from maskrcnn.postprocess.polygonize import load_ann
# AOI index data w/ georeferencing info
AOI_IN_DIR = 'data/Siaya/Meta/aoi.csv'
# download log data
LOG_IN_DIR = 'data/Siaya/Meta/aoi_download_log.csv'
# satellite derive... | pd.read_csv(LOG_IN_DIR) | pandas.read_csv |
import pandas as pd
import re
import win32com.client
from graphviz import Digraph
def LoadExcelStructure(fileFolder,fileName):
"""
Return a dataframe containing information about your Excel file VB structure
fileFolder: Your Excel file folder
fileName: Your Excel file name including the extension
"... | pd.DataFrame() | pandas.DataFrame |
import pytest
from pandas import Series
from cellengine.utils.scale_utils import apply_scale
@pytest.fixture(scope="module")
def scale():
scale = {"minimum": 5, "maximum": 10, "type": "LinearScale"}
return scale
def test_should_apply_scale(scale):
input = Series([10, 0, 1.2, 10, 40])
output = Serie... | Series([], dtype="float64") | pandas.Series |
#--------------------------------------------------------------- Imports
from dotenv import load_dotenv
import alpaca_trade_api as tradeapi
import os
from pathlib import Path
import string
import pandas as pd
import numpy as np
import seaborn as sns
import panel as pn
from panel.interact import interact, interactive, f... | pd.read_csv(file, infer_datetime_format=True, parse_dates=True, index_col='Date') | pandas.read_csv |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# %%
DATA_ROOT = '../../data/raw'
# %% [markdown]
# ## LOADING DATA
# %%
print('Loading raw datasets...', flush=True)
GIT_COMMITS_PATH = f"{DATA_ROOT}/GIT... | pd.merge(szz_fault_inducing_commits, jira_bugs, on='key') | pandas.merge |
#
# unility libraary that provides capabilies to interact with the SCM instances and provide
# the retrieved data in a format for presentation.
#
# this library provides functions for communicating directly with an SCM instnace
# and it also provides functions with the _proxy naming where the data is retrived
# fro... | pd.read_json(r.content, orient='index') | pandas.read_json |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import geopandas as gpd
from shapely.geometry import Point
moz_zipfile = "zip:///home/leo/Desktop/ml_flood_prediction/data/floods_13-03-2020/moz_flood.zip"
moz_gdf = gpd.read_file(moz_zipfile)
moz_g... | pd.to_datetime(flood_start) | pandas.to_datetime |
from copy import deepcopy
import networkx as nx
import numpy as np
import pandas as pd
from graspologic.utils import largest_connected_component
from ..utils import get_paired_inds, to_pandas_edgelist
class MaggotGraph:
def __init__(self, g, nodes=None, edges=None):
self.g = g
# TODO add checks... | pd.DataFrame(cols) | pandas.DataFrame |
# import libraries
import glob
import os
from collections import OrderedDict
from pathlib import Path
import cv2
import face_recognition
import numpy as np
import pandas as pd
from PIL import Image
from tqdm import tqdm
def wget_video(
name,
url,
cmd="youtube-dl --continue --write-auto-sub --get-thumbnai... | pd.DataFrame(results) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
@author: pattenh1
"""
import os
import cv2
import SimpleITK as sitk
import ijroi
import numpy as np
import pandas as pd
import lxml.etree
import lxml.builder
import matplotlib
from matplotlib import cm
class ROIhandler(object):
"""Container class for handling ROIs lo... | pd.DataFrame(xs, columns=['x1']) | pandas.DataFrame |
"""
Evaluate the fair model on a dataset;
Also evaluate benchmark algorithms: OLS, SEO, Logistic regression
Main function: evaluate_FairModel
Input:
- (x, a, y): evaluation set (can be training/test set)
- loss: loss function name
- result: returned by exp_grad
- Theta: the set of Threshold
Output:
- predictions over... | pd.Series.unique(y_quant) | pandas.Series.unique |
from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient
from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient
from azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateBatch, ImageFileCreateEntry, Region
from msre... | pd.DataFrame(d) | pandas.DataFrame |
import requests
import pandas as pd
import numpy as np
import time
class FMP_CONNECTION(object):
def __init__(self,api_key:str):
self._api_key = api_key
def set_apikey(self,new_apikey):
self._api_key = new_apikey
def get_apikey(self) -> str:
return self._api_key
... | pd.to_datetime(closing_df.index, infer_datetime_format=True) | pandas.to_datetime |
# Import Modulues
#==================================
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
from matplotlib import cm
from collections import OrderedDict
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from... | pd.DataFrame({'Packing Fraction':y_predicted}) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
"""
#!/usr/bin/python
import matplotlib.pylab as plt
import csv
from datetime import datetime, timezone
import pandas as pd
import seaborn as sns
def reddit_plot():
reddit_x = []
reddit_y = []
reddit_y_num = []
reddit_x_filtered = []
dateList... | pd.read_csv("Twitter_dataset.csv") | pandas.read_csv |
"""
The io module provides support for reading and writing diffusion profile data
and diffusion coefficients data to csv files.
"""
import numpy as np
import pandas as pd
from scipy.interpolate import splev
from pydiffusion.core import DiffProfile, DiffSystem
import matplotlib.pyplot as plt
import threading
# To solv... | pd.DataFrame({'dis': dis, 'X': X, 'DC': DC}) | pandas.DataFrame |
"""Permutation test function as described in CellPhoneDB 2.0."""
from abc import ABC
from types import MappingProxyType
from typing import (
Any,
List,
Tuple,
Union,
Mapping,
Iterable,
Optional,
Sequence,
TYPE_CHECKING,
)
from functools import partial
from itertools import product
fr... | pd.MultiIndex.from_frame(interactions, names=[SOURCE, TARGET]) | pandas.MultiIndex.from_frame |
from bittrex import Bittrex
import requests
import pandas as pd
import os
import bittrex_test as btt
import quandl_api_test as qat
from scrape_coinmarketcap import scrape_data
API_K = os.environ.get('bittrex_api')
API_S = os.environ.get('bittrex_sec')
if API_K is None:
API_K = os.environ.get('btx_key')
API_S =... | pd.to_datetime(df['TimeStamp']) | pandas.to_datetime |
#############################################################
# Begin defining Dash app layout
# code sections
# 1 Environment setup
# 2 Setup Dataframes
# 3 Define Useful Functions
# 4 Heatmap UI controls
# 5 Curves plot UI controls
# 6 Navbar definition
# 7 Blank figure to display during initial app loading
# 8 Overa... | pd.to_datetime(max_date + x_margin) | pandas.to_datetime |
# -*- coding: utf-8 -*-
# @author: Elie
#%% ==========================================================
# Import libraries set library params
# ============================================================
import pandas as pd
import numpy as np
import os
pd.options.mode.chained_assignment = None #Pandas warnings off
#pl... | pd.read_csv(cnv_counts_path, sep='\t', low_memory=False) | pandas.read_csv |
"""Debiasing using reweighing"""
"""
This data recipe performs reweighing debiasing using the AIF360 package.
https://github.com/Trusted-AI/AIF360
<NAME>., <NAME>. Data preprocessing techniques for classification without discrimination.
Knowl Inf Syst 33, 1โ33 (2012). https://doi.org/10.1007/s10115-011-0463-8
The... | pd.DataFrame(dataset_transf_test.features, columns=dataset_transf_test.feature_names) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 28 15:27:09 2017
@author: Adam
run_dire()
- function to build path to a run directory
run_file()
- function to build path to a run file
cashew()
- caching wrapper
H5Scan
- class for accessing hdf5 files without groups
... | pd.read_pickle(cache_file) | pandas.read_pickle |
# pylint: disable-msg=W0612,E1101,W0141
import nose
from numpy.random import randn
import numpy as np
from pandas.core.index import Index, MultiIndex
from pandas import Panel, DataFrame, Series, notnull, isnull
from pandas.util.testing import (assert_almost_equal,
assert_series_equal... | assertRaisesRegexp(TypeError, 'hierarchical index', df.sortlevel, 0) | pandas.util.testing.assertRaisesRegexp |
# -*- coding: utf-8 -*-
"""Tests for dataframe `adni` extension."""
# pylint: disable=W0621
# Third party imports
import numpy as np
import pandas as pd
import pytest
from adnipy import adni # noqa: F401 pylint: disable=W0611
@pytest.fixture
def test_df():
"""Provide sample dataframe for standardized testing... | pd.testing.assert_frame_equal(correct, with_rid) | pandas.testing.assert_frame_equal |
from datetime import timedelta
import operator
import numpy as np
import pytest
import pytz
from pandas._libs.tslibs import IncompatibleFrequency
from pandas.core.dtypes.common import is_datetime64_dtype, is_datetime64tz_dtype
import pandas as pd
from pandas import (
Categorical,
Index,
IntervalIndex,
... | tm.assert_series_equal(result, exp) | pandas._testing.assert_series_equal |
'''GDELTeda.py
Project: WGU Data Management/Analytics Undergraduate Capstone
<NAME>
August 2021
Class for collecting Pymongo and Pandas operations to automate EDA on
subsets of GDELT records (Events/Mentions, GKG, or joins).
Basic use should be by import and implementation within an IDE, or by editing
se... | pd.StringDtype() | pandas.StringDtype |
#!/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.DataFrame({"meter_value": [], "cdd_65": []}) | pandas.DataFrame |
#!/usr/bin/env python
"""
analyse Elasticsearch query
"""
import json
from elasticsearch import Elasticsearch
from elasticsearch import logger as es_logger
from collections import defaultdict, Counter
import re
import os
from datetime import datetime
# Preprocess terms for TF-IDF
import numpy as np
import pandas as pd... | pd.read_csv(tfidf_whole_f, index_col=0) | pandas.read_csv |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class RedRio:
def __init__(self,codigo = None,**kwargs):
self.info = pd.Series()
self.codigo = codigo
self.info.slug = None
self.fecha = '2006-06-06 06:06'
self.workspace = '/media/'
self.seccion... | pd.read_excel(file,sheetname=1) | pandas.read_excel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.