prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
#
import numpy
import pandas
from sklearn.preprocessing import StandardScaler
# trash and should be removed
class PctTransformer:
def __init__(self):
self.f_row = None
def fit(self, data):
pass
# are you ok, man? what's this?
def transform(self, data):
self.f_row = data[[0], ... | pandas.isna(data) | pandas.isna |
"""pandasなどなど関連。"""
from __future__ import annotations
import gc
import html
import logging
import typing
import warnings
import numpy as np
import pandas as pd
import sklearn.utils
import pytoolkit as tk
logger = logging.getLogger(__name__)
def label_encoding(values: pd.Series | np.ndarray, values_set: typing.It... | pd.api.types.is_object_dtype(df[c].dtype) | pandas.api.types.is_object_dtype |
import os
from functools import lru_cache
from glob import glob
from time import time
import numpy as np
import pandas as pd
import torch
import yaml
from fire import Fire
from glog import logger
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
from torch.utils.data import DataLoader... | pd.DataFrame(data) | pandas.DataFrame |
"""
上市公司公告查询
来源:[巨潮资讯网](http://www.cninfo.com.cn/new/commonUrl?url=disclosure/list/notice-sse#)
备注
使用实际公告时间
如查询公告日期为2018-12-15 实际公告时间为2018-12-14 16:00:00
"""
import asyncio
from aiohttp.client_exceptions import ContentTypeError
import math
import time
import aiohttp
import logbook
import pandas as pd
import... | pd.DataFrame() | pandas.DataFrame |
"""
Generate ensemble submission by majority vote.
Authors:
<NAME> and <NAME>
"""
import argparse
import glob
import pandas as pd
parser = argparse.ArgumentParser('Get args for ensemble script')
parser.add_argument('--split',
type=str,
default='dev',
... | pd.DataFrame(data=d) | pandas.DataFrame |
"""Implement custom daily and weekly trading day calendars and datetime methods
- pandas custom business calendar
Author: <NAME>
License: MIT
"""
import datetime
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import pandas_datareader as pdr
from pandas.tseries.holiday import USFederalHoli... | MonthEnd(0) | pandas.tseries.offsets.MonthEnd |
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(camels_file, sep=",", dtype={"gauge_id": str}) | pandas.read_csv |
from typing import Iterable, Tuple
from ._account import Account
import pandas as pd
import numpy as np
from math import isfinite
from collections import OrderedDict
TRADE_KEYS = ('asset', 'date_entry', 'date_exit', 'side', 'n_transactions', 'wavg_price_entered', 'wavg_price_exited',
'qty_entered', 'qty... | pd.DataFrame(trade_tuples, columns=TRADE_KEYS) | pandas.DataFrame |
import pandas as pd
def filter_data(df,center,attr_name,tolerance=5):
lat_name,lon_name,_ = attr_name
return df[attr_name][(df[lat_name]>center[0]-tolerance) & (df[lat_name]<center[0]+tolerance) & (df[lon_name]>center[1]-tolerance) & (df[lon_name]<center[1]+tolerance)]
def convert_timestamp(df,time_name):
... | pd.to_datetime(df[time_name]) | pandas.to_datetime |
import pandas as pd
import numpy as np
#ads_1_sum,ads_2_sum是每个店铺90天的广告费用和
ads_all=pd.read_csv('../JDD_sale/dataset/sort_t_ads.csv')
ads_all['create_dt']= | pd.to_datetime(ads_all['create_dt']) | pandas.to_datetime |
import pandas as pd
import ibis
from ibis.backends.base.sql.compiler import Compiler
from .conftest import get_query
def test_simple_scalar_aggregates(con):
# Things like table.column.{sum, mean, ...}()
table = con.table('alltypes')
expr = table[table.c > 0].f.sum()
query = get_query(expr)
sq... | pd.DataFrame({'g': ['foo', 'bar', 'baz']}) | pandas.DataFrame |
import os
import yaml
import json
import pandas as pd
import matplotlib.pyplot as plt
from pylab import rcParams
import seaborn as sns
import numpy as np
from sklearn.linear_model import LinearRegression
import glob
import time
###############################################################################... | pd.DataFrame() | pandas.DataFrame |
"""Functions for saving proset reports to disk.
Copyright by <NAME>
Released under the MIT license - see LICENSE file for details
"""
from copy import deepcopy
import numpy as np
import pandas as pd
CELL_FORMAT = { # format definitions for xlsxwriter
"header_blue": {"font_name": "Calibri", "bold"... | pd.isna(report["batch"]) | pandas.isna |
import configparser
import datetime as dt
import logging
import os
import shutil
from pathlib import Path
from urllib.error import URLError
import matplotlib.image as mplimg
import pandas as pd
import pkg_resources as pr
from . import stats
from .exceptions import NoFilesFoundError
try:
from urllib import urlret... | pd.Series(image_names) | pandas.Series |
import pickle
from abc import ABC, abstractmethod # abstract base class
import numpy as np
import pandas as pd
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import torch
from .modelbuilder import (build_pytorch_nnet, defa... | pd.Series(li_score, name=metric_name, index=self.Y.columns) | pandas.Series |
####
#### July 2. This is a copy of the version we had from before. plotting one year.
#### Here we are extending it to 2 years. Since August of a given year to the end
#### of the next year.
####
import matplotlib.backends.backend_pdf
import csv
import numpy as np
import pandas as pd
# import geopandas as gpd
from I... | register_matplotlib_converters() | pandas.plotting.register_matplotlib_converters |
'''
Simple vanilla LSTM multiclass classifier for raw EEG data
'''
import scipy.io as spio
import numpy as np
from keras import backend as K
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
import pandas as pd
import matplotli... | pd.get_dummies(train_y['prompt']) | pandas.get_dummies |
import numpy as np
import pandas as pd
import anndata
import matplotlib.pyplot as plt
import seaborn as sns
from natsort import natsorted
def plot_adt_hist(adt, attr, out_file, alpha=0.5, dpi=500, figsize=None):
idx_signal = np.isin(adt.obs[attr], "signal")
signal = adt.obs.loc[idx_signal, "counts"]
backg... | pd.concat(dfs) | pandas.concat |
#################################################################
#################################################################
############### Clustergrammer
#################################################################
#################################################################
#######################... | pd.Series(index=sample_metadata.index, data=sample_metadata.index, name='Sample') | pandas.Series |
# License: Apache-2.0
import databricks.koalas as ks
import numpy as np
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
from gators.feature_generation.elementary_arithmethics import ElementaryArithmetics
@pytest.fixture
def data_add():
X = pd.DataFrame(np.arange(9).reshape(3, 3), ... | pd.DataFrame(X_numpy_new) | pandas.DataFrame |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2022/4/10 17:42
Desc: 东方财富网-数据中心-特色数据-股权质押
东方财富网-数据中心-特色数据-股权质押-股权质押市场概况: http://data.eastmoney.com/gpzy/marketProfile.aspx
东方财富网-数据中心-特色数据-股权质押-上市公司质押比例: http://data.eastmoney.com/gpzy/pledgeRatio.aspx
东方财富网-数据中心-特色数据-股权质押-重要股东股权质押明细: http://data.eastmoney.com/gpz... | c(temp_df['最新质押市值']) | pandas.to_numeric |
import pandas as pd
import numpy as np
import dateutil
import networkx as nx
ADULT_AGE = 18
def get_hmis_cp():
"""
Pull in relevant CSVs from `../data/`, merge them, clean them, and return a tuple containing the cleaned HMIS data
and the cleaned Connecting Point data.
"""
# get raw dataframes
... | pd.read_csv('../data/connecting_point/cp_client_duplicates_link_plus.csv') | pandas.read_csv |
import os
import glob
import collections
import cv2
import numpy as np
import pandas as pd
import pickle
import time
import settings
IMG_DIR = settings.IMG_DIR
VAL_FILE = settings.VAL_FILE
CLASS_FILE = settings.CLASS_FILE
BBOX_FILE = settings.BBOX_FILE
BBOX_BIN_FILE = os.path.join(settings.DATA_DIR, 'bbox.pk')
BBOX_BI... | pd.DataFrame({'fn': fns, 'bbox': mbb}, columns=['fn','bbox']) | pandas.DataFrame |
from backlight.strategies import filter as module
import pytest
import pandas as pd
import numpy as np
import backlight
import backlight.trades
from backlight.strategies.amount_based import simple_entry_and_exit
from backlight.asset.currency import Currency
@pytest.fixture
def symbol():
return "USDJPY"
@pytest... | pd.Timestamp("2018-06-06 00:04:00") | pandas.Timestamp |
import pandas as pd
import numpy as np
import math
Ratings= | pd.read_csv("/home/4/16B09737/Documents/src/user-collaborative-filtering/tour_score.csv") | pandas.read_csv |
class Pywedge_Charts():
'''
Makes 8 different types of interactive Charts with interactive axis selection widgets in a single line of code for the given dataset.
Different types of Charts viz,
1. Scatter Plot
2. Pie Chart
3. Bar Plot
4. Violin Plot
5. Box Plot... | pd.DataFrame(self.new_y, columns=new_y_cols) | 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.testing.assert_frame_equal(result, expected) | pandas.testing.assert_frame_equal |
"""
data_ops
This file contains access to data and methods for assembly of data.
- <NAME>, 2018
"""
import argparse
import os
import random
from collections import Counter, OrderedDict, defaultdict
import networkx as nx
import numpy as np
import pandas as pd
import scipy.io as sio
import tensorflow as tf
from log_c... | pd.read_csv(data_file, header=None, index_col=None, names=['from', 'to', 'rating']) | pandas.read_csv |
import os
import pandas as pd
import sp_util
from sp_util import OptionalStr
class DSException (Exception):
pass
class DataStore:
def __init__(self, root: OptionalStr = None, name: OptionalStr = None):
self.root: str = sp_util.root_or_default(root)
self.name: str = sp_util.name_or_default(name... | pd.DataFrame({f: [] for f in names}) | pandas.DataFrame |
import pandas as pd
import matplotlib.pyplot as plt
from pyshop import ShopSession
license_path = r''
shop = ShopSession(license_path='', silent=False)
# Set time resolution
starttime = pd.Timestamp('2018-02-27')
endtime = pd.Timestamp('2018-02-28')
shop.set_time_resolution(starttime=starttime, endtime=endtime, time... | pd.Timedelta(hours=1) | pandas.Timedelta |
import warnings
import pandas as pd
warnings.filterwarnings('ignore')
import time
from autox.autox_server.util import log
from tqdm import tqdm
def fe_window(G_df_dict, G_data_info, G_hist, is_train, remain_time):
# 对G_df_dict['BIG']表做扩展特征
start = time.time()
log('[+] feature engineer, window')
big_... | pd.DataFrame() | pandas.DataFrame |
import os
import streamlit as st
import pandas as pd
import altair as alt
import sqlite3
from sqlite3 import Connection
import requests
import json
import plotly.express as px
# spotify stuff
SPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID')
SPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET')
def ge... | pd.read_sql(f'select song, date, album, round(avg({feature}),2) as avg_feature from acoustic_features where artist="<NAME>" group by album', con=conn) | pandas.read_sql |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import pandas as pd
import numpy as np
import pathlib
import pickle
from datetime import datetime, timezone
from emhass.retrieve_hass import retrieve_hass
from emhass.optimization import optimization
from emhass.forecast import forecast
from emhass.utils i... | pd.DataFrame() | pandas.DataFrame |
import glob
import pandas as pd
import numpy as np
import config
from lcoc import afdc
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
##### Functions #####
###################
### Residential ###
###################
def res_rates_to_utils(scenario = 'baseline',
... | pd.read_csv(dcfc_lcoc_file) | pandas.read_csv |
"""
The main module for Atomic pattern dictionary, jjoiningthe atlas estimation
and computing the encoding / weights
Copyright (C) 2015-2020 <NAME> <<EMAIL>>
"""
from __future__ import absolute_import
import logging
import os
import time
# to suppress all visual, has to be on the beginning
import matplotlib
if os.e... | pd.DataFrame(list_times) | pandas.DataFrame |
# coding=utf-8
# !/usr/bin/env python3
import os, re
import numpy as np
import pandas as pd
def svLen(sv_data):
data_grab = re.compile("^.*SVLEN=(?P<sv_len>-?[0-9]+).*$")
if 'SVLEN' in str(sv_data['INFO'].iloc[0]):
data_info = data_grab.search(sv_data['INFO'].iloc[0]).groupdict()
sv... | pd.DataFrame(columns=sv_data.columns) | 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.DataFrame({}) | pandas.DataFrame |
import time
import numpy as np
import pandas as pd
pd.plotting.register_matplotlib_converters()
from pandas_datareader import data as pd_data
from fbprophet import Prophet
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import STL
def get_ticker_data(ticker, start_date, end_date):
retry_cnt, max_... | pd.DataFrame() | pandas.DataFrame |
import scipy.sparse
import pickle
import gzip
import pandas as pd
import numpy as np
import scipy.io
import os, sys, re
import logging
def _load_items(dirname, **kwargs):
name = kwargs.get('name')
column = kwargs.get('column', -1)
trim_suffix = kwargs.get('trim', False)
fbz = os.path.join(dirname, f'{n... | pd.read_csv(fn_cache, sep='\t', dtype=np.int32) | pandas.read_csv |
import pandas as pd
import numpy as np
import random
import datetime
import os
def max_price(df):
return max(df['close'])
def max_close_date(df):
return pd.to_datetime(max_price_row(df).date.iloc[0])
def max_price_row(df):
r, c = df[df['close'] == max_price(df)].shape
try:
if r == 1:
... | pd.read_csv(path+name) | pandas.read_csv |
from unittest import result
import pytest
import stockeasy
import logging
import pandas as pd
df_stocklist = pd.DataFrame([['VTSAX', 120], ['MSFT', 100]], columns=['symbol', 'sharesOwned'])
df_stocklist_meta = pd.DataFrame(columns=['symbol', 'sharesOwned'])
def test_init():
assert 1 == 1
# Default Contract Ch... | pd.DataFrame([['vtsax', 120], ['msft', 100]], columns=['symbol', 'sharesOwned']) | pandas.DataFrame |
import numpy as np
import pandas as pd
import streamlit as st
import importlib
import os
import sys
import time
def file_selector(folder_path='.'):
filenames = os.listdir(folder_path)
filenames_ = [f for f in filenames if f[-3:] == "txt"]
selected_filename = st.selectbox('Select a file', filenames_)
... | pd.read_csv("./TAGS.csv", index_col=0) | pandas.read_csv |
# -*- coding: utf-8 -*-
'''
Copyright 2018, University of Freiburg.
Chair of Algorithms and Data Structures.
<NAME> <<EMAIL>>
'''
import urllib
import codecs
import os
import glob
import http
from time import sleep
import pandas as pd
from bs4 import BeautifulSoup
import nltk
from nltk.tokenize import sent_tokenize
f... | pd.DataFrame() | pandas.DataFrame |
# Import containerclass with static data for use of FingridApi services.
#from statics import FingridApiStatics
# Import libraries
from ratelimit import limits
import datetime
import difflib
import requests
import pandas as pd
class FingridOpenDataClient():
'''
Pythonic Client Module, for interaction with th... | pd.DataFrame(df_dict) | pandas.DataFrame |
#Autre test pour le filtre des musées sur les villes, qui vérifie la correspondance de manière plus précise.
import sys
import os
from pathlib import Path
scriptpath = Path(os.path.dirname(os.path.abspath(__file__))).parent
sys.path.insert(0,str(scriptpath))
import pandas as pd
from data_extraction.filtre_base_de_don... | isnull(x) | pandas.isnull |
#######################################
# Input Example ::
# python hotspot_predict.py -lat 11.05 -long 76.1 -rad 0.2 -hpts 5
#######################################
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import math
from tensorflow.keras.models import Sequential
from ten... | pd.read_csv('hotspots_fake_data.csv') | pandas.read_csv |
import pandas as pd
import numpy as np
import os
import json
import openpyxl
import pickle
import PySimpleGUI as sg
from keras_bert import load_trained_model_from_checkpoint
from keras_bert import get_custom_objects
from keras import Input, Model
from keras.models import load_model
from preprocessing import preproc... | pd.read_csv('./datasets/df_text.csv') | pandas.read_csv |
import numpy as np
import vigra
from ilastikrag import Rag
from ilastikrag.util import generate_random_voronoi
from ilastikrag.accumulators.edgeregion import EdgeRegionEdgeAccumulator
class TestEdgeRegionEdgeAccumulator(object):
def test1(self):
superpixels = generate_random_voronoi((100,200), 200)
... | pd.merge(features_df, transposed_features_df, how='left', on=['sp1', 'sp2'], suffixes=('_orig', '_transposed')) | pandas.merge |
"""
Module for processing and handling replays
"""
# Todo move into module
import asyncio
import lzma
from base64 import b64decode, b64encode
from io import StringIO
import bezier
import numpy as np
import pandas as pd
import requests
class DegenerateTriangle(Exception):
pass
def lzma_replay_to_df(lzma_byte_s... | pd.Series() | pandas.Series |
# --------------------------------------------------------------------------------------------------
# Copyright (c) 2021 Microsoft Corporation
#
# 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 Softw... | pd.concat(run_dfs) | pandas.concat |
import pandas as pd
import pandas.testing as pdt
import pytest
import pytz
from werkzeug.exceptions import RequestEntityTooLarge
from sfa_api.conftest import (
VALID_FORECAST_JSON, VALID_CDF_FORECAST_JSON, demo_forecasts)
from sfa_api.utils import request_handling
from sfa_api.utils.errors import (
BadAPIRequ... | pdt.assert_frame_equal(test_df, null_df) | pandas.testing.assert_frame_equal |
import requests
from typing import Dict, List, Optional
import sys
from pathlib import Path
import os
from shutil import rmtree
import json
import pandas as pd
import click
from joblib import Memory
from datetime import date, timedelta
# this removes cache every day to invalidate
today = date.today()
yesterday = today... | pd.DataFrame(rows, columns=cols) | pandas.DataFrame |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2021 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import pandas as pd
from numpy import allclose, isclose
from pandapower.pf.runpp_3ph import runpp_3ph
from pandapower.results impo... | pd.Series(data=0., index=net.bus.index) | pandas.Series |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# General
import pandas as pd
import numpy as np
from IPython.display import display
import warnings
warnings.filterwarnings("ignore",category=DeprecationWarning)
#Propias
import metricas
import bautizo_prepago as bt
import config_bt_prepago as cf
l_gral_lema_stem = cf... | pd.concat([Pred_M1, Pred_M2, Pred_M3], axis=1) | pandas.concat |
import pandas as pd
import os
# where to save or read
CSV_DIR = 'OECD_csv_datasets'
PROCESSED_DIR = 'OECD_csv_processed'
# datafile = 'OECD_csv_processed/industry_candidates.csv'
if not os.path.exists(PROCESSED_DIR):
os.makedirs(PROCESSED_DIR)
# STAGE 3:
def standardize_data(dset_id, df):
# standardized col... | pd.DataFrame(columns=def_cols) | pandas.DataFrame |
import datetime
import numpy as np
import pandas as pd
import requests
from pandas.tseries.offsets import BDay
from fixed_income import util
DATE_FORMAT = "%Y%m%d"
TREASURY_KINDS = ("Bill", "Note", "Bond", "CMB", "TIPS", "FRN")
SECURITY_FIELDS = [
"cusip",
"issueDate",
"securityType",
"securityTerm",... | pd.read_html(response.text) | pandas.read_html |
import pandas as pd
def trades_to_candles(trades_data, price_column="price", timestamp_column="created_at", amount_column="amount",
time_interval="1min"):
"""
This function takes the trades data frame and gets candles data.
:param pd.DataFrame trades_data: Trades data frame.
:pa... | pd.NamedAgg(column=amount_column, aggfunc="sum") | pandas.NamedAgg |
import datetime
import hashlib
import os
import time
from warnings import (
catch_warnings,
simplefilter,
)
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Series,
Timestamp,
concat,
date_range,
timedelt... | Index(data) | pandas.Index |
# -*- coding: utf-8 -*-
"""MLBA_Hakathon_fin
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1SKr50EBzZcYaqyl9jx5PxEvdUu70PjMj
"""
#Importing libraries
import glob
import pandas as pd
import numpy as np
import sys, getopt
import tensorflow as tf
import... | pd.concat(res, axis=1) | pandas.concat |
# -*- coding: utf-8 -*-
import re
import warnings
from datetime import timedelta
from itertools import product
import pytest
import numpy as np
import pandas as pd
from pandas import (CategoricalIndex, DataFrame, Index, MultiIndex,
compat, date_range, period_range)
from pandas.compat import PY... | pd.MultiIndex.from_arrays([lev1, lev2], names=['Name', 'Number']) | pandas.MultiIndex.from_arrays |
"""SQL io tests
The SQL tests are broken down in different classes:
- `PandasSQLTest`: base class with common methods for all test classes
- Tests for the public API (only tests with sqlite3)
- `_TestSQLApi` base class
- `TestSQLApi`: test the public API with sqlalchemy engine
- `TestSQLiteFallbackApi`: t... | tm.makeTimeDataFrame() | pandas._testing.makeTimeDataFrame |
"""
The ``expected_returns`` module provides functions for estimating the expected returns of
the assets, which is a required input in mean-variance optimization.
By convention, the output of these methods is expected *annual* returns. It is assumed that
*daily* prices are provided, though in reality the functions are ... | pd.DataFrame(prices) | pandas.DataFrame |
import covasim as cv
import covasim.defaults as cvd
import covasim.utils as cvu
import numba as nb
import numpy as np
import pandas as pd
from collections import defaultdict
def generate_people(n_people: int, mixing: pd.DataFrame, reference_ages: pd.Series, households: pd.Series) -> cv.People:
'''
From d... | pd.isna(self.dispersion) | pandas.isna |
import pandas as pd
import json
import os
import numpy
import glob
from zipfile import ZipFile
### -------------------------------------Test and Help function -------------------------------------------------------
def test_me():
print("Hello World")
def help():
print('''
---------------------------------... | pd.merge(df, day_visits_exp, on=[place_key,file_key]) | pandas.merge |
# Arithmetic tests for DataFrame/Series/Index/Array classes that should
# behave identically.
# Specifically for datetime64 and datetime64tz dtypes
from datetime import (
datetime,
time,
timedelta,
)
from itertools import (
product,
starmap,
)
import operator
import warnings
import numpy as np
impo... | tm.assert_numpy_array_equal(result, expected) | pandas._testing.assert_numpy_array_equal |
from __future__ import division
import numpy as np
import pandas as pd
import sys, os, csv
from src.utils import metadataExtractor, cxpPrinter
from src.analysis import extractFeaturesFromWell
from skimage.filters import threshold_otsu
def getPeakThreshold(config,wellmapping):
cxpPrinter.cxpPrint('Calculating peak... | pd.concat(dataframes_norm) | pandas.concat |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 16 09:04:46 2017
@author: <NAME>
pygemfxns_plotting.py produces figures of simulation results
"""
# Built-in Libraries
import os
import collections
# External Libraries
import numpy as np
import pandas as pd
#import netCDF4 as nc
import matplotlib as mp... | pd.read_csv(kaab_dict_fn) | pandas.read_csv |
import unittest
from pandas import (
Timestamp,
DataFrame,
concat,
MultiIndex
)
from toolbox.constitutes.constitute_adjustment import ConstituteAdjustment
class ConstituteAdjustmentTest(unittest.TestCase):
def examples(self):
self.foo_constitutes = DataFrame(data=[
# symbol ... | Timestamp('2010-01-07', tz='UTC') | pandas.Timestamp |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | DataFrame.from_records(records) | pandas.DataFrame.from_records |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Race-car Data Creation Class.
This script contains all utilities to create proper dataset.
Revision History:
2020-05-10 (Animesh): Baseline Software.
2020-08-22 (Animesh): Updated Docstring.
Example:
from _data_handler import DataHandler
"""... | pd.DataFrame(dev4,columns=["image"]) | pandas.DataFrame |
import csv
import pandas as pd
import seaborn as sns
class Recommendation(object):
def similarMovie(self):
sns.set_style('dark')
'exec(%matplotlib inline)'
ratings_data = pd.read_csv(r"C:\Users\<NAME>\Videos\ml-latest-small\ratings.csv")
ratings_data = pd.read_csv(r"C:\Users\<NAME>a\Videos... | pd.read_csv(r"C:\Users\<NAME>a\Videos\ml-latest-small\movies.csv") | pandas.read_csv |
# %%
# practice computer vision competition
# https://www.kaggle.com/c/digit-recognizer/
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.callbacks import EarlyStopping
from sklearn.model_selection import train_test_split
import pandas as pd
import seaborn as sns
import numpy as np
im... | pd.DataFrame(history.history) | pandas.DataFrame |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Credits: <NAME>, <NAME>
import os
os.environ["CUDA_VISIBLE_DEVICES"] = ""
os.environ["TF_XLA_FLAGS"] = "--tf_xla_cpu_global_jit"
# loglevel : 0 all printed, 1 I not printed, 2 I and W not printed, 3 nothing printed
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import fire
impo... | pd.concat([df_1000, df_500], ignore_index=True) | pandas.concat |
import typing
import pandas as pd
import copy
import os
import random
import collections
import typing
import logging
import json
import re
import io
import string
import time
import cgitb
import sys
from ast import literal_eval
from itertools import combinations
from d3m import container
from d3m import utils
from d3... | pd.to_datetime(right_df[right_join_column_name]) | pandas.to_datetime |
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import copy
import numpy as np
import random
import math
from creature_ability_list import creature_ability_dict
from creature_ability_conditions import creature_ability_condition_dict
from spell_ability_list import spell_ability_dict
from amulet_ability_l... | pd.DataFrame([sample], columns=my_columns) | pandas.DataFrame |
import numpy as np
import operator
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import pandas as pd
import sys
#Function to calculate PCA
def CalculatePCA(pdata):
cv_mat = np.cov(pdata.T)
eig_val,eig_vec = np.linalg.eigh(cv_mat)
eig_vec = eig_vec.transpose()
d = dict()
for i in... | pd.DataFrame(SVDData) | pandas.DataFrame |
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import math
import random
import operator
import sys
sys.setrecursionlimit(10000)
xl= | pd.ExcelFile("mpd2018.xlsx") | pandas.ExcelFile |
import pandas as pd
import os, glob
def get_negative_cols(pais,hh_df):
try: negative_dict = pd.read_csv('output/hh_survey_negative_values.csv').set_index('pais')
except: negative_dict = pd.DataFrame(columns=['negative_values'])
negative_cols = [_c for _c in hh_df.columns if ((hh_df[_c].dtype == 'float32'... | pd.read_csv('./output/percent_of_survey_dropped_negative_values.csv') | pandas.read_csv |
from google.cloud import bigquery, firestore
import json
import pandas as pd
import time
import requests
import geojson
import numpy as np
from matplotlib.path import Path
from time import sleep
def get_all_region_info():
if not hasattr(get_all_region_info, "updateTime"):
get_all_region_info.updateTime =... | pd.DataFrame(results) | pandas.DataFrame |
#
# Copyright 2015 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | pd.Timestamp("2015-06-28", tz="UTC") | pandas.Timestamp |
# Copyright (c) Facebook, Inc. and its affiliates.
from factor_learning.utils import utils
from factor_learning.dataio.DigitImageTfDataset import DigitImageTfDataset
from factor_learning.dataio.DigitImageTfPairsDataset import DigitImageTfPairsDataset
from subprocess import call
import os
from scipy import linalg
impo... | scatter_matrix(data_frame) | pandas.plotting.scatter_matrix |
"""
Test the _dummy module.
"""
import re
import numpy as np
import pandas as pd
from sklearn.model_selection import ParameterGrid
import pytest
from sportsbet.datasets import DummySoccerDataLoader
def test_get_all_params():
"""Test all parameters."""
dataloader = DummySoccerDataLoader()
all_params = d... | pd.Timestamp('5/4/1997') | pandas.Timestamp |
import os
import shutil
#import re
import sys
import platform
import subprocess
import numpy as np
import json
import pickle
import pandas as pd
from pandas import Series
import xml.etree.ElementTree as ET
import glob
import argparse
try:
import lvdb
except:
import pdb as lvdb
print('using pdb instead of lv... | pd.DataFrame() | pandas.DataFrame |
""" I/O functions of the aecg package: tools for annotated ECG HL7 XML files
This module implements helper functions to parse and read annotated
electrocardiogram (ECG) stored in XML files following HL7
specification.
See authors, license and disclaimer at the top level directory of this project.
"""
# Imports ====... | pd.DataFrame([valrow2], columns=VALICOLS) | pandas.DataFrame |
from selenium import webdriver
import pandas
from flask import Flask, render_template
driver = webdriver.Chrome()
quotesList = []
author = []
tags = []
for i in range(1, 11):
url = 'http://quotes.toscrape.com/js/page/{}'.format(i)
driver.get(url)
quotes = driver.find_elements_by_class_name... | pandas.DataFrame(quotesList, columns=['Quote', 'Author', 'Tags']) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 21 11:44:20 2019
@author: tanma
"""
import pandas as pd, numpy as np
from sklearn.preprocessing import StandardScaler
from keras.models import Model
from keras.callbacks import ModelCheckpoint
from keras.layers import Input, SpatialDropout1D, GRU, LSTM,Conv1D, concatenat... | pd.concat(cols, axis=1) | pandas.concat |
#%%
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import pandas as pd
import seaborn as sns
import phd.viz
import phd.stats
import pickle
colors, palette = phd.viz.phd_style()
constants = phd.thermo.load_constants()
# Load the data set
data = pd.read_csv('../../data/ch2_in... | pd.DataFrame([]) | pandas.DataFrame |
from src.prime_system import PrimeSystem
import pytest
import pandas as pd
import numpy as np
import numpy.testing
L = 100
rho = 1025
@pytest.fixture
def ps():
yield PrimeSystem(L=L,rho=rho)
def test_dict_prime(ps):
length = 10
values = {
'length' : length,
}
units = {
'length' :... | pd.DataFrame() | pandas.DataFrame |
# -*- coding: utf-8 -*-
#
# 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
... | pd.DataFrame(res['data']) | pandas.DataFrame |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | is_object_dtype(self.dtype) | pandas.api.types.is_object_dtype |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 15:00:00 2018
@author: <NAME>
"""
import numpy as np
import pandas as pd
from scipy.spatial import Voronoi, ConvexHull
import signature.calculations as calc
from functools import partial
class MixedCrystalSignature:
"""Class for calculation ... | pd.DataFrame() | pandas.DataFrame |
#!python3
"""
Download gene expression data from the GDC (TCGA) database.
"""
import os
import errno
import logging
import re
import glob
import gzip
import shutil
import requests
import pandas as pd
logging.basicConfig(filename='./annotation/download.log', level=logging.INFO)
try:
os.chdir("/home/... | pd.read_csv(manifest, sep="\t") | pandas.read_csv |
from builtins import range
import pandas as pd
import numpy as np
from functools import partial
from multiprocessing import cpu_count, Pool
from tensorflow.keras.utils import Progbar
from chemml.chem import Molecule
from chemml.utils import padaxis
class CoulombMatrix(object):
"""
The implementation of cou... | pd.DataFrame(sorted_cm) | pandas.DataFrame |
import pandas as pd
import glob
import csv
files = [
"a100-results.csv",
"clx-1S-results.csv",
"clx-results.csv",
"gen9-results.csv",
"mi100-results.csv",
# "rome-results-aocc.csv",
"rome-results-cce.csv"]
csv_frames = []
for f in files:
csv_frames.append( | pd.read_csv(f, skipinitialspace=True) | pandas.read_csv |
# Copyright 2021 Research Institute of Systems Planning, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | pd.DataFrame.from_dict(self._lifecycle_state_machines) | pandas.DataFrame.from_dict |
import os
import pathlib
import pickle
import random
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from S2S_load_sensor_data import read_data_datefolder_hourfile
from S2S_settings import settings
FPS = settings["FPS"]
FRAME_INTERVAL = settings["FRAME_INTERVAL"]
sample_counts = settings... | pd.Timedelta("30ms") | pandas.Timedelta |
# -*- coding: utf-8 -*-
"""
Created 23 April 2019
mean_traces.py
Version 1
The purpose of this script is to pull all of the mean trace files that were
saved from the initial analysis. These traces are mean subtracted and filtered
and comprise the entire 6 s of recording. The idea here is to open the files
individually,... | pd.DataFrame() | pandas.DataFrame |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from copy import deepcopy
import numpy as np
import pandas as pd
import networkx as nx
import statsmodels.formula.api as smf
import statsmodels.api as sm
from scipy.cluster.vq import kmeans, whiten, vq
from gmeterpy.core.readings import Readings
from gm... | pd.DataFrame() | pandas.DataFrame |
import pandas as pd
import sys
import glob
import os
import re
import numpy as np
import logging
logging.basicConfig(stream=sys.stdout,
level=logging.INFO,
format='[%(asctime)s] %(message)s',
datefmt='%Y/%m/%d %H:%M:%S')
#inside pathx (MD)
def time_freq_fi... | pd.DataFrame(moresecxy.iloc[i,:]) | pandas.DataFrame |
import os
import re
import config
import constants
import transform
import numpy as np
import pandas as pd
import matplotlib as mpl
from scipy.spatial import distance_matrix
import plotly as py
files_location = config.data_source_file_location
files = os.listdir(files_location)
def extract_data_ci(years):
pass
def ... | pd.read_csv(data_ci1_fullname, skiprows=2, usecols = constants.keep_columns_CI, encoding='ISO-8859-1') | pandas.read_csv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.