prompt
stringlengths
19
1.03M
completion
stringlengths
4
2.12k
api
stringlengths
8
90
import gpxpy import pandas as pd def path_to_gpx(path_to_tcx): return path_to_tcx.split('.')[0] + '.gpx' def get_workout_info(path_to_tcx): """Get name and type of a workout from its gpx file.""" path = path_to_gpx(path_to_tcx) with open(path) as f: gpx = gpxpy.parse(f) # assert len(gpx....
pd.DataFrame(dic)
pandas.DataFrame
# Copyright (c) 2021. <NAME>. All rights Reserved. import numpy import numpy as np import pandas as pd from bm.datamanipulation.AdjustDataFrame import remove_null_values class DocumentProcessor: custom_dtypes = [] model_types = [] def __init__(self): self.custom_dtypes = ['int64', 'float64', 'd...
pd.isna(df[col])
pandas.isna
"""Tests for misc module.""" import mock import numpy as np import pandas as pd from pandas.testing import assert_frame_equal from numpy.testing import assert_almost_equal import pytest import causalimpact standardize = causalimpact.misc.standardize_all_variables unstandardize = causalimpact.misc.unstandardize df_...
pd.DataFrame(data)
pandas.DataFrame
from __future__ import absolute_import, print_function from builtins import object, str import copy, numpy, pandas, pyarrow as pa, sys, uuid from .pygraphistry import PyGraphistry from .pygraphistry import util from .pygraphistry import bolt_util from .nodexlistry import NodeXLGraphistry from .tigeristry import Tigeri...
pandas.DataFrame(lnodes, columns=[nodeid])
pandas.DataFrame
"""Prepare feature data from Universal Dependencies and UniMorph datasets. We need to know the feature values of each word in BERT's vocab. For the multilingual model, we want to know the feature values for all the languages it models. This module is intended to be run as a script: $ python src/features.py """ i...
pd.DataFrame(result)
pandas.DataFrame
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Date: 2022/1/26 13:10 Desc: 申万指数-申万一级、二级和三级 http://www.swsindex.com/IdxMain.aspx https://legulegu.com/stockdata/index-composition?industryCode=851921.SI """ import time import json import pandas as pd from akshare.utils import demjson import requests from bs4 import Bea...
numeric(temp_df["最新价"])
pandas.to_numeric
from pathlib import Path import numpy as np import pandas as pd import pandas.testing as tm import pytest from tableauhyperapi import Connection, CreateMode, HyperProcess, TableName, Telemetry import pantab import pantab._compat as compat def assert_roundtrip_equal(result, expected): """Compat helper for compar...
pd.concat([expected, expected])
pandas.concat
###### # Author: <NAME> # this file loads and organizes # Foundation data for further use ###### import numpy as np import networkx as nx import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np from datetime import datetime,timedelta from tqdm import tqdm import matplot...
pd.read_csv("data/nft_metadata.csv")
pandas.read_csv
# ---------------------------------------------------------------------------- # Name: Read/Write/Helper functions for HDF5 based CML data format cmlH5 # Purpose: # # Authors: # # Created: # Copyright: (c) <NAME> 2016 # Licence: The MIT License # -----------------------------------------------...
pd.DataFrame(index=t, data=data_dict)
pandas.DataFrame
# -*- coding: utf-8 -*- """ 爬虫抓取工具 """ import numpy as np import time import uuid import sys from mllib.utils import seleniumutil as util import re import lxml.html import pandas as pd from lxml import etree from urllib.request import urlopen, Request import requests from pandas.compat import StringIO from mllib.uti...
StringIO(text_1)
pandas.compat.StringIO
#!/usr/bin/env python # -*- coding: utf-8 -*- import featuretools as ft import pandas as pd import pytest from numpy import nan from cardea.data_loader import EntitySetLoader from cardea.problem_definition.predicting_diagnosis import DiagnosisPrediction @pytest.fixture() def diagnosis_prediction(): return Diagn...
pd.DataFrame({"object_id": [0, 2, 1, 7]})
pandas.DataFrame
# # Build a graph describing the layout of each station based on data # from the MTA's elevator and escalator equipment file. We also # incorporate an override file, since some of the MTA descriptions # too difficult for this simple program to understand. Writes to # stdout. # import argparse import pandas as pd import...
pd.read_csv(master_file)
pandas.read_csv
import os import joblib import numpy as np import pandas as pd from joblib import Parallel from joblib import delayed from Fuzzy_clustering.version2.common_utils.logging import create_logger from Fuzzy_clustering.version2.dataset_manager.common_utils import check_empty_nwp from Fuzzy_clustering.version2.dataset_manag...
pd.DataFrame()
pandas.DataFrame
# -*- coding: utf-8 -*- # pylint: disable=E1101 # flake8: noqa from datetime import datetime import csv import os import sys import re import nose import platform from multiprocessing.pool import ThreadPool from numpy import nan import numpy as np from pandas.io.common import DtypeWarning from pandas import DataFr...
StringIO(csv)
pandas.compat.StringIO
#! /usr/bin/env python3 # -*- coding: utf-8 -*- ########################################################################## # Copyright (c) 2017-2018 <NAME>. All rights reserved. # # Use of this source code is governed by a BSD-style license that can be # # found in the LICENSE file. ...
pd.MultiIndex.from_tuples([(mvt, muscle) for muscle in summary.index], names=index_names)
pandas.MultiIndex.from_tuples
from __future__ import absolute_import, division, print_function import pytest from datetime import datetime, timedelta import numpy as np import pandas as pd import pandas.util.testing as tm from pandas import DataFrame, Series from string import ascii_lowercase from blaze.compute.core import compute from blaze ...
Series(('a', 'b', 'c'))
pandas.Series
from __future__ import division import pytest import numpy as np from datetime import timedelta from pandas import ( Interval, IntervalIndex, Index, isna, notna, interval_range, Timestamp, Timedelta, compat, date_range, timedelta_range, DateOffset) from pandas.compat import lzip from pandas.tseries.offsets imp...
IntervalIndex(index, copy=False)
pandas.IntervalIndex
##################################################################### ####### Dash Plotly with Bootstrap Components ######### ##################################################################### import os import pandas as pd import numpy as np from datetime import datetime import dash_bootstrap_compone...
pd.Timestamp.today()
pandas.Timestamp.today
# This file is part of the # Garpar Project (https://github.com/quatrope/garpar). # Copyright (c) 2021, 2022, <NAME>, <NAME> and QuatroPe # License: MIT # Full Text: https://github.com/quatrope/garpar/blob/master/LICENSE # ============================================================================= # IMPORTS # =...
pdt.assert_series_equal(result, expected)
pandas.testing.assert_series_equal
import pandas as pd from scipy.io.arff import loadarff def data_albrecht(): raw_data = loadarff("../data_experiment/classic/albrecht.arff") df_data = pd.DataFrame(raw_data[0]) new_alb = df_data.drop(columns=['FPAdj', 'RawFPcounts', 'AdjFP']) return new_alb def data_china(): raw_data = loadarff("...
pd.DataFrame(raw_data[0])
pandas.DataFrame
""" Collection of functions to prepare the master curve for the identification of the Prony series parameters. Methods are provided to shift the raw measurement data into a master curve and remove measurement outliers through smoothing of the master curve. """ import numpy as np import pandas as pd import matplotlib...
pd.DataFrame(Temp, columns=['T'])
pandas.DataFrame
from sklearn.metrics.ranking import roc_auc_score, roc_curve from sklearn.model_selection import train_test_split from keras.layers import Dense, Dropout, Activation from imblearn.keras import balanced_batch_generator from imblearn.under_sampling import NearMiss from keras.models import Sequential from keras.optimizers...
pd.DataFrame(shuffled_X_test)
pandas.DataFrame
""" Test for utility class functionality """ from core.utility import Utility import pandas as pd import numpy as np d1 = [4,3,2,1] d2 = [1,2,3,4] d3 = [2,np.nan,6,8] df =
pd.DataFrame()
pandas.DataFrame
import numpy as np import pandas as pd import itertools import collections def findDuplicates(N, L, MOI): ''' This function takes as an input the number of cells (N), the library size (L) and the average MOI for the virus and returns the number of duplicate cells. ''' n_tags_per_cell = np.random.po...
pd.DataFrame()
pandas.DataFrame
from typing import List, Dict, Union import pickle from pathlib import Path import pandas as pd import numpy as np import h5py def extract_result(results: Dict, key: str) -> pd.Series: df = pd.concat({(int(res['hp_ix']), int(bs_ix), k):
pd.DataFrame(v, index=[0])
pandas.DataFrame
### 第一批数据:1:敏感语料(短语) 2:微博评论原文(senti100k,未处理),各6754条,测试集比例0.1 import pandas as pd df_1 = pd.read_excel('/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/网络信息语料 文德 20210122.xlsx', sheet_name='测试集') df_0 = pd.read_csv('/Users/leo/Data/项目数据/文德数慧-文本内容审核/分类实验/数据/weibo_senti_100k.csv') df_0 = df_0.sample(n=6754).reset_index(drop=...
pd.DataFrame({'label':[label],'text':[text]})
pandas.DataFrame
""" Author: <EMAIL> / <EMAIL> Purpose: ease OCT image access and analyses """ import pandas as pd import numpy as np import os import glob import matplotlib.pyplot as plt import matplotlib.image as mpimg import plotly.graph_objects as go class TopconSegmentationData: # extract thickness data from ...
pd.DataFrame(columns=columns_names)
pandas.DataFrame
# -*- coding:utf-8 -*- # /usr/bin/env python """ Date: 2021/8/28 21:26 Desc: 东方财富网-行情首页-上证 A 股-每日行情 获取最近一个交易日的交易信息 使用示例(直接运行main函数,获取最近一个交易日的交易信息): main() """ import time import json import pandas as pd import os from data_urls import a_detail_url as url from comm_funcs import requests_get from comm_funcs import get...
numeric(save_df["涨跌幅"], errors="coerce")
pandas.to_numeric
import pandas as pd import streamlit as st @st.cache(suppress_st_warning=True) def load_zero_data(fast_file) -> pd.DataFrame: """ Load a Zero Fasting data export CSV file and return a pandas DataFrame version of the file. DataFrame is reindexed chronologically, oldest to newest, before returned. Args:...
pd.concat([start_dt, end_dt], axis=1)
pandas.concat
import os """ First change the following directory link to where all input files do exist """ os.chdir("D:\\Book writing\\Codes\\Chapter 2") import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt import seaborn as sns #from sklearn.model_selection impor...
pd.DataFrame(y_test)
pandas.DataFrame
"""Read in hourly weather file.""" import os import glob import yaml from datetime import datetime from dateutil import tz import numpy as np import pandas as pd import xarray as xr from timezonefinder import TimezoneFinder from ideotype import DATA_PATH from ideotype.utils import CC_RH, CC_VPD from ideotype.data_pr...
pd.read_csv(fpath_stations_info)
pandas.read_csv
import logging from tqdm import tqdm import pandas as pd import kex logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') types = { "Inspec": "Abst", "www": "Abst", "kdd": "Abst", "Krapivin2009": "Full", "SemEval2010": "Full", "...
pd.DataFrame(each_data)
pandas.DataFrame
#!/usr/bin/env python # coding: utf-8 # # Simple tool to analyze data from www.data.gouv.fr # # **Note:** This is a Jupyter notebook which is also available as its executable export as a Python 3 script (therefore with automatically generated comments). # # Libraries # In[ ]: import sys,os addPath= [os.path.absp...
PAN.set_option('display.max_colwidth', None)
pandas.set_option
import io import os from datetime import datetime import pandas as pd import scrapy from scrapy import Request from scrapy import signals from fooltrader.api.quote import get_security_list from fooltrader.contract.data_contract import KDATA_COLUMN_STOCK, KDATA_COLUMN_163 from fooltrader.contract.files_contract import...
pd.to_datetime(df_current.index)
pandas.to_datetime
import datetime as dt import itertools import json import logging import re from functools import cached_property from itertools import product from typing import Callable, List, Mapping, Optional, Sequence, Union import numpy as np import pandas as pd import tushare as ts from ratelimiter import RateLimiter from retr...
pd.concat([data, cache], axis=1)
pandas.concat
import time import numpy as np import pandas as pd from sklearn.decomposition import PCA from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import KFold from tqdm import tqdm def timeit(method): def timed(*args, **kw): ts = time.time() result = metho...
pd.concat([df_test, df_test_lda], axis=1)
pandas.concat
import numpy as np import pandas as pd import spacy from spacy.lang.de.stop_words import STOP_WORDS from nltk.tokenize import sent_tokenize from itertools import groupby import copy import re import sys import textstat # Method to create a matrix with contains only zeroes and a index starting by 0 def cr...
pd.DataFrame(d_end_punct_list)
pandas.DataFrame
# Neural network for pop assignment # Load packages import tensorflow.keras as tf from kerastuner.tuners import RandomSearch from kerastuner import HyperModel import numpy as np import pandas as pd import allel import zarr import h5py from sklearn.model_selection import RepeatedStratifiedKFold, train_test_split from s...
pd.DataFrame(top_freqs["freq"])
pandas.DataFrame
# -*- coding: utf-8 -*- """ Created on Wed Oct 7 20:41:59 2020 @author: prasa """ import pandas as pd import re import nltk from nltk.stem import WordNetLemmatizer from nltk.stem import PorterStemmer from nltk.corpus import stopwords #import the file and here label and message is separeted with ...
pd.read_csv('D:/Work space/smsspamcollection/SMSSpamCollection', sep='\t', names=["labels", "Text_Message"])
pandas.read_csv
import numpy as np import scipy.io as sio import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm import matplotlib.cm as cm import pandas as pd import copy #Filters from sklearn.model_selecti...
pd.concat([df_f] * q_signals_file, ignore_index=False)
pandas.concat
# ***************************************************************************** # Copyright (c) 2019, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of sou...
pandas.Series(result)
pandas.Series
import cv2 from datetime import datetime import pandas from bokeh.plotting import figure from bokeh.io import output_file, show first_frame = None status_list = [None, None] time_stamp = [] video = cv2.VideoCapture(0) while True: check, frame= video.read() status = 0 gray_frame = cv2.cv...
pandas.DataFrame(columns=['start', 'end'])
pandas.DataFrame
# Copyright (c) 2018-2021, NVIDIA CORPORATION. import re from concurrent.futures import ThreadPoolExecutor import numpy as np import pandas as pd import pytest import cudf from cudf.datasets import randomdata from cudf.testing._utils import assert_eq, assert_exceptions_equal params_dtypes = [np.int32, np.uint32, np...
pd.Series([1.0, 2.0, 3.0, np.nan, None])
pandas.Series
import os import re import matplotlib.pyplot as plt import numpy as np import pandas as pd import netdice.experiments.sri_plot_helper as sph from netdice.experiments.compare_approaches import bf_states_for_target_precision, \ hoeffding_samples_for_target_precision from netdice.my_logging import log class Analyz...
pd.DataFrame(data_list, columns=["precision"])
pandas.DataFrame
# import app components from app import app, data from flask_cors import CORS CORS(app) # enable CORS for all routes # import libraries from flask import request import pandas as pd import re from datetime import datetime from functools import reduce # define functions ## process date args def date_arg(arg): try...
pd.read_csv(data.ccodwg[k])
pandas.read_csv
#! /usr/bin/env python3 import re import math import json import inspect import pkg_resources import numpy as np import pandas as pd from time import time from joblib import Parallel, delayed from typing import Any, Dict, List, Optional, Union from pathlib import Path from pkg_resources import resource_filename from p...
pd.read_stata(infile, columns=tokeep, chunksize=chunksize)
pandas.read_stata
# spikein_utils.py # Single Cell Sequencing Quality Assessment: scqua # # Copyright 2018 <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the Lice...
pd.read_csv(tpm_file, index_col=0)
pandas.read_csv
# -*- coding: utf-8 -*- import pandas as pd class JPY(object): """docstring for JPY""" def __init__(self, usd_filename, btc_filename, bch_filename): usd = pd.read_csv(usd_filename, parse_dates=['snapped_at']) btc = pd.read_csv(btc_filename, parse_dates=['snapped_at']) bch = pd.read_csv(...
pd.merge(btc, bch, how='left')
pandas.merge
from Task1 import * from Task3 import * from Task5 import * from Task6 import * import csv import pandas as pd from pandas import read_csv from sympy import * import sqlalchemy from sqlalchemy.orm import sessionmaker #Напишите скрипт, читающий во всех mp3-файлах указанной директории ID3v1-теги и выводящий...
pd.concat([titles, table[['capital', 'ccn3', 'area', 'currencies']], lat, lng], axis=1)
pandas.concat
import numpy as np import pandas as pd import time # count clock time import psutil # access the number of CPUs import pyomo.environ as pyo from pyomo.environ import Set, Var, Binary, NonNegativeReals, RealSet, Constraint, ConcreteModel, Objective, minimize, Suffix, DataPortal from...
pd.read_csv(CaseName+'/oT_Data_UpwardOperatingReserve_' +CaseName+'.csv', index_col=[0,1,2])
pandas.read_csv
import pandas as pd import string import numpy as np import pkg_resources import seaborn as sns from PIL import Image from wordcloud import WordCloud import matplotlib.pyplot as plt from pdfminer.high_level import extract_text from tqdm import tqdm import os class wording: def __init__(self): self.res...
pd.DataFrame()
pandas.DataFrame
""" Программа создает файлы-исходники в папке it\Иван\ИВАН\НовыйАвтомат(НК/ВБ/МАЙ)\Исходники(НК/ВБ/МАЙ)CRM , необходимые для автоматов Ивана. Логика основанана на сверке данных из JSON застройщика, где содержатся свободные квартиры, и "Эталонных выгрузок", в которых содержатся данные по всем квартирам вообще При выв...
pd.read_csv(path+'_'+file+'.csv',sep=';', encoding='cp1251',engine='python', index_col=False)
pandas.read_csv
# # 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...
pd.Series(arr, dtype=dtype, name=name)
pandas.Series
# -*- coding: utf-8 -*- import pytest import pandas as pd from numpy import nan, float64 from jqfactor_analyzer.prepare import get_clean_factor_and_forward_returns from jqfactor_analyzer.performance import ( factor_information_coefficient, factor_autocorrelation, mean_information_coefficient, quantil...
pd.testing.assert_frame_equal(avgrt, expected)
pandas.testing.assert_frame_equal
"""Provides helper functions for reading input data and configuration files. The default configuration values are provided in aneris.RC_DEFAULTS. """ from collections import abc import os import yaml import pandas as pd from aneris.utils import isstr, isnum, iamc_idx RC_DEFAULTS = """ config: default_luc_method...
pd.ExcelWriter(f, engine='xlsxwriter')
pandas.ExcelWriter
import os import unittest import pandas as pd from sklearn import datasets from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, Imputer, LabelEncoder, LabelBinarizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.tree import DecisionTreeRegressor from sklearn...
pd.DataFrame(iris.data,columns=iris.feature_names)
pandas.DataFrame
#import AYS_Environment as ays_env import c_global.cG_LAGTPKS_Environment as c_global import numpy as np import pandas as pd import sys,os import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredText pars=dict( Sigma = 1.5 * 1e8, Cstar=5500, a0=0.03, aT=3.2*1e3, ...
pd.DataFrame(actions[start_time:end_time])
pandas.DataFrame
# -*- coding: utf-8 -*- # # License: This module is released under the terms of the LICENSE file # contained within this applications INSTALL directory """ Utility functions for model generation """ # -- Coding Conventions # http://www.python.org/dev/peps/pep-0008/ - Use the Python s...
pd.Timedelta(23, unit='h')
pandas.Timedelta
""":func:`~pandas.eval` parsers """ import ast import operator import sys import inspect import tokenize import datetime import struct from functools import partial import pandas as pd from pandas import compat from pandas.compat import StringIO, zip, reduce, string_types from pandas.core.base import StringMixin fro...
com.pprint_thing(self.terms)
pandas.core.common.pprint_thing
import os import glob import psycopg2 import pandas as pd from sql_queries import * def process_song_file(cur, filepath): """Reads songs log file row by row, selects needed fields and inserts them into song and artist tables. Parameters: cur (psycopg2.cursor()): Cursor of the sparkifydb databa...
pd.read_json(filepath, lines=True)
pandas.read_json
#!/usr/bin/env python import sys import PySimpleGUI as sg import pandas as pd import numpy as np from icon import icon def file_picker(): """shows a file picker for selecting a postQC.tsv file. Returns None on Cancel.""" chooser = sg.Window('Choose file', [ [sg.Text('Filename')], [sg.Input(), ...
pd.unique(df['UID'])
pandas.unique
from flask import * from flask_cors import CORS,cross_origin import warnings import os import dash import plotly.express as px from flask import Flask, render_template #this has changed import plotly.graph_objs as go import numpy as np import dash_core_components as dcc import uuid from werkzeug.utils import secure_fil...
pd.DataFrame.from_dict(data_scraped['data'])
pandas.DataFrame.from_dict
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model from logistic_regression import LogisticRegression def Cal_accuracy(predictions, y): correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]...
pd.DataFrame(dict)
pandas.DataFrame
import pandas as pd import numpy as np import re as re from base import Feature, get_arguments, generate_features Feature.dir = 'features' # """sample usage # """ # class Pclass(Feature): # def create_features(self): # self.train['Pclass'] = train['Pclass'] # self.test['Pclass'] = test['Pclass']...
pd.to_datetime(test["publishedAt"])
pandas.to_datetime
# ----------------------------------------------------------------------------- '''A Feature Module of classes and functions related to stress distributions.''' # Case() : A collection of LaminateModel objects # Cases() : A collection of Cases # flake8 distributions.py --ignore E265,E501,N802,N806 import os import imp...
pd.Series(self.load_params)
pandas.Series
import time import datetime start_time = time.time() date = str(datetime.datetime.now().strftime(format='%m%d')) import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor # from sklearn import pipeline, model_selection from sklearn import pipeline, grid_search # from sklearn.fea...
pd.merge(all_details, hd_pro_desc, how='left', on='product_uid')
pandas.merge
from typing import List from bs4 import BeautifulSoup from pandas.core.frame import DataFrame import requests import pandas as pd import numpy as np import json # Scraping Target api to create a database stores = np.arange(0000, 4000, 1).tolist() stores = [str(store).zfill(4) for store in stores] # stores =...
pd.DataFrame(dot_data)
pandas.DataFrame
# -*- coding: utf-8 -*- """ @author: efourrier Purpose : Automated test suites with unittest run "python -m unittest -v test" in the module directory to run the tests The clock decorator in utils will measure the run time of the test """ ######################################################### # Import Packages a...
pd.Series(['A']*300 + ['B']*200 + ['C']*200 +['A']*300)
pandas.Series
# -*- coding: utf-8 -*- #----------------------------------------------------------------------------------- #Framework: #1. In this framework, only set parameters then train model for you. #2. Automatically recommend best models for you. Give you insights that what model # is fitting your problem best. #3. Give y...
pd.concat([X_norm, Y], axis=1)
pandas.concat
import pandas as pd import numpy as np import re import marcformat class MarcExtractor(object): tag_marc_file = 'MARC_FILE' tag_filter_columns = 'FILTER_COLUMNS' tag_marc_output_file = 'MARC_OUTPUT_FILE' marcFile = '' marcOutFile = '' filteredColumns = [] df =
pd.DataFrame()
pandas.DataFrame
""" GLM fitting utilities based on NeuroGLM by <NAME>, <NAME>: https://github.com/pillowlab/neuroGLM <NAME> International Brain Lab, 2020 """ from warnings import warn, catch_warnings import numpy as np from numpy.linalg.linalg import LinAlgError import pandas as pd from brainbox.processing import bincount2D from sk...
pd.Series(stimvecs, index=self.trialsdf.index)
pandas.Series
# ---------------------------------------------------------------------------- # Copyright (c) 2017-2019, 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(['sample_a', 'sample_b'], name='id')
pandas.Index
""" """ import io import os import pandas as pd import numpy as np from datetime import datetime import yaml import tethys_utils as tu import logging from time import sleep from pyproj import Proj, CRS, Transformer pd.options.display.max_columns = 10 ############################################# ### Parameters bas...
pd.read_csv(permit_csv)
pandas.read_csv
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-12-12 15:00:35 # @Author : <NAME> (<EMAIL>) # @Link : github.com/taseikyo # @Version : python3.5 """ obtain video information that exceeds the play threshold """ import os import sys import csv import requests import pandas as pd PLAY_THRESHOLD = 50...
pd.concat([df1, df2], axis=0, ignore_index=True, sort=False)
pandas.concat
# coding=utf-8 """ 数据源解析模块以及示例内置数据源的解析类实现 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import numpy as np import pandas as pd from .ABuSymbol import EMarketTargetType from ..CoreBu.ABuFixes import six from ..UtilBu import ABuDate...
pd.DataFrame(klines, index=dates_pd)
pandas.DataFrame
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import panel as pn from patchwork._sample import PROTECTED_COLUMN_NAMES, find_partially_labeled class SingleImageTagger(): def __init__(self, f, classname="class", size=200): self.classname = classname # determine PNG or JPG and ...
pd.isna(self.df[c])
pandas.isna
from pathlib import Path from typing import List, Tuple import matplotlib.pyplot as plt import pandas as pd from pylossmap import BLMData from pylossmap.lossmap import LossMap from tqdm.auto import tqdm def ufo_stable_proton(ufo_meta: pd.DataFrame) -> pd.DataFrame: ufo_meta = ufo_meta[ufo_meta["beam_mode"] == "S...
pd.Timedelta("1s")
pandas.Timedelta
import requests import pandas as pd from datetime import timedelta import numpy as np def ba_timezone(ba, format): """ Retrieves the UTC Offset (for standard time) for each balancing area. """ offset_dict = {'AEC': 6, 'AECI': 6, 'AVA': 8, 'AVRN': ...
pd.to_datetime(f'{start_date}T00:00:00{utc_offset}')
pandas.to_datetime
# %matplotlib notebook import pandas as pd import numpy as np import seaborn as sns sns.set(color_codes=True) from sklearn import preprocessing # from imblearn.over_sampling import SMOTE from imblearn.over_sampling import SMOTE,RandomOverSampler from sklearn.model_selection import train_test_split from sklearn.ensembl...
pd.read_pickle(fileNameToSave, compression='infer')
pandas.read_pickle
""" To fix the yield from the UPTSO preprocessed files both Schwaller & Lowe versions Keeps all data, no filtration done. Version: 1.31: 2021-04-16; A.M. @author: <NAME> (DocMinus) license: MIT License Copyright (c) 2021 DocMinus """ import pandas as pd import numpy as np def deconvolute_yield(row): text_yiel...
pd.to_numeric(data["TxtYield"], errors="coerce")
pandas.to_numeric
import numpy as np import random as rand import copy import time import matplotlib.pyplot as plt import sys import os import pandas as pd from .toric_model import * from .util import Action from .mcmc import * from .toric_model import Toric_code from matplotlib import rc #rc('font',**{'family':'sans-serif'})#,'sans-...
pd.DataFrame(columns=['SEQ', 'eps', 'kld', 'tvd', 'steps'])
pandas.DataFrame
__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...
pandas.DataFrame(self._returns_df[d])
pandas.DataFrame
import os from os.path import join as pjoin import numpy as np import pandas as pd import scipy.stats import dask from cesium import featurize from cesium.tests.fixtures import (sample_values, sample_ts_files, sample_featureset) import numpy.testing as npt import pytest DATA_PATH ...
pd.Series({'meta1': 0.5})
pandas.Series
import numpy as np import pytest from pandas import ( DataFrame, Index, MultiIndex, Series, Timestamp, date_range, to_datetime, ) import pandas._testing as tm import pandas.tseries.offsets as offsets class TestRollingTS: # rolling time-series friendly # xref GH13327 def set...
Timestamp("20130101 09:00:00")
pandas.Timestamp
"""Test functions in owid.datautils.dataframes module. """ import numpy as np import pandas as pd from pytest import warns from typing import Any, Dict from owid.datautils import dataframes class TestCompareDataFrames: def test_with_large_absolute_tolerance_all_equal(self): assert dataframes.compare( ...
pd.DataFrame({"col_01": [1, 2]})
pandas.DataFrame
# -*- coding: utf-8 -*- """ Created on Wed Jan 16 11:27:05 2019 @author: <NAME> """ """ Quick Start In order to use this program, you will need to do these things: * Specify a value for the variable 'server' to indicate whether local files will be input for, perhaps, debugging mode or file path...
pd.read_csv(path1+files1[i])
pandas.read_csv
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' functions that disambiguate names using an external file. Inputs are: - a tab delimited csv with columns "Unique Names" (= found name, as in the text) and "NameCopy" (the right name) - output from 01_parse_xml.py The "disambiguate_names" function will use the ...
pd.read_csv(original_path, delimiter=cf.CSV_SEP)
pandas.read_csv
import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize("align_axis", [0, 1, "index", "columns"]) def test_compare_axis(align_axis): # GH#30429 s1 = pd.Series(["a", "b", "c"]) s2 = pd.Series(["x", "b", "z"]) result = s1.compare(s2, align_axis=align_...
pd.Index(["self", "other"])
pandas.Index
# -*- coding: utf-8 -*- from __future__ import print_function from distutils.version import LooseVersion from numpy import nan, random import numpy as np from pandas.compat import lrange from pandas import (DataFrame, Series, Timestamp, date_range) import pandas as pd from pandas.util.testing im...
pd.Timestamp('2013-01-02')
pandas.Timestamp
#!/usr/bin/env python # coding: utf-8 # # <font color='yellow'>How can we predict not just the hourly PM2.5 concentration at the site of one EPA sensor, but predict the hourly PM2.5 concentration anywhere?</font> # # Here, you build a new model for any given hour on any given day. This will leverage readings across a...
pd.set_option('display.max_columns', 500)
pandas.set_option
import unittest import keras import numpy as np import pandas as pd import sklearn from sklearn import preprocessing import xrdos class test_xrdos(unittest.TestCase): def test_split(self): data = {'column1': [2, 2, 3], 'column2': [1, 3, 5]} df = pd.DataFrame(data) one, two = xrdos.split...
pd.DataFrame(data)
pandas.DataFrame
# -*- coding: utf-8 -*- import datetime as dt, logging, numpy, pandas as pd, pyarrow as pa, unittest import graphistry, graphistry.plotter from common import NoAuthTestCase logger = logging.getLogger(__name__) nid = graphistry.plotter.Plotter._defaultNodeId triangleNodesDict = { 'id': ['a', 'b', 'c'], 'a1...
pd.DataFrame({'aa': [0, 1, 2], 'bb': ['a', 'b', 'c'], 'cc': ['b', 0, 1]})
pandas.DataFrame
""" This code is copied from Philippjfr's notebook: https://anaconda.org/philippjfr/sankey/notebook """ from functools import cmp_to_key import holoviews as hv import numpy as np import pandas as pd import param from bokeh.models import Patches from holoviews import Operation from holoviews.core.util import basestrin...
pd.DataFrame(links)
pandas.DataFrame
import numpy import pandas import sklearn import seaborn import matplotlib.pyplot as plot from sklearn import datasets from sklearn import model_selection from sklearn import pipeline from sklearn import preprocessing from sklearn import linear_model from sklearn import ensemble from sklearn import metrics from sklear...
pandas.Series(iris.target)
pandas.Series
# -*- coding: utf-8 -*- """ Notes and tries on Chaper 03 (Think Stats 2, <NAME>) Self-study on statistics using pyhton @author: Github: @rafaelmm82 """ import thinkstats2 import thinkplot import nsfg import math import first import matplotlib.pyplot as plt import numpy as np import pandas as pd pmf=...
pd.DataFrame(array)
pandas.DataFrame
import pandas as pd from argparse import ArgumentParser def read_metadata(f): print(f"reading metadata file {f}...") df = pd.read_csv(f,sep='\t',low_memory=False) df['fulldate'] = df['date'].apply(lambda x: "XX" not in str(x)) df = df.query("fulldate == True").copy() df['date'] =
pd.to_datetime(df['date'])
pandas.to_datetime
import os # Reduce CPU load. Need to perform BEFORE import numpy and some other libraries. os.environ['MKL_NUM_THREADS'] = '2' os.environ['OMP_NUM_THREADS'] = '2' os.environ['NUMEXPR_NUM_THREADS'] = '2' import gc import math import copy import json import numpy as np import pandas as pd import torch as th import torch...
pd.read_csv('test.csv')
pandas.read_csv
from copy import deepcopy import elasticsearch import pandas as pd from suricate.base import ConnectorMixin from suricate.dftransformers.cartesian import cartesian_join import numpy as np import time ixname = 'ix' ixnamesource = 'ix_source' ixnametarget = 'ix_target' ixname_pairs = [ixnamesource, ixnametarget] class...
pd.DataFrame.from_dict(score, orient='columns')
pandas.DataFrame.from_dict
## 1. Recap ## import pandas as pd loans = pd.read_csv("cleaned_loans_2007.csv") print(loans.info()) ## 3. Picking an error metric ## import pandas as pd # False positives. fp_filter = (predictions == 1) & (loans["loan_status"] == 0) fp = len(predictions[fp_filter]) # True positives. tp_filter = (predictions == 1) ...
pd.Series(predictions)
pandas.Series
#!/usr/bin/env python3 """ dataframe_utils.py Utilities for pd.DataFrame manipulation for ipy notebooks. """ import errno import os from astropy import units as u from astropy.coordinates import SkyCoord from astropy.io import fits from astropy.table import Table import matplotlib.pyplot as plt import numpy as np im...
pd.read_pickle(pickle_path)
pandas.read_pickle