prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
from typing import Dict
import pandas as pd
import datetime as dt
from src.typeDefs.stateConfig import IStateConfig
from src.typeDefs.stateslinesMeasRecord import IGenLineDataRecord
from typing import List
def getGenLinesDailyData(statesConfigSheet: List[IStateConfig], targetFilePath: str) -> List[List]:
all... | pd.melt(dataSheeetDf, id_vars=['Date']) | pandas.melt |
import pandas as pd
def get_raw_data(fname, cols_to_read, limit_rows=True, nrows=100):
path = f"./1.desired_subset_of_raw_data/{fname}.csv"
if limit_rows:
df = pd.read_csv(path, nrows=nrows, index_col="ACCOUNT_NUM", usecols=cols_to_read)
else:
df = | pd.read_csv(path, index_col="ACCOUNT_NUM", usecols=cols_to_read) | pandas.read_csv |
# %% 说明
# ------------------------------------------------------------------->>>>>>>>>>
# 最后更新ID name的时候用这个脚本,从师兄的list汇总完成替换
# os.chdir("/Users/zhaohuanan/NutstoreFiles/MyNutstore/Scientific_research/2021_DdCBE_topic/Manuscript/20220311_My_tables")
# ------------------------------------------------------------------->>... | pd.ExcelWriter('20220308_TargetSeqInfoForBarPlot_fixmin.xlsx') | pandas.ExcelWriter |
import os
# Enforce CPU Usage
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # Uncommenting enforces CPU usage # Commenting enforces GPU usage
# Seed the Random-Number-Generator in a bid to get 'Reproducible Results'
import tensorflow as tf
from keras import backend as K
from numpy.random import seed
seed(1)
tf.compat.v... | pd.DataFrame(unlink_ties_score) | pandas.DataFrame |
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
import osmnx as ox
import pandas as pd
import numpy as np
import geopandas as gpd
import networkx as nx
import math
from math import sqrt
import ast
import functools
from shapely.geometry import Point, LineString
pd.set_option("display.pre... | pd.DataFrame(columns=['u','v', 'geometry', 'length']) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 17:15:16 2020
@author: JAVIER
"""
import numpy as np
import pandas as pd
import pickle
from .. import bci_architectures as athena
from . import bci_penalty_plugin as bci_penalty
from .. import load_brain_data as lb
from Fancy_aggregations import penalties as pn
from... | pd.DataFrame(accuracies_test) | pandas.DataFrame |
import numpy as np
import matplotlib.pyplot as pl
import pandas as pd
sheets = pd.read_excel('Family Predictions 2022.xlsx', sheet_name=None)
questions = sheets.pop('Main')
player_sheets = sheets
player_sheets.keys()
questions['ID'] = questions['ID'].astype(int)
questions.set_index('ID')
questions = questions.drop(['C... | pd.DataFrame(data=guesses) | pandas.DataFrame |
import decimal
import numpy as np
from numpy import iinfo
import pytest
import pandas as pd
from pandas import to_numeric
from pandas.util import testing as tm
class TestToNumeric(object):
def test_empty(self):
# see gh-16302
s = pd.Series([], dtype=object)
res = to_numeric(s)
... | tm.assert_series_equal(res, s) | pandas.util.testing.assert_series_equal |
import pandas as pd
import spell
from curami.commons import file_utils
'''
find spelling mistakes of identified similar pairs in previous step
'''
match_ratio = 0.85
def analyze():
attributes = | pd.read_csv(file_utils.matched_attributes_file, encoding=file_utils.encoding) | pandas.read_csv |
#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting
# ms-python.python added
import os
try:
os.chdir(os.path.join(os.getcwd(), 'eddy_src/q_learning_stock'))
print(os.getcwd())
except:
pass
import indicators
impo... | pd.read_csv(portfolio_report_path) | pandas.read_csv |
import pandas as pd
from datetime import datetime
import numpy as np
import scipy.stats as ss
from sklearn import preprocessing
data_root = '/media/jyhkylin/本地磁盘1/study/数据挖掘竞赛/SMPCUP2017/'
post_data = pd.read_table(data_root+'SMPCUP2017dataset/2_Post.txt' ,sep='\001' ,names=['userID' ,'blogID' ,'date'])
browse_data... | pd.DataFrame(index=userList) | pandas.DataFrame |
"""initialize gui by reading in images specified by user inputs in notebooks/label.ipynb"""
import cocpit
import os
import pandas as pd
from typing import Tuple
import itertools
def read_parquet(
year: int, time_of_day: str, precip_threshold: float, precip: str
) -> Tuple[pd.DataFrame, str]:
"""
Read a t... | pd.DataFrame({"path": all_classes}) | pandas.DataFrame |
"""
Tests for the simulation codebase.
"""
from __future__ import division
import numpy as np
import pandas as pd
import pytest
import multiprocessing
from choicemodels import MultinomialLogit
from choicemodels.tools import (iterative_lottery_choices, monte_carlo_choices,
MergedChoiceTable, parallel_lottery_... | pd.DataFrame(d1) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""# 基於內容推薦"""
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import paired_distances,cosine_similarity
movies = pd.read_csv('./ml-latest-small/movies.csv')
rate = pd.read_csv('./ml-latest-small/ratings.csv')
display(movies.head())
display(rate.head())
# movies留下movieI... | pd.concat([df, oneHot], axis=1) | pandas.concat |
'''
Functions used to compute and compare TOP_K KDE or IsolationForest scores for on different ports, in order to determine top ranked most anomalous time windows.
'''
# --- Imports ---
from sklearn.preprocessing import MinMaxScaler
import scipy.integrate as integrate
import pandas as pd
import numpy as np
import tim... | pd.DataFrame(df, columns=col_headers) | pandas.DataFrame |
import pandas as pd
from datetime import datetime
from sklearn.preprocessing import LabelEncoder, label_binarize
from sklearn.ensemble import RandomForestClassifier
train_payments_file = 'data/qiwi_payments_data_train.csv'
train_users_file = 'data/qiwi_users_data_train.csv'
# test files
test_payments_file = 'data/qiwi... | pd.concat([train, train_cat_bin], axis=1) | pandas.concat |
#!/usr/bin/env python
# coding: utf-8
"""
Created on Mon November 10 14:13:20 2019
@author: <NAME>
takes the condition name as input (e.g. lik or int)
"""
def covariate (cond):
# data analysis and wrangling
import pandas as pd
import numpy as np
import os
from pathlib import Path
... | pd.DataFrame() | pandas.DataFrame |
import os
import pandas as pd
import logging
FORMAT = ">>> %(filename)s, ln %(lineno)s - %(funcName)s: %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)
review_folder = 'Z:\\LYR\\LYR_2017studies\\LYR17_2Dmodelling\\LYR17_1_EDDPD\\review\\133'
# initializing csv file lists
hpc_files = []
... | pd.DataFrame() | pandas.DataFrame |
### RF TRAINING AND EVALUATION FOR MULTICLASS CLINICAL OUTCOMES ###
# The script is divided in 4 parts:
# 1. Data formatting
# 2. Hyperparameter Tuning (HT_results)
# 3. Model training and cross validation (CV_results)
# 4. Model training and predictions (TEST_results)
## Intended to be run with arguments:
# ... | pd.DataFrame(columns=['id', 'da', 'pdr', 'pdrm', 'pdm']) | pandas.DataFrame |
#!/usr/bin/env python3
# Copyright (c) 2022. RadonPy developers. All rights reserved.
# Use of this source code is governed by a BSD-3-style
# license that can be found in the LICENSE file.
__version__ = '0.2.1'
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import os
import platform
import radonpy
... | pd.DataFrame(prop_data, index=[data['DBID']]) | pandas.DataFrame |
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
def history_to_png(history_file, output_file, period=None):
history = pd.read_csv(history_file, parse_dates=True, index_col=0)
if period is None:
history = hi... | pd.to_datetime(end) | pandas.to_datetime |
# -*- coding: utf-8 -*-
"""
Functions for collecting data from swehockey
"""
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests
import time
from datetime import datetime
def getGames(df_ids):
"""
Get all games from list of ids
Output is dataframe with all games
""... | pd.notna(df_games['p4score']) | pandas.notna |
import itertools
import numpy as np
import pytest
import pandas as pd
from pandas.core.internals import ExtensionBlock
from .base import BaseExtensionTests
class BaseReshapingTests(BaseExtensionTests):
"""Tests for reshaping and concatenation."""
@pytest.mark.parametrize('in_frame', [True, False])
def ... | pd.Series(data) | pandas.Series |
import numpy as np
import pandas as pd
from . import time_utils as time
desired_fields = [
'last_reported',
# 'num_bikes_available',
'capacity',
'day_of_week',
'is_holiday',
'season',
'segment_of_day',
'cloud_coverage',
'condition',
'condition_class',
'humidity',
'pressure',
'rain',
'snow',... | pd.merge(merged, meta, on='station_id') | pandas.merge |
# Author: <NAME>
"""Trains the models and saves the training and validation scores to a csv file.
Usage: model_selection.py --csv_path=<csv_path>
Options:
--csv_path=<csv_path> path and file name of the model scores csv file
"""
import os
import numpy as np
import pandas as pd
from sklearn.compose import Column... | pd.read_csv("data/raw/X_test.csv", parse_dates=['year']) | pandas.read_csv |
import numpy as np
import pandas as pd
import pathlib
from sklearn.model_selection import train_test_split
file_path = pathlib.WindowsPath(__file__).parent.parent.parent.joinpath('data/')
test_path = file_path.joinpath('test.csv')
train_path = file_path.joinpath('train.csv')
# Importing datasets
def load_test_dataset... | pd.merge(test,temp2, how='left', on= cols) | pandas.merge |
import numpy as np
import pandas as pd
class DataTransform:
def __init__(self, data):
self.data = data
def columns_pattern(self):
# get columns name from dataframe
columns = list(self.data.columns)
# remove spaces, specified characters and format to snake case
column... | pd.notnull(data_composition[i]) | pandas.notnull |
"""
Functions used for pre-processing
"""
#import math
import pickle
#import copy
#import config
import os
# for multiprocessing
from functools import partial
from multiprocessing import Pool, cpu_count
from joblib import Parallel, delayed
import joblib
import numpy as np
import pandas as pd
from sklearn.decomposit... | pd.DateOffset(days=gap) | pandas.DateOffset |
from . import logger
import pandas as pd
from neslter.parsing.files import Resolver, find_file
def read_product_csv(path):
"""file must exist and be a CSV file"""
df = | pd.read_csv(path, index_col=None, encoding='utf-8') | pandas.read_csv |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# TODO: сделать детализацию счета и заказать в html/excel
# замаскировать телефоны
# сделать обработку excel на pandas: Analysis of account detail (excel)
import zipfile
with zipfile.ZipFile('Doc_df7c89c378c04e8daf69257ea95d9a2e.zip'... | pd.DataFrame(data=records, columns=columns) | pandas.DataFrame |
# ----------------------------------------------------------------------------------
# # Presenting Word Frequency Results
# ----------------------------------------------------------------------------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
print("TOTAL RESULTS")
to... | pd.read_csv('/mnt/c/Users/charl/Desktop/finance_perso/BurnieYilmazRS19/resultsData/percent_totals_long_terms_Bitcoin.csv') | pandas.read_csv |
import pandas
import os
import config.config_reader as cr
class workload_info_connector(object):
"""description of class"""
# workload_data = None
# file_path = ""
def __init__(self, file_path):
temp_cr = cr.config_reader()
self.workload_mix = temp_cr.group_name_vec
self.workl... | pandas.read_csv(file_path) | pandas.read_csv |
"""
Tests for CBMonthEnd CBMonthBegin, SemiMonthEnd, and SemiMonthBegin in offsets
"""
from datetime import (
date,
datetime,
)
import numpy as np
import pytest
from pandas._libs.tslibs import Timestamp
from pandas._libs.tslibs.offsets import (
CBMonthBegin,
CBMonthEnd,
CDay,
SemiMonthBegin,
... | assert_offset_equal(offset, base, expected) | pandas.tests.tseries.offsets.common.assert_offset_equal |
r"""
Baseline Calculation
"""
# Standard Library imports
import argparse
import cartopy.crs as ccrs
import datetime
import h5py
import json
import matplotlib.colors
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import netCDF4
import numpy as np
import os
import pandas as pd
impor... | pd.to_timedelta(window2//2, 'H') | pandas.to_timedelta |
import numpy as np
import pandas as pd
def generate_dataset(coeffs, n, std_dev, intercept=0., distribution='normal', binary=False, seed=None, **kwargs):
"""Generate an artificial dataset
:param coeffs: List of coefficients to use for computing the ouytput variable.
:type coeffs: :obj:`list`
:param n: ... | pd.DataFrame({'coeff': coeffs, 'std_dev': std_dev}) | pandas.DataFrame |
"""
STATUS:OK for 1sec timeframe. NOK for 1Min timeframe but the failure cases are skipped.
BUG:issue with leakage with timeframe=1Min for some conditions (cf. tests symbols= [S_TEST_F1, S_TEST_F2])
NOTE: to run tests with expected failure, add the --runxfail option to pytest
"""
import pytest
import random
import nump... | pd.Timestamp(end, tz="utc") | pandas.Timestamp |
import sys
import random
import os
from lifelines import KaplanMeierFitter
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from lifelines import CoxPHFitter
from sklearn.metrics import average_precision_score, precision_recall_curve, roc_auc_score, roc_curve, auc, \
brier_score_loss, precisio... | pd.read_csv(path, usecols=["eid", "2443-3.0"], index_col="eid") | pandas.read_csv |
from datetime import datetime
import pandas as pd
import subprocess
codes_file = "/home/gaza/Documents/sportsbook/sportsbook/codenames.csv"
games_file = "/home/gaza/Documents/sportsbook/sportsbook/dailybets.csv"
def load_codes():
data = pd.read_csv(codes_file)
df = pd.DataFrame(data, columns=['code','league'... | pd.DataFrame(data) | pandas.DataFrame |
from datetime import datetime, timedelta
import numpy as np
import pytest
from pandas._libs.tslibs import period as libperiod
import pandas as pd
from pandas import DatetimeIndex, Period, PeriodIndex, Series, notna, period_range
import pandas._testing as tm
class TestGetItem:
def test_ellipsis(self):
#... | pd.Period("2017-09-02") | pandas.Period |
# -*- coding: utf-8 -*-
# pylint: disable=W0612,E1101
from collections import OrderedDict
from datetime import datetime
import numpy as np
import pytest
from pandas.compat import lrange
from pandas import DataFrame, MultiIndex, Series, date_range, notna
import pandas.core.panel as panelm
from pandas.core.panel impor... | tm.assert_frame_equal(panel.loc['a2'], df2) | pandas.util.testing.assert_frame_equal |
"""
Test cases for the wiutils.transformers.compute_detection_by_deployment function.
"""
import pandas as pd
import pytest
from wiutils.transformers import compute_detection_by_deployment
@pytest.fixture(scope="function")
def images():
return pd.DataFrame(
{
"deployment_id": ["001", "001", "... | pd.testing.assert_frame_equal(images_original, images) | pandas.testing.assert_frame_equal |
PATH_ROOT='C:/Users/<NAME>/Desktop/ICoDSA 2020/SENN/'
print('==================== Importing Packages ====================')
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
import pandas as pd
import re
import json
import math
import string
import numpy as np
from bs4 import BeautifulSoup
i... | pd.concat([df_pool,x],ignore_index=True) | pandas.concat |
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
pio.templates.default = "simple_white"
def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature ... | pd.read_csv(filename, parse_dates=["Date"]) | pandas.read_csv |
import wandb
from wandb import data_types
import numpy as np
import pytest
import os
import sys
import datetime
from wandb.sdk.data_types._dtypes import *
class_labels = {1: "tree", 2: "car", 3: "road"}
test_folder = os.path.dirname(os.path.realpath(__file__))
im_path = os.path.join(test_folder, "..", "assets", "test... | pd.DataFrame([[42], [42]]) | 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-2007') | pandas.to_datetime |
from datetime import datetime
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from scipy.stats import zscore
import matplotlib.pyplot as pyplot
def drawHist(x):
#创建散点图
#第一个参数为点的横坐标
#第二个参数为点的纵坐标
pyplot.hist(x, 100)
pyplot.xlabel('x')
pyplot.ylabel('y')
pyplot.title('... | pd.read_csv('./google-play-store-apps/googleplaystore_user_reviews.csv') | pandas.read_csv |
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import matplotlib.pyplot as plt
import xgboost as xgb
import shap
from sklearn.model_selection import ParameterGrid
from sklearn.preprocessing import MinMaxScaler
'''
Feature selection is done using XGBoost and SHAP.
XGBoost is an optimized distrib... | pd.DataFrame(y_val) | pandas.DataFrame |
from collections import OrderedDict
from datetime import datetime, timedelta
import numpy as np
import numpy.ma as ma
import pytest
from pandas._libs import iNaT, lib
from pandas.core.dtypes.common import is_categorical_dtype, is_datetime64tz_dtype
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
Da... | tm.makePeriodIndex(100) | pandas._testing.makePeriodIndex |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 22:37:36 2020
@author: arti
"""
import pandas as pd
df = pd.read_csv('./titanic.csv')
print(df.head())
print('--')
| pd.set_option('display.max_columns', 15) | pandas.set_option |
import numpy as np
import pandas as pd
import os
import time
import shutil
from numpy import array
from numpy import argmax
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import indoor_location.getWordVector as getWordVector
import indoor_location.globalConfig as globalCo... | pd.DataFrame(all_samples, columns=column_tags) | pandas.DataFrame |
#%%
import os
from typing import Dict
from pandas.core.frame import DataFrame
import pandas
import seaborn as sns
import matplotlib.pyplot as plt
#%%
outDir = "results"
chunkDir = "chunk_data"
miningDir = "mining_data"
def chunk_data():
files = []
container: Dict[str, DataFrame] = {}
f... | pandas.concat(t2) | pandas.concat |
#!/usr/bin/env python
# coding: utf-8
# # Predicting Student Academic Performance
# ## an exploration in data visualiation and machine learning efffectiveness
# #### The goal of this project was to examine a number of ML algorithms that were capable of adjusting to categorical data and attempt to predict student perfo... | pd.get_dummies(data, columns=["gender", "NationalITy", "PlaceofBirth", "SectionID", "StageID", "Topic", "Semester", "Relation", "ParentAnsweringSurvey", "ParentschoolSatisfaction", "StudentAbsenceDays"]) | pandas.get_dummies |
import numpy as np
from matplotlib import pyplot as plt
import time
import emcee
import corner
import seaborn as sns
import pandas as pd
from IPython.display import display, Math
import arviz as az
from scipy.stats import scoreatpercentile
#b_w=0.25 #CC+H0 Mejor sin smoothear!
#b_w=0.005 #Nuisance Mejor sin smoothear!... | pd.DataFrame(flat_samples,columns=self.labels) | pandas.DataFrame |
import pandas as pd
from collections import deque, namedtuple
class PositionSummary(object):
"""
Takes the trade history for a user's watchlist from the database and it's
ticker. Then applies the FIFO accounting methodology to calculate the
overall positions status i.e. final open lots, average cost a... | pd.DataFrame(flows, columns=["date", "flows"]) | pandas.DataFrame |
"""
Prisma Inc.
database.py
Status: UNDER DEVELOPMENT for Major Update Ryzen
Made by <NAME>.
"""
import pandas as pd
import os
import requests
import progressbar
import gc
import pymongo
import gridfs
from pprint import pprint
import json
import certifi
from sneakers.api.low import builder as bd
from sneakers.api... | pd.DataFrame(resultcursor) | pandas.DataFrame |
import numpy as np
import pandas as pd
import pytest
from hypothesis import given, settings
from pandas.testing import assert_frame_equal
from janitor.testing_utils.strategies import (
conditional_df,
conditional_right,
conditional_series,
)
@pytest.mark.xfail(reason="empty object will pass thru")
@given(... | assert_frame_equal(expected, actual) | pandas.testing.assert_frame_equal |
# -*- coding: utf-8 -*-
"""
Created on Mon May 30 06:44:09 2016
@author: subhajit
"""
import pandas as pd
import datetime
from sklearn import cross_validation
import xgboost as xgb
import numpy as np
import h5py
import os
os.chdir('D:\Data Science Competitions\Kaggle\Expedia Hotel Recommendations\codes')
def map5ev... | pd.read_csv('../input/destinations.csv') | pandas.read_csv |
"""Mock data for bwaw.insights tests."""
import pandas as pd
ACTIVE_BUSES = pd.DataFrame([
['213', 21.0921481, '1001', '2021-02-09 15:45:27', 52.224536, '2'],
['213', 21.0911025, '1001', '2021-02-09 15:46:22', 52.2223788, '2'],
['138', 21.0921481, '1001', '2021-02-09 15:45:27', 52.224536, '05'],
['138'... | pd.DataFrame([
['1001', '01', 52.224536, 21.0921481, 'al.Zieleniecka', '2020-10-12 00:00:00.0']
], columns=['ID', 'Number', 'Latitude', 'Longitude', 'Destination', 'Validity']) | pandas.DataFrame |
"""
-------------------------------------------
Author: <NAME> (<EMAIL>)
Date: 10/13/17
-------------------------------------------
"""
# our modules
import visJS2jupyter.visJS_module as visJS_module # "pip install visJS2jupyter"
import create_graph # from URA package
# common packages, most likely already installed
i... | pd.Series(TR_to_pvalue) | pandas.Series |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import panel as pn
pn.extension()
import hvplot.pandas
import datetime
# # 1 load data
# In[2]:
folder_path = './data/'
# Load data from each csv and assign to variable data_****"
data_net_zero = pd.read_csv(folder_path + 'net_zero.csv', parse_... | pd.read_csv(folder_path + 'book_sales.csv', parse_dates = ['as_at_date'], dayfirst=True) | pandas.read_csv |
"""Filter classifier"""
import json
import logging
import collections
import functools
import math
import scipy.optimize
import numpy as np
import pandas as pd
from pandas import json_normalize
import sklearn.linear_model
from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score, log_loss
from .uti... | json_normalize(data) | pandas.json_normalize |
# Author: <NAME> 2021-10-01
#
# Amazon has a new format for their website
#
# copy text of your Kindle library to a *.txt file
# entries will look a little like this:
#
# King of Thorns (The Broken Empire Book 2)
# <NAME>
# Acquired on September 24, 2021
# In2
# Collections
# 1
# Device
# Deliver or Remove from Device
... | pd.ExcelFile(prevRatingsFname) | pandas.ExcelFile |
# #-- -- -- -- Supervised Learning with scikit-learn
# # Used for Data Scientist Training Path
# #FYI it's a compilation of how to work
# #with different commands.
# ### --------------------------------------------------------
# # # # ------>>>> Which of these is a
# classification problem? Once
# you ... | pd.get_dummies(df, drop_first=True) | pandas.get_dummies |
from ast import literal_eval
import numpy as np
import pandas as pd
import scipy
from pandas import DataFrame
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.neighbors import BallTree, KDTree, NearestNeighbors
from sklearn.preprocessing import Mu... | DataFrame.sparse.from_spmatrix(X) | pandas.DataFrame.sparse.from_spmatrix |
# Bulding futures_bundle
import pandas as pd
from os import listdir
from tqdm import tqdm # Used for progress bar
# Change the path to where you have your data
base_path = "/Users/dmitrymikhaylov/Documents/code/fin/testing_clenow/data/"
data_path = base_path + 'random_futures/'
meta_path = 'futures_meta/meta.csv'
futu... | pd.Timedelta(days=1) | pandas.Timedelta |
##################################
# #
# Leveraged product scrapers #
# oliverk1 #
# July 2019 #
# #
##################################
# Import packages and setup time
from selenium import webdriver
import pan... | pd.concat([totalresult, result], axis=0, sort=False) | pandas.concat |
# Arithmetic tests for DataFrame/Series/Index/Array classes that should
# behave identically.
from datetime import datetime, timedelta
import numpy as np
import pytest
from pandas.errors import (
NullFrequencyError, OutOfBoundsDatetime, PerformanceWarning)
import pandas as pd
from pandas import (
DataFrame, ... | tm.assert_equal(result, expected) | pandas.util.testing.assert_equal |
"""
.. _logs:
Log File Analysis (experimental)
================================
Logs contain very detailed information about events happening on computers.
And the extra details that they provide, come with additional complexity that
we need to handle ourselves. A pageview may contain many log lines, and a
session ca... | pd.DataFrame(scraped_lines, columns=scraped_cols) | pandas.DataFrame |
####
#### Jan 10, 2022
####
"""
This is created after the meeting on Jan, 10, 2022.
Changes made to the previous version:
a. Vertical lines for time reference
b. Add area of fields to the title of the plots.
c. In the title break AdamBenton2016 to one county!
d.... | pd.to_datetime(SG_df_NDVI['human_system_start_time']) | pandas.to_datetime |
'''
Input event payload expected to be in the following format:
{
"Batch_start": "MAC000001",
"Batch_end": "MAC000010",
"Data_start": "2013-06-01",
"Data_end": "2014-01-01",
"Forecast_period": 7
}
'''
import boto3, os
import json
import pandas as pd
import numpy as np
from pyathena import connect
REGION = os.envir... | pd.read_sql(selected_households, connection) | pandas.read_sql |
from requests import get
import datetime
import pandas as pd
from starlingpy.StarlingAPIs import Account_APIs
BASE_PATH = "https://api.starlingbank.com/api/v2/"
class TransactionHistory:
"""
A history of transactions associated with the Starling account, between stipulated datetimes.
Requires the Sta... | pd.to_datetime(df["transactionTime"]) | pandas.to_datetime |
import pandas as pd
import numpy as np
from tqdm import tqdm
#读取轨迹数据
i = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
user = pd.read_csv(r"G:\track data and travel prediction\dataset\DataTech_Travel_Train_User",
sep='|', names=['USER_ID', 'FLAG', 'TRAVEL_TYPE'])
#user = u... | pd.read_csv(filename, sep='|', names=["USER_ID", "START_TIME", "LONGITUDE", "LATITUDE", "P_MONTH"]) | pandas.read_csv |
"""
This script visualises the prevention parameters of the first and second COVID-19 waves.
Arguments:
----------
-f:
Filename of samples dictionary to be loaded. Default location is ~/data/interim/model_parameters/COVID19_SEIRD/calibrations/national/
Returns:
--------
Example use:
------------
"""
__author_... | pd.to_datetime('2020-12-18') | pandas.to_datetime |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import prince
from sklearn.cluster import DBSCAN
import itertools
from cmca import CMCA
from ccmca import CCMCA
plt.style.use('ggplot')
alpha = r'$ \alpha $'
tableau10 = {
'blue': '#507AA6',
'orange': '#F08E39',
'red': '#DF585C',
'... | pd.read_csv(csv) | pandas.read_csv |
import pandas as pd
import inspect
import functools
# ============================================ DataFrame ============================================ #
# Decorates a generator function that yields rows (v,...)
def pd_dfrows(columns=None):
def dec(fn):
def wrapper(*args,**kwargs):
return pd... | pd.DataFrame(d,inx,columns=columns) | pandas.DataFrame |
import requests
import os
import time
from datetime import datetime
from calendar import timegm
import pandas
import boto3
import io
from utilities.exceptions import ApiError
from airflow.models import Variable
class TDAClient:
"""
Class for accessing TDA API.
...
Attributes
----------
clien... | pandas.DataFrame(columns=column_names) | pandas.DataFrame |
"""
Contains functions and classes that are olfactory-specific.
@author: <NAME>
"""
# ################################# IMPORTS ###################################
import copy
import itertools
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.lina... | pd.DataFrame(W, index=data.index, columns=ks) | pandas.DataFrame |
"""Class to process full HydReSGeo dataset.
Note: If IRUtils.py is not available, you need to download it before the
installation of the package into the `hprocessing/` folder:
.. code:: bash
wget -P hprocessing/ https://raw.githubusercontent.com/felixriese/thermal
-image-processing/master/tiprocessing/I... | pd.DataFrame(lwir_dict) | pandas.DataFrame |
import pandas as pd
import numpy as np
import spacy
from sklearn.decomposition import PCA
from sklearn.neighbors import NearestNeighbors
nlp = spacy.load('my_model')
df = pd.read_csv('Spotify/data.csv')
df = df[:100]
df['artists'] = df['artists'].apply(lambda x: x[1:-1].replace("'", ''))
df_slim = df.drop(['id', 're... | pd.DataFrame(song_list) | pandas.DataFrame |
from datetime import datetime, time
from itertools import product
import numpy as np
import pytest
import pytz
import pandas as pd
from pandas import (
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Series,
date_range,
period_range,
to_datetime,
)
import pandas.util.testing as tm
import... | tm.makeTimeDataFrame(freq="12h") | pandas.util.testing.makeTimeDataFrame |
# <NAME>
# python 3.6
""" Input:
------
It reads the individual driver's correlation nc files
Also uses regional masks of SREX regions to find dominant drivers regionally
Output:
-------
* Timeseries of the percent distribution of dominant drivers at different lags
"""
from scipy import stats
from scipy impor... | pd.Series(tas_px) | pandas.Series |
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
import numpy as np
from os.path import isfile, join
from os import listdir
import os
from collections import OrderedDict
from hrate.data_handling.selfloops import read_selfloops_file
imp... | pd.to_datetime(HR_plot_selected['range']['x'][1]) | pandas.to_datetime |
from collections import deque
from datetime import datetime
import operator
import re
import numpy as np
import pytest
import pytz
import pandas as pd
from pandas import DataFrame, MultiIndex, Series
import pandas._testing as tm
import pandas.core.common as com
from pandas.core.computation.expressions import _MIN_ELE... | pd.date_range("20010101", periods=10) | pandas.date_range |
from unittest import TestCase, main
import datetime
import pandas as pd
import numpy as np
import numpy.testing as npt
import pandas.util.testing as pdt
from break4w.question import (Question,
_check_cmap
)
class QuestionTest(TestCase):
def setUp(sel... | pdt.assert_series_equal(kseries, tseries) | pandas.util.testing.assert_series_equal |
# coding: utf-8
# # Leave-One-Patient-Out classification of individual volumes
#
# Here, we train a classifier for each patient, based on the data of all the other patients except the current one (Leave One Out Cross-Validation). To this end, we treat each volume as an independent observation, so we have a very larg... | pd.MultiIndex.from_tuples(this_df.index) | pandas.MultiIndex.from_tuples |
# pylint: disable=g-bad-file-header
# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved.
#
# 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/... | pd.DataFrame(pooled) | pandas.DataFrame |
import os
import datetime
import logging
import json
import uuid
import pandas as pd
from collections import Counter
from installed_clients.GenomeAnnotationAPIClient import GenomeAnnotationAPI
from installed_clients.DataFileUtilClient import DataFileUtil
from installed_clients.GenomeFileUtilClient import GenomeFileUti... | pd.DataFrame(columns=['gene', 'term', 'events', 'score']) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 15:41:39 2018
@author: elcok
"""
import geopandas as gpd
import pandas as pd
import os
import igraph as ig
import numpy as np
import sys
import subprocess
from shapely.geometry import Point
from geoalchemy2 import Geometry, WKTElement
from vtra.utils import load_co... | pd.ExcelWriter(flow_output_excel) | pandas.ExcelWriter |
import argparse
import sys
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.neighbors import BallTree
STEERING_ANGLE_RATIO = 14.7
def calculate_closed_loop_metrics(model_frames, expert_frames, fps=30, failure_rate_threshold=1.0):
lat_errors = calculate_lateral_errors(model_frames, ex... | pd.concat(datasets) | pandas.concat |
"""
Author: <NAME>
Main class for Jaal network visualization dashboard
"""
# import
import dash
import visdcc
import pandas as pd
from dash import dcc, html
# import dash_core_components as dcc
# import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
from ... | pd.DataFrame(self.data['nodes']) | pandas.DataFrame |
# -*- coding: utf-8 -*-
# Copyright 2017 <NAME> <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | pd.concat([df_norm, df_range]) | pandas.concat |
import datetime
import json
import pathlib
import numpy as np
import pandas as pd
def downsample(df, offset):
"""Reduce dataframe by resampling according to frequency offset/rule
Parameters
----------
df : pandas.core.frame.DataFrame
A pandas dataframe where the index is the date.
offset... | pd.concat([resampled, df.iloc[[-1]]]) | pandas.concat |
'''
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([l_sum], columns=cols) | pandas.DataFrame |
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, roc_curve
from sklearn.utils import res... | pd.Series(rf.feature_importances_,index=features.columns) | pandas.Series |
import numpy as np
import pandas as pd
import warnings
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
warnings.filterwarnings('ignore')
columns_name=["user_id","item_id","rating","timestamp"]
df= | pd.read_csv("ml-100k/u.data",sep='\t',names=columns_name) | pandas.read_csv |
from binance.client import Client
import keys
from pandas import DataFrame as df
from datetime import datetime
import trading_key
client=Client(api_key=keys.Pkeys, api_secret=keys.Skeys)
#get candle data
def candle_data(symbols, intervals):
candles=client.get_klines(symbol=symbols, interval=interv... | df(candles) | pandas.DataFrame |
import pandas as pd
import numpy as np
import click
import h5py
import os
import logging
from array import array
from copy import deepcopy
from tqdm import tqdm
from astropy.io import fits
from fact.credentials import create_factdb_engine
from zfits import FactFits
from scipy.optimize import curve_fit
from joblib imp... | pd.to_datetime("") | pandas.to_datetime |
from __future__ import division
import pytest
import numpy as np
from pandas import (Interval, IntervalIndex, Index, isna,
interval_range, Timestamp, Timedelta,
compat)
from pandas._libs.interval import IntervalTree
from pandas.tests.indexes.common import Base
import pandas.uti... | IntervalIndex.from_breaks(idx) | pandas.IntervalIndex.from_breaks |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Import OptionMetrics data.
"""
from __future__ import print_function, division
import os
import zipfile
import numpy as np
import pandas as pd
import datetime as dt
from scipy.interpolate import interp1d
from impvol import lfmoneyness, delta, vega
from datastorage.q... | pd.read_hdf(path + 'riskfree.h5', 'riskfree') | pandas.read_hdf |
import os
import sys
import requests
import numpy as np
import pandas as pd
import kauffman.constants as c
from kauffman.tools._etl import county_msa_cross_walk as cw
# https://www.census.gov/programs-surveys/popest.html
| pd.set_option('max_columns', 1000) | pandas.set_option |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.