prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
import numpy as np
from pandas.tseries.holiday import USFederalHolidayCalendar
import datetime
import pandas as pd
def mape(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
def rmse(y_true, y_pred):
y_true, y_pred = np.array(y_... | pd.DataFrame(holidays) | pandas.DataFrame |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# %%capture
# Compile and import local pyrossgeo mo... | pd.read_csv("%s/commuter_networks.csv" % sim_config_path) | pandas.read_csv |
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from utils.utils import CONSTANTS
from utils.utils import publication_plot_pred_act, publication_plot_residuals
from use_crabnet import predict_crabnet
from use_densenet import predict_densen... | pd.read_csv(classics_results_csv) | pandas.read_csv |
#!/usr/bin/env python
# coding: utf-8
# In[62]:
import pandas as pd
import plotly.graph_objects as go
import france_data_management as data
import datetime as dt
from datetime import timedelta
from dateutil.relativedelta import relativedelta
PATH = "../../"
# In[63]:
df_vacsi = data.import_data_vacsi_fra()
# I... | pd.to_datetime(DATE_DEBUT) | pandas.to_datetime |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2022/3/21 17:40
Desc: 天天基金网-基金档案-投资组合
http://fundf10.eastmoney.com/ccmx_000001.html
"""
import pandas as pd
import requests
from bs4 import BeautifulSoup
from akshare.utils import demjson
def fund_portfolio_hold_em(symbol: str = "162411", date: str = "2020") -> ... | pd.DataFrame() | pandas.DataFrame |
from sapextractor.database_connection.interface import DatabaseConnection
from sapextractor.utils.string_matching import find_corr
import pandas as pd
from getpass import getpass
from sapextractor.utils import constants
import time
class OracleConnection(DatabaseConnection):
def __init__(self, hostname="127.0.0.1... | pd.DataFrame({x: [] for x in columns}) | pandas.DataFrame |
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from tkinter import filedialog
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from scipy.interpolate import make_interp_spline, BSpline
from mpldatacurso... | pd.read_csv(self.gainPerdaPath, header=2, engine='python') | pandas.read_csv |
"""
A warehouse for constant values required to initilize the PUDL Database.
This constants module stores and organizes a bunch of constant values which are
used throughout PUDL to populate static lists within the data packages or for
data cleaning purposes.
"""
import importlib.resources
import pandas as pd
import ... | pd.Int64Dtype() | pandas.Int64Dtype |
import yfinance as yf
import pandas as pd
import sys
from datetime import datetime
class FinanceAnalysis:
def analyze(self, best_n=25):
# Load data from file, generate data by running the `ticker_counts.py` script
date_created = datetime.today().strftime('%Y-%m-%d')
csv_filename = f"{dat... | pd.Series([tickerName, tickerIndustry, tickerClose, Low5d, High5d, change1d, change5d, change1mo]) | pandas.Series |
import pandas as pd
import numpy as np
from copy import deepcopy
import os
from data.download import DatasetDownloader
import tarfile
import sys
from scipy.interpolate import interp1d
from pyts.visualization import plot_paa
from pyts.transformation import PAA
import pickle
from scipy.spatial.distance import cdist, squa... | pd.to_datetime(start, unit="ms") | pandas.to_datetime |
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
from powersimdata.design.generation.clean_capacity_scaling import (
add_new_capacities_collaborative,
add_new_capacities_independent,
add_shortfall_to_targets,
)
def test_independent_new_capacity():
area_names = ["Pacific... | assert_frame_equal(targets[test_columns], expected_return[test_columns]) | pandas.testing.assert_frame_equal |
import glob
import os
import tarfile
import luigi
import pandas as pd
import wget
from research_user_interest.utils.template import GokartTask
class GetTextfileTask(GokartTask):
textfile_url: str = luigi.Parameter()
def run(self):
wget.download(self.textfile_url)
self.dump("get text file tas... | pd.DataFrame({"title": title, "body": body, "label": label}) | pandas.DataFrame |
#!/usr/bin/python3
#
# CS224W Fall 2019-2020
# @<NAME>, <NAME>, <NAME>
#
import datetime as datetime
import numpy as np
import os
import pandas as pd
import pathlib
# Where files listed in DATASETS are located.
DATASET_DIR = '/shared/data'
DATASETS = {
'bad': [
'iran_201906_1_tweets_csv_hashed.csv',
... | pd.concat(li, axis=0, ignore_index=True) | pandas.concat |
__author__ = 'saeedamen'
#
# Copyright 2015 Thalesians Ltd. - http//www.thalesians.com / @thalesians
#
# 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
... | pandas.read_csv("volsurface.csv") | pandas.read_csv |
#!/usr/bin/env python
# coding: utf-8
"""
This file is part of MADIP: Molecular Atlas Data Integration Pipeline
This module loads the data for step_1_collect_protein_data.ipynb jupyter notebook.
Age in days is only approximate and not involved in the downstream analysis. Qualitative age category is defined based on th... | pd.ExcelFile('../data/source_data/1-s2.0-S2211124717311889-mmc4.xlsx') | pandas.ExcelFile |
"""A script for running an already trained SSD model on a video, saving the result as
both a video file which can be inspected by humans, and also as a text file.
Only uses imageio for video input/output which is nice for when OpenCV
is built without video encoding support. """
import cv2
import imageio ... | pd.concat(all_detections) | pandas.concat |
"""Run unit tests.
Use this to run tests and understand how tasks.py works.
Example:
Create directories::
mkdir -p test-data/input
mkdir -p test-data/output
Run tests::
pytest test_combine.py -s
Notes:
* this will create sample csv, xls and xlsx files
* test_combine_(... | pd.concat([df11, df11]) | pandas.concat |
""" Functions to generate the set of endpoints for the time series
benchmark on the HiRID database"""
import glob
import logging
import math
import os
import os.path
import pickle
import random
import sys
import lightgbm as lgbm
import numpy as np
import pandas as pd
import skfda.preprocessing.smoothing.kernel_sm... | pd.concat(out_dfs, axis=0) | pandas.concat |
import streamlit as st
import pandas as pd
import altair as alt
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from imblearn.over_sampling import RandomOverSampler
from sklearn.metrics import confusion_matrix
################## CSS Stuff ########... | pd.read_csv(url) | pandas.read_csv |
import os
import pandas
from mlopenapp.pipelines import vectorization as vct,\
text_preprocessing as tpp, \
logistic_regression as lr, \
metrics as mtr
from mlopenapp.utils import io_handler as io
from mlopenapp.utils import plotter, data_handler
# These will be replaced by user input
train_paths = [
... | pandas.DataFrame() | pandas.DataFrame |
"""Tests for cell_img.common.df_style."""
from absl.testing import absltest
from cell_img.common import df_style
import numpy as np
import numpy.testing as npt
import pandas as pd
class DfStyleTest(absltest.TestCase):
def testColorizerWithInts(self):
values = [1, 2, 3, 4]
c = df_style.make_colorizer_from... | pd.Series(values) | pandas.Series |
#!/usr/bin/env python
# coding: utf-8
__author__ = "<NAME>"
"""
Dash Server for visualizing the decision boundrary of a DenseNet (or general CNN with adapdation) classifier.
Several parts regarding the DB handling are adapted from <NAME>, github.com/choosehappy
"""
# In[5]:
import re
import colorsys
import mat... | pd.DataFrame.from_dict(selectedData['points']) | pandas.DataFrame.from_dict |
import pandas as pd
from LS_STM import LSSTM
from data_makers import make_data_stm
from aiding_functions import load_obj
from sklearn.svm import SVC
import numpy as np
import matplotlib.pyplot as plt
raw_data = pd.read_csv('./finance_data/raw_data.csv')
raw_data['Date'] = | pd.to_datetime(raw_data['Date'], format='%Y-%m-%d') | pandas.to_datetime |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import itertools
import json
import operator
import os
from pathlib import Path
from pprint import pprint
import re
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.lines import Line2D
import numpy as np
import pandas as pd
import s... | pd.DataFrame(joined_data_circuits) | pandas.DataFrame |
# BSD 3-Clause License
#
# Copyright (c) 2019, <NAME>
# 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 source code must retain the above copyright notice, this
# list of ... | concat([results, result], axis=0, ignore_index=True, sort=False) | pandas.concat |
'''Tests for preprocess.py. '''
import pytest
import pandas as pd
import numpy as np
from titanic import preprocess
#
##### FIXTURES ####################################################################################
#
COLUMNS = ['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age',
... | pd.DataFrame(data=data, columns=COLUMNS) | pandas.DataFrame |
import sys
import traceback
import warnings
from . import jhu
import mechbayes.models.SEIRD
import pandas as pd
import matplotlib.pyplot as plt
import numpy as onp
import jax
import jax.numpy as np
from jax.random import PRNGKey
import numpyro
from numpyro.infer import MCMC, NUTS, Predictive
from pathlib import ... | pd.Timedelta("1d") | pandas.Timedelta |
#SPDX-License-Identifier: MIT
""" Helper methods constant across all workers """
import requests
import datetime
import time
import traceback
import json
import os
import sys
import math
import logging
import numpy
import copy
import concurrent
import multiprocessing
import psycopg2
import psycopg2.extensions
import cs... | pd.DataFrame(source_data) | pandas.DataFrame |
import unittest
import numpy as np
import pandas as pd
import random
import kMeans as k
class kMeans_spec(unittest.TestCase):
def setUp(self):
return 0
def test_random_element(self):
df = pd.DataFrame([[1,0,2],
[2,0,2.5],
[3,6,1.5]],None,['a1','a2','a3'])
... | pd.DataFrame() | pandas.DataFrame |
import pandas as pd
import numpy as np
import multiprocessing as mp
from tqdm import tqdm
import h5py
import os
###########################################
def match_profile_coords():
# After applying profile mask, the masked df_profile should match the df_beads on both coordinates and seq.
amino_acids = pd.r... | pd.read_csv(f'{local_rot_dir}/{fname}') | pandas.read_csv |
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import collections
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import Helper
import json
import os
import holoviews as hv
from holoviews import opts, dim
# hv.extension('bokeh')
hv.extension('matplotlib')... | pd.DataFrame(aux_data) | pandas.DataFrame |
#!/usr/bin/env python
# coding: utf-8
# # Generate local files with the received delta translated excel files
# Read file in added data order.
# In[1]:
import pandas as pd
import openpyxl
import json
import os
import re
import glob
import argparse
# In[2]:
def load_json_as_df(json_data):
out_df = pd.DataFr... | pd.concat([excel_df, sheet], axis=0) | pandas.concat |
import os
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from catboost import Pool
from catboost import CatBoostClassifier
import scipy.io.wavfile as wavfile
import python_speech_features.base as speech
class pohui:
def __init__(self):
... | pd.read_csv('data/random.csv') | pandas.read_csv |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import os, sys
from scipy.spatial import distance
from scipy.cluster import hierarchy
from scipy import stats
import matplotlib.patches as mpatches
import io
import base64
import random
from sklearn import preprocessing
from ... | pd.Series(cluster_labels, name='cluster', index=X_data.index) | pandas.Series |
# ----------------------------------------------------------------------------
# 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 |
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
import seaborn as sns
import gc
import calendar
import pickle
import os
from sklearn.preprocessing import StandardScaler
from os.path import join
from sklearn.metrics import confu... | pd.concat(Data,axis=0) | pandas.concat |
# -*- coding: utf-8 -*-
# pylint: disable-msg=E1101,W0612
from datetime import datetime, timedelta
import pytest
import re
from numpy import nan as NA
import numpy as np
from numpy.random import randint
from pandas.compat import range, u
import pandas.compat as compat
from pandas import Index, Series, DataFrame, isn... | Series(['A_B_C', 'B_C_D', 'E_F_G', 'EFGHEF']) | pandas.Series |
#Library of functions called by SimpleBuildingEngine
import pandas as pd
import numpy as np
def WALLS(Btest=None):
#Building height
h_building = 2.7#[m]
h_m_building = h_building / 2
h_cl = 2.7# heigth of a storey
#number of walls
n_walls = 7
A_fl = 48
#WALLS CHARACTERISTICS
#Orie... | pd.Series([0.1, 0.1, 0.1, 0.1, 0.1, 0, 0]) | pandas.Series |
#!/usr/bin/env python
# coding: utf-8
# # IRM Analysis
# This notebook will compare the performance of IRM on an unseen platform's worth of gene expression to that of ERM. These results will be used for the preliminary data section for Aim 2 in my prelim proposal.
#
# For more information on what IRM and ERM are, rea... | pd.DataFrame(result_dict) | pandas.DataFrame |
def test_get_number_rows_cols_for_fig():
from mspypeline.helpers import get_number_rows_cols_for_fig
assert get_number_rows_cols_for_fig([1, 1, 1, 1]) == (2, 2)
assert get_number_rows_cols_for_fig(4) == (2, 2)
def test_fill_dict():
from mspypeline.helpers import fill_dict
def test_default_to_regular... | pd.DataFrame([[1, 1, 1], [0, 0, 0], [1, 1, 1], [1, 0, 0]]) | pandas.DataFrame |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 4 14:42:02 2018
@author: rwilson
"""
import pandas as pd
import numpy as np
import scipy.linalg as linalg
import random
import os
import h5py
import matplotlib.pyplot as plt
import itertools
from numba import njit
from numba import prange
import o... | pd.to_datetime(staTime) | pandas.to_datetime |
__author__ = '<NAME>'
from sklearn.cluster import KMeans
import scipy.stats as stats
from collections import OrderedDict
import matplotlib.pyplot as plt
import math
import pandas as pd
import numpy as np
import operator
class Optimizer(object):
"""
Head of opmizer operations.
Provide statistic a... | pd.Series(True, name='Selected') | pandas.Series |
import ast
import importlib
import re
import numpy as np
import pandas as pd
import woodwork as ww
def import_or_none(library):
'''
Attemps to import the requested library.
Args:
library (str): the name of the library
Returns: the library if it is installed, else None
'''
try:
... | pd.isnull(longitude) | pandas.isnull |
## 1. Introduction ##
import pandas as pd
titanic_survival = | pd.read_csv("titanic_survival.csv") | pandas.read_csv |
# -*- coding: utf-8 -*-
""" test function application """
import pytest
from string import ascii_lowercase
from pandas import (date_range, Timestamp,
Index, MultiIndex, DataFrame, Series)
from pandas.util.testing import assert_frame_equal, assert_series_equal
from pandas.compat import product as ... | tm.assert_frame_equal(result, expected) | pandas.util.testing.assert_frame_equal |
"""
Copyright 2021 <NAME> - <EMAIL>
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 agree... | pd.DataFrame.from_dict(gd_image.info['bands']) | pandas.DataFrame.from_dict |
"""
pygemfxns_preprocessing.py is a list of the model functions that are used to preprocess the data into the proper format.
"""
# Built-in libraries
import os
#import glob
import argparse
# External libraries
import pandas as pd
import numpy as np
#import xarray as xr
#import netCDF4 as nc
#from time import strftime... | pd.read_csv(wgms_fp + wgms_id_fn, encoding='unicode_escape') | pandas.read_csv |
import re
import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame, Series
import pandas._testing as tm
from pandas.tseries.offsets import BDay
class TestXS:
def test_xs(self, float_frame, datetime_frame):
idx = float_frame.index[5]
xs = float_frame.xs(idx)
for ... | pd.Index([]) | pandas.Index |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import os
# In[2]:
train_encoded = pd.read_csv("../data/train_store_encoded_onehot.csv")
# In[3]:
train_df = pd.read_csv("../data/train.csv")
store_df = pd.read_csv("../data/store.csv")
# In[4]:
cate_df = store_df.apply... | pd.to_datetime(df["Date"]) | pandas.to_datetime |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 08:00:00 2020
@author: <NAME>
contact : <EMAIL>
Ceci correspond aux fonctions utilisées pour traiter les données dans le cadre du projet ODIASP
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import scipy
from scipy.ndimage impo... | pandas.read_csv(csv_path, delimiter=",") | pandas.read_csv |
"""Prepare plots of statistical significance of features."""
import os
from joblib import Parallel, delayed
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import seaborn as sns
from sklearn.inspection import partial_dependence
from camcan.processing import permutation_importance
from... | pd.read_hdf(CONNECT_DATA_CORR, key='basc197') | pandas.read_hdf |
import sys
from sqlalchemy import create_engine
import pandas as pd
import pickle
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomFo... | pd.Series(X) | pandas.Series |
# 지역, 서비스 코드 파서
import pandas as pd
import numpy as np
import re
import datetime
from .rq_class import *
from .search import findTag, parseAll
apinfo = ApiInfo('1a%2FLc1roxNrXp8QeIitbwvJdfpUYIFTcrbii4inJk3m%2BVpFvZSWjHFmOfWiH9T7TMbv07j5sDnJ5yefVDqHXfA%3D%3D', 'http://api.visitkorea.or.kr/openapi/service/rest/KorWith... | pd.DataFrame(result_tmp, columns=['tag1','code1','tag2','code2','tag3','code3']) | pandas.DataFrame |
import numpy as np
import pandas as pd
pd.set_option('display.expand_frame_repr', False)
from scipy.stats import mode
import warnings
import ntpath, pathlib
import copy
import itertools
import os
from .collect import Collect
# d6tcollect.init(__name__)
from .helpers import *
from .utils import PrintLogger
# *******... | pd.DataFrame(df_col_present, index=col_all) | pandas.DataFrame |
import webbrowser
import numpy as np
import pandas as pd
import tax_utils as tut
from tax_calculator import TaxCalculator
class NorwegianTax(TaxCalculator):
"""
to facilitate easy input
add random text to trigger a code push...
"""
def __init__(self, salary=0, birth_year=1978, tax_year=None, gain... | pd.DataFrame(out, columns=['tax_type', 'tax_basis', 'tax']) | pandas.DataFrame |
"""Get Names from Vornam Koeln.
Sources:
- Official Source: https://offenedaten-koeln.de/
- Download Samples: https://github.com/fxnn/vornamen
"""
import pandas as pd
urls = [
"https://offenedaten-koeln.de/sites/default/files/Vornamen_Koeln_2017.csv",
"https://offenedaten-koeln.de/sites/default/files... | pd.concat(names_dfs) | pandas.concat |
import base64
import io
import textwrap
import dash
import dash_core_components as dcc
import dash_html_components as html
import gunicorn
import plotly.graph_objs as go
from dash.dependencies import Input, Output, State
import flask
import pandas as pd
import urllib.parse
from sklearn.preprocessing import StandardSca... | pd.concat([PC_df_outlier_covar, Eigen_df_outlier_covar], axis=1) | pandas.concat |
import numpy as np
import matplotlib.pyplot as pls
import pandas as pd
import warnings
from IPython.display import display, HTML
import seaborn as sns
import lightgbm as lgb
from lightgbm import LGBMClassifier,LGBMRegressor
import shap
from .eda_anova import anova,two_way_anova,turkeyHSD
warnings.filterwarnings("ig... | pd.merge(cat_perc,cat_perc2,on=feature) | pandas.merge |
# coding: utf-8
import pandas as pd
import baostock as bs
from datetime import datetime, timedelta
lg = bs.login()
# 显示登陆返回信息
print('login respond error_code:' + lg.error_code)
print('login respond error_msg:' + lg.error_msg)
def get_stock_info(symbol):
rs = bs.query_stock_basic(code=symbol)
data_list = []
... | pd.concat(data, ignore_index=True) | pandas.concat |
"""
Author: <NAME>
Modified: <NAME>
"""
import os
import warnings
import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_almost_equal, assert_allclose
from statsmodels.tools.sm_exceptions import EstimationWarning
from statsmodels.tsa.holtwinters import (ExponentialSmoothing,
... | pd.Series(data, index) | pandas.Series |
import pytest
from mapping import mappings
from pandas.util.testing import assert_frame_equal, assert_series_equal
import pandas as pd
from pandas import Timestamp as TS
import numpy as np
from pandas.tseries.offsets import BDay
@pytest.fixture
def dates():
return pd.Series(
[TS('2016-10-20'), TS('2016-11... | pd.MultiIndex.from_product([[0, 1], ['front', 'back']]) | pandas.MultiIndex.from_product |
# Mar21, 2022
##
#---------------------------------------------------------------------
# SERVER only input all files (.bam and .fa) output MeH matrix in .csv
# August 3, 2021 clean
# FINAL github
#---------------------------------------------------------------------
import random
import math
import pysam
import csv
... | pd.read_csv(res_dir) | pandas.read_csv |
from hetdesrun.component.registration import register
from hetdesrun.datatypes import DataType
import pandas as pd
from scipy.signal import butter
from scipy.signal import lfilter
# ***** DO NOT EDIT LINES BELOW *****
# These lines may be overwritten if input/output changes.
@register(inputs={"data": DataType.Series,... | pd.Series(filtered, index=data.index) | pandas.Series |
import numpy as np
import pandas as pd
import xarray as xr
from raven import models
from .common import TESTDATA
import pytest
@pytest.mark.skip
class TestGR4JCemaneige():
def test_simple(self):
time = | pd.date_range('2000-01-01', freq='D', periods=365 * 3) | pandas.date_range |
# Implementation of support points generator
#
# Reference:
# <NAME>, "Support Points" (2018) *The Annals of Statistics*
__all__ = [
"tran_sp",
"tf_sp",
]
from grama import add_pipe
from numpy import diag, eye, ma, newaxis, number, zeros
from numpy.linalg import norm
from numpy.random import choice, multiva... | DataFrame(data=X, columns=var) | pandas.DataFrame |
import pandas as pd
import numpy as np
import logging
import os
import math
import logging
import sys
import os
import random
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
from global_variables import config as g
# ROOT_DIR = os.path.dirname(os.path.abspath("top_... | pd.read_csv(input_filepath + "loadcons.csv") | pandas.read_csv |
import pytest
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
import pandas as pd
from generators import (
generate_votes,
row_maker,
)
def test_row_keys():
voting_machine = row_maker()
row = voting_machine()
assert list(row.keys()) == ["timestamp", "... | pd.read_csv("data/region_data.csv", usecols=["region", "color"]) | pandas.read_csv |
import sys
import time
import pandas as pd
import numpy as np
import copyreg, types
from tqdm import tqdm
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-talk')
plt.style.use('bmh')
#plt.rcParams['font.family'] = 'DejaVu Sans Mono'
plt.rcParams['font.size'] = 9.5
... | pd.DataFrame(out) | pandas.DataFrame |
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTHS = ["january","february", "march", "april",\
"may","june","all"]
DAYS = ["monday","tuesday","wednesday","thursd... | pd.to_datetime(df['Start Time']) | pandas.to_datetime |
import streamlit as st
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from PIL import Image
from scrapping import DataFetcher
from models import Models
from seir import SeirModel
corona = Image.open('images/title_logo.png')
s... | pd.Timestamp('now') | pandas.Timestamp |
import pandas as pd
from pandas.testing import assert_frame_equal
from dtspec.core import markdown_to_df
# pylint: disable=redefined-outer-name
def test_convert_table_to_df():
given = """
| id | name |
| - | - |
| 1 | one |
| 2 | two |
| 3 | three |
"... | pd.DataFrame({"id": ["1", "2", "3"], "name": ["one", "#2", "three"]}) | pandas.DataFrame |
import datetime
import re
from warnings import (
catch_warnings,
simplefilter,
)
import numpy as np
import pytest
from pandas._libs.tslibs import Timestamp
import pandas as pd
from pandas import (
DataFrame,
HDFStore,
Index,
Int64Index,
MultiIndex,
RangeIndex,
... | ensure_clean_store(setup_path) | pandas.tests.io.pytables.common.ensure_clean_store |
from datetime import date
from flask import Flask, render_template, request, g
import json
import os
import socket
import pandas as pd
from redis import Redis
app = Flask(__name__)
redisurl = os.getenv('REDIS_URL')
hostname = socket.gethostname()
# Button Colour
buttoncolour = "blue"
button = './static/{}.png'.forma... | pd.read_json(raw) | pandas.read_json |
import datetime
from datetime import timedelta
from distutils.version import LooseVersion
from io import BytesIO
import os
import re
from warnings import catch_warnings, simplefilter
import numpy as np
import pytest
from pandas.compat import is_platform_little_endian, is_platform_windows
import pandas.util._test_deco... | pd.DataFrame({"A": [char]}) | pandas.DataFrame |
from collections import OrderedDict
import datetime
from datetime import timedelta
from io import StringIO
import json
import os
import numpy as np
import pytest
from pandas.compat import is_platform_32bit, is_platform_windows
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame... | tm.assert_frame_equal(result, expected) | pandas._testing.assert_frame_equal |
# Script designed to visulize the working time distribution from your time logger.
# Copyright © 2020 <NAME>
# Licensed under MIT License
import sys
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
f_name = sys.argv[1]
precision = str(sys.argv[2])
df = | pd.read_csv(f_name) | pandas.read_csv |
from collections import defaultdict
import pandas as pd
prefixs = defaultdict(int)
# https://www.kaggle.com/imoore/titanic-the-only-notebook-you-need-to-see/notebook
personal_titles = set(t.lower() for t in ["Mr.",
# "Miss.", != Miss
... | pd.get_dummies(X) | pandas.get_dummies |
__author__ = "saeedamen" # <NAME>
#
# Copyright 2016 Cuemacro
#
# 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 la... | pd.DatetimeIndex(delivery_date) | pandas.DatetimeIndex |
import pandas as pd
from utils.storage import load_frame, dump_frame, DATA_PATH, check_if_stepframe, check_if_vecframe
def daySplitter(step_name, data_path=DATA_PATH):
"""
Splits entries into days and saves results as vecframe.
"""
stepframe = load_frame(step_name, data_path)
check_if_stepframe(s... | pd.read_csv(data_path+ epochsfile) | pandas.read_csv |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
def perform_pca(data, n_components=3, y=None):
"""
data = Data on which to perform PCA
n_components = 3. This is the number o... | pd.concat([principal_comp, data[y]], axis=1) | pandas.concat |
# 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, ... | pd.testing.assert_frame_equal(result, expected_result) | pandas.testing.assert_frame_equal |
from flask import Flask
from flask import jsonify, send_from_directory
from flask import request
from flask import current_app
from flask import make_response
from flask import render_template
from flask_pymongo import PyMongo
import xsg
import pymortar
import pandas as pd
import pendulum
import toml
import pytz
impor... | pd.DataFrame(readings, index=times, columns=['readings']) | pandas.DataFrame |
# -*- coding: utf-8 -*-
'''
Script for grabbing a csv from a Google Sheet id and outputting JSON [compatible with Timeline JS](https://timeline.knightlab.com/docs/json-format.html)
Todo:
- Support for slide types
- Support for eras
- Support for scale
Usage: Update gsheet_id with Google Sheet ID below and run script... | pd.DataFrame(data) | pandas.DataFrame |
import numpy as np
from datetime import timedelta
from distutils.version import LooseVersion
import pandas as pd
import pandas.util.testing as tm
from pandas import to_timedelta
from pandas.util.testing import assert_series_equal, assert_frame_equal
from pandas import (Series, Timedelta, DataFrame, Timestamp, Timedelt... | TimedeltaIndex(['4 day', '3 day', '6 day'], name='idx') | pandas.TimedeltaIndex |
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.concat([thisjob_df, df_to_append], axis=1) | pandas.concat |
#!/usr/bin/env python
# coding: utf-8
# # 2019-01-21: Initial Data Exploration
#
# ### Authors
# * <NAME> (<EMAIL>)
# ## Preparations
# In[1]:
# --- Imports
# Standard libraries
import os
import re
# External packages
import matplotlib.pyplot as plt
import numpy
import pandas
# In[2]:
# --- Configuration Pa... | pandas.DataFrame() | pandas.DataFrame |
# http://github.com/timestocome
# take a look at the differences in daily returns for recent bull and bear markets
# http://afoysal.blogspot.com/2016/08/arma-and-arima-timeseries-prediction.html
# predictions appear to increase and decrease with actual returns but scale is much smaller
# of course if it was this eas... | pd.to_datetime('10-09-2002') | pandas.to_datetime |
import warnings
import pytest
from pandas import DataFrame, Series
import pandas._testing as tm
from pandas.core.algorithms import safe_sort
class TestPairwise:
# GH 7738
df1s = [
DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[0, 1]),
DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], column... | safe_sort(result.index.levels[1]) | pandas.core.algorithms.safe_sort |
import os
from io import BytesIO
import fastavro as fa
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.orc as orc
import pytest
import cudf
from cudf.tests.utils import assert_eq
if not os.environ.get("RUN_HDFS_TESTS"):
pytestmark = pytest.mark.skip("Env not configured to run HDFS test... | pd.read_csv(f) | pandas.read_csv |
from market import getMarket as gm
from market import getData as gd
from price import getPrice as gp
from dba import mysql as ms
from settings import config
import pandas as pd
import datetime
import time
# 插入市场信息
def insert_market():
# idList, name = gm.run()
idList = gd.get_id_list()
name = gd.get_name_list()
... | pd.DataFrame(df) | pandas.DataFrame |
"""
TRANSFORM
Create relevant statistics about Google trends data
for streamlit_app.py
"""
import pandas as pd
import logging
import streamlit as st
def create_query_date(df):
""" Day format of query_timestamp """
df['query_date'] = pd.to_datetime(df.query_timestamp).dt.date
return df
def dr... | pd.notnull(df.rank_t) | pandas.notnull |
import numpy as np
import pandas as pd
from sklearn.utils.estimator_checks import check_estimator
from autofeat import AutoFeatRegressor, AutoFeatClassifier
def get_random_data(seed=15):
# generate some toy data
np.random.seed(seed)
x1 = np.random.rand(1000)
x2 = np.random.randn(1000)
x3 = np.rand... | pd.isna(df.iloc[999, 1]) | pandas.isna |
import pandas as pd
from unittest import TestCase
from .sar import Reservoirs
from .hidro import Stations
from .hidro.serie_temporal import SerieTemporal
from .hidro import EntityApi
class TestApi(TestCase):
def test_get_stations_by_city(self):
recife = Stations(name_city="RECIFE")
piranhas = St... | pd.to_datetime(data, dayfirst=True) | pandas.to_datetime |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import datetime
import glob
import networkx
import numpy
import os
import pandas
import pickle
import networkx_analysis
nodes_overlap_species_nm_fns = [ networkx_analysis.nm_name_equal,
networkx_analysis.nm_name_clean_equal,
net... | pandas.DataFrame(node_match_reaction_data) | pandas.DataFrame |
from dataclasses import dataclass
import numpy as np
import pandas as pd
from os import path
from typing import Tuple
from osa import factory
from handlers.result import BaseResult
from handlers.file import get_setting, get_selected_file_path
from handlers.cache import load_only_array_results
@dataclass
class SaveD... | pd.DataFrame(data=trace, columns=["trace [dBm]"]) | pandas.DataFrame |
# PyLS-PM Library
# Author: <NAME>
# Creation: November 2016
# Description: Library based on <NAME>'s simplePLS,
# <NAME>'s plspm and <NAME>'s matrixpls made in R
import pandas as pd
import numpy as np
import scipy as sp
import scipy.stats
from .qpLRlib4 import otimiza, plotaIC
import scipy.linalg
from col... | pd.read_csv(Mcsv) | pandas.read_csv |
# Encoding: utf-8
""" SpineSession class
Spine session is used to load metadata information created using matlab SpineImaging class
It has load and save capabilities
"""
import copy
import io
import json
import os
import sys
import pickle
import logging
from builtins import input
import matplotlib
import matplotlib.... | pd.read_csv(f) | pandas.read_csv |
# %% [markdown]
# # 📃 Solution for Exercise 02
#
# This notebook aims at building baseline classifiers, which we'll use to
# compare our predictive model. Besides, we will check the differences with
# the baselines that we saw in regression.
#
# We will use the adult census dataset, using only the numerical features.
... | pd.Series(result_dummy["test_score"], name="Dummy score") | pandas.Series |
#!/usr/bin/env python
# coding: utf-8
# # Polifact_Analysis
#
# ### @Author : <NAME>
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
import plotly.express as px
from scipy import signal
import warnings
warnings.filterwarnings("ignore... | pd.set_option('display.max_colwidth', 200) | pandas.set_option |
# Parameters
XGB_WEIGHT = 0.6200
BASELINE_WEIGHT = 0.0200
OLS_WEIGHT = 0.0700
NN_WEIGHT = 0.0600
XGB1_WEIGHT = 0.8000 # Weight of first in combination of two XGB models
BASELINE_PRED = 0.0115 # Baseline based on mean of training data, per Oleg
import numpy as np
import pandas as pd
import xgboost as xgb
from skl... | pd.read_csv("../input/train_2016_v2.csv") | pandas.read_csv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.