INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Constructs a OpenAIGPTConfig from a Python dictionary of parameters.
def from_dict(cls, json_object): """Constructs a `OpenAIGPTConfig` from a Python dictionary of parameters.""" config = OpenAIGPTConfig(vocab_size_or_config_json_file=-1) for key, value in json_object.items(): config.__dict__[key] = value return config
Update input embeddings with new embedding matrice if needed
def set_num_special_tokens(self, num_special_tokens): " Update input embeddings with new embedding matrice if needed " if self.config.n_special == num_special_tokens: return # Update config self.config.n_special = num_special_tokens # Build new embeddings and initiali...
Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings
def set_num_special_tokens(self, num_special_tokens): """ Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings """ self.transformer.set_num_special_tokens(num_special_tokens) self.lm_head.set_embeddings_weights(self.transformer...
Performs a single optimization step.
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for...
: param step: which of t_total steps we re on: param nowarn: set to True to suppress warning regarding training beyond specified t_total steps: return: learning rate multiplier for current update
def get_lr(self, step, nowarn=False): """ :param step: which of t_total steps we're on :param nowarn: set to True to suppress warning regarding training beyond specified 't_total' steps :return: learning rate multiplier for current update """ if self.t_total < ...
Performs a single optimization step.
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for...
Runs basic whitespace cleaning and splitting on a piece of text.
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
Checks whether chars is a punctuation character.
def _is_punctuation(char): """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency....
Converts a sequence of tokens into ids using the vocab.
def convert_tokens_to_ids(self, tokens): """Converts a sequence of tokens into ids using the vocab.""" ids = [] for token in tokens: ids.append(self.vocab[token]) if len(ids) > self.max_len: logger.warning( "Token indices sequence length is longer ...
Converts a sequence of ids in wordpiece tokens using the vocab.
def convert_ids_to_tokens(self, ids): """Converts a sequence of ids in wordpiece tokens using the vocab.""" tokens = [] for i in ids: tokens.append(self.ids_to_tokens[i]) return tokens
Save the tokenizer vocabulary to a directory or file.
def save_vocabulary(self, vocab_path): """Save the tokenizer vocabulary to a directory or file.""" index = 0 if os.path.isdir(vocab_path): vocab_file = os.path.join(vocab_path, VOCAB_NAME) with open(vocab_file, "w", encoding="utf-8") as writer: for token, token_in...
Instantiate a PreTrainedBertModel from a pre - trained model file. Download and cache the pre - trained model file if needed.
def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): """ Instantiate a PreTrainedBertModel from a pre-trained model file. Download and cache the pre-trained model file if needed. """ if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHI...
Tokenizes a piece of text.
def tokenize(self, text): """Tokenizes a piece of text.""" text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English models were not tra...
Strips accents from a piece of text.
def _run_strip_accents(self, text): """Strips accents from a piece of text.""" text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": continue output.append(char) ...
Adds whitespace around any CJK character.
def _tokenize_chinese_chars(self, text): """Adds whitespace around any CJK character.""" output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") ...
Checks whether CP is the codepoint of a CJK character.
def _is_chinese_char(self, cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is ...
Tokenizes a piece of text into its word pieces.
def tokenize(self, text): """Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example: input = "unaffable" output = ["un", "##aff", "##able"] Args: ...
Output a list of tuples ( story 1st continuation 2nd continuation label )
def load_rocstories_dataset(dataset_path): """ Output a list of tuples(story, 1st continuation, 2nd continuation, label) """ with open(dataset_path, encoding='utf_8') as f: f = csv.reader(f) output = [] next(f) # skip the first line for line in tqdm(f): output.append(...
Pre - process datasets containing lists of tuples ( story 1st continuation 2nd continuation label )
def pre_process_datasets(encoded_datasets, input_len, cap_length, start_token, delimiter_token, clf_token): """ Pre-process datasets containing lists of tuples(story, 1st continuation, 2nd continuation, label) To Transformer inputs of shape (n_batch, n_alternative, length) comprising for each batch, contin...
Masking some random tokens for Language Model task with probabilities as in the original BERT paper.: param tokens: list of str tokenized sentence.: param tokenizer: Tokenizer object used for tokenization ( we need it s vocab here ): return: ( list of str list of int ) masked tokens and related labels for LM prediction
def random_word(tokens, tokenizer): """ Masking some random tokens for Language Model task with probabilities as in the original BERT paper. :param tokens: list of str, tokenized sentence. :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here) :return: (list of str, list...
Convert a raw sample ( pair of sentences as tokenized strings ) into a proper training sample with IDs LM labels input_mask CLS and SEP tokens etc.: param example: InputExample containing sentence input as strings and is_next label: param max_seq_length: int maximum length of sequence.: param tokenizer: Tokenizer: retu...
def convert_example_to_features(example, max_seq_length, tokenizer): """ Convert a raw sample (pair of sentences as tokenized strings) into a proper training sample with IDs, LM labels, input_mask, CLS and SEP tokens etc. :param example: InputExample, containing sentence input as strings and is_next lab...
Get one sample from corpus consisting of two sentences. With prob. 50% these are two subsequent sentences from one doc. With 50% the second sentence will be a random one from another doc.: param index: int index of sample.: return: ( str str int ) sentence 1 sentence 2 isNextSentence Label
def random_sent(self, index): """ Get one sample from corpus consisting of two sentences. With prob. 50% these are two subsequent sentences from one doc. With 50% the second sentence will be a random one from another doc. :param index: int, index of sample. :return: (str, str, in...
Get one sample from corpus consisting of a pair of two subsequent lines from the same doc.: param item: int index of sample.: return: ( str str ) two subsequent sentences from corpus
def get_corpus_line(self, item): """ Get one sample from corpus consisting of a pair of two subsequent lines from the same doc. :param item: int, index of sample. :return: (str, str), two subsequent sentences from corpus """ t1 = "" t2 = "" assert item < s...
Get random line from another document for nextSentence task.: return: str content of one line
def get_random_line(self): """ Get random line from another document for nextSentence task. :return: str, content of one line """ # Similar to original tf repo: This outer loop should rarely go for more than one iteration for large # corpora. However, just to be careful, ...
Gets next line of random_file and starts over when reaching end of file
def get_next_line(self): """ Gets next line of random_file and starts over when reaching end of file""" try: line = next(self.random_file).strip() #keep track of which document we are currently looking at to later avoid having the same doc as t1 if line == "": ...
Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo but with several refactors to clean it up and remove a lot of unnecessary variables.
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_list): """Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but with several refactors to clean it up and remove a lot of unnecessary variables.""" cand_indices = [] ...
This code is mostly a duplicate of the equivalent function from Google BERT s repo. However we make some changes and improvements. Sampling is improved and no longer requires a loop in this function. Also documents are sampled proportionally to the number of sentences they contain which means each sentence ( rather tha...
def create_instances_from_document( doc_database, doc_idx, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_list): """This code is mostly a duplicate of the equivalent function from Google BERT's repo. However, we make some changes and improvements. Sampling is impr...
embedding: an nn. Embedding layer bias: [ n_vocab ] labels: [ b1 b2 ] inputs: [ b1 b2 n_emb ] sampler: you may use a LogUniformSampler Return logits: [ b1 b2 1 + n_sample ]
def sample_logits(embedding, bias, labels, inputs, sampler): """ embedding: an nn.Embedding layer bias: [n_vocab] labels: [b1, b2] inputs: [b1, b2, n_emb] sampler: you may use a LogUniformSampler Return logits: [b1, b2, 1 + n_sample] """ true_log_probs, sa...
Params: hidden:: [ len * bsz x d_proj ] target:: [ len * bsz ] Return: if target is None: out:: [ len * bsz ] Negative log likelihood else: out:: [ len * bsz x n_tokens ] log probabilities of tokens over the vocabulary We could replace this implementation by the native PyTorch one if their s had an option to set bias o...
def forward(self, hidden, target=None, keep_order=False): ''' Params: hidden :: [len*bsz x d_proj] target :: [len*bsz] Return: if target is None: out :: [len*bsz] Negative log likelihood else: ...
r Computes log probabilities for all: math: n \ _classes From: https:// github. com/ pytorch/ pytorch/ blob/ master/ torch/ nn/ modules/ adaptive. py Args: hidden ( Tensor ): a minibatch of examples Returns: log - probabilities of for each class: math: c in range: math: 0 < = c < = n \ _classes where: math: n \ _classe...
def log_prob(self, hidden): r""" Computes log probabilities for all :math:`n\_classes` From: https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.py Args: hidden (Tensor): a minibatch of examples Returns: log-probabilities of for each class :ma...
labels: [ b1 b2 ] Return true_log_probs: [ b1 b2 ] samp_log_probs: [ n_sample ] neg_samples: [ n_sample ]
def sample(self, labels): """ labels: [b1, b2] Return true_log_probs: [b1, b2] samp_log_probs: [n_sample] neg_samples: [n_sample] """ # neg_samples = torch.empty(0).long() n_sample = self.n_sample n_tries = 2 * n_sample ...
A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible.
def build_tf_to_pytorch_map(model, config): """ A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible. """ tf_to_pt_map = {} if hasattr(model, 'transformer'): # We are loading in a TransfoXLLMHeadModel...
Load tf checkpoints in a pytorch model
def load_tf_weights_in_transfo_xl(model, config, tf_path): """ Load tf checkpoints in a pytorch model """ try: import numpy as np import tensorflow as tf except ImportError: print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " ...
Initialize the weights.
def init_weights(self, m): """ Initialize the weights. """ classname = m.__class__.__name__ if classname.find('Linear') != -1: if hasattr(m, 'weight') and m.weight is not None: self.init_weight(m.weight) if hasattr(m, 'bias') and m.bias is not None...
Instantiate a TransfoXLPreTrainedModel from a pre - trained model file or a pytorch state dict. Download and cache the pre - trained model file if needed.
def from_pretrained(cls, pretrained_model_name_or_path, state_dict=None, cache_dir=None, from_tf=False, *inputs, **kwargs): """ Instantiate a TransfoXLPreTrainedModel from a pre-trained model file or a pytorch state dict. Download and cache the pre-trained model file if n...
Params: input_ids:: [ bsz len ] mems:: optional mems from previous forwar passes ( or init_mems ) list ( num layers ) of mem states at the entry of each layer shape:: [ self. config. mem_len bsz self. config. d_model ] Note that the first two dimensions are transposed in mems with regards to input_ids and target Return...
def forward(self, input_ids, mems=None): """ Params: input_ids :: [bsz, len] mems :: optional mems from previous forwar passes (or init_mems) list (num layers) of mem states at the entry of each layer shape :: [self.config.mem_len, bsz,...
Run this to be sure output and input ( adaptive ) softmax weights are tied
def tie_weights(self): """ Run this to be sure output and input (adaptive) softmax weights are tied """ # sampled softmax if self.sample_softmax > 0: if self.config.tie_weight: self.out_layer.weight = self.transformer.word_emb.weight # adaptive softmax (includ...
Params: input_ids:: [ bsz len ] target:: [ bsz len ] Returns: tuple ( softmax_output new_mems ) where: new_mems: list ( num layers ) of hidden states at the entry of each layer shape:: [ mem_len bsz self. config. d_model ]:: Warning: shapes are transposed here w. regards to input_ids softmax_output: output of the ( ada...
def forward(self, input_ids, target=None, mems=None): """ Params: input_ids :: [bsz, len] target :: [bsz, len] Returns: tuple(softmax_output, new_mems) where: new_mems: list (num layers) of hidden states at the entry of each layer ...
Return DateOffset object from string or tuple representation or datetime. timedelta object
def to_offset(freq): """ Return DateOffset object from string or tuple representation or datetime.timedelta object Parameters ---------- freq : str, tuple, datetime.timedelta, DateOffset or None Returns ------- DateOffset None if freq is None. Raises ------ Val...
Return DateOffset object associated with rule name
def get_offset(name): """ Return DateOffset object associated with rule name Examples -------- get_offset('EOM') --> BMonthEnd(1) """ if name not in libfreqs._dont_uppercase: name = name.upper() name = libfreqs._lite_rule_alias.get(name, name) name = libfreqs._lite_r...
Infer the most likely frequency given the input index. If the frequency is uncertain a warning will be printed.
def infer_freq(index, warn=True): """ Infer the most likely frequency given the input index. If the frequency is uncertain, a warning will be printed. Parameters ---------- index : DatetimeIndex or TimedeltaIndex if passed a Series will use the values of the series (NOT THE INDEX) war...
Find the appropriate frequency string to describe the inferred frequency of self. values
def get_freq(self): """ Find the appropriate frequency string to describe the inferred frequency of self.values Returns ------- str or None """ if not self.is_monotonic or not self.index._is_unique: return None delta = self.deltas[0] ...
load a pickle with a provided encoding
def load(fh, encoding=None, is_verbose=False): """load a pickle, with a provided encoding if compat is True: fake the old class hierarchy if it works, then return the new type objects Parameters ---------- fh : a filelike object encoding : an optional encoding is_verbose : sh...
This is called upon unpickling rather than the default which doesn t have arguments and breaks __new__.
def _new_Index(cls, d): """ This is called upon unpickling, rather than the default which doesn't have arguments and breaks __new__. """ # required for backward compat, because PI can't be instantiated with # ordinals through __new__ GH #13277 if issubclass(cls, ABCPeriodIndex): from...
Construct an index from sequences of data.
def ensure_index_from_sequences(sequences, names=None): """ Construct an index from sequences of data. A single sequence returns an Index. Many sequences returns a MultiIndex. Parameters ---------- sequences : sequence of sequences names : sequence of str Returns ------- i...
Ensure that we have an index from some index - like object.
def ensure_index(index_like, copy=False): """ Ensure that we have an index from some index-like object. Parameters ---------- index : sequence An Index or other sequence copy : bool Returns ------- index : Index or MultiIndex Examples -------- >>> ensure_index(...
Trims zeros and decimal points.
def _trim_front(strings): """ Trims zeros and decimal points. """ trimmed = strings while len(strings) > 0 and all(x[0] == ' ' for x in trimmed): trimmed = [x[1:] for x in trimmed] return trimmed
We require that we have a dtype compat for the values. If we are passed a non - dtype compat then coerce using the constructor.
def _simple_new(cls, values, name=None, dtype=None, **kwargs): """ We require that we have a dtype compat for the values. If we are passed a non-dtype compat, then coerce using the constructor. Must be careful not to recurse. """ if not hasattr(values, 'dtype'): ...
Create a new Index inferring the class with passed value don t copy the data use the same object attributes with passed in attributes taking precedence.
def _shallow_copy_with_infer(self, values, **kwargs): """ Create a new Index inferring the class with passed value, don't copy the data, use the same object attributes with passed in attributes taking precedence. *this is an internal non-public method* Parameters ...
More flexible faster check like is but that works through views.
def is_(self, other): """ More flexible, faster check like ``is`` but that works through views. Note: this is *not* the same as ``Index.identical()``, which checks that metadata is also the same. Parameters ---------- other : object other object to c...
Internal method to handle NA filling of take.
def _assert_take_fillable(self, values, indices, allow_fill=True, fill_value=None, na_value=np.nan): """ Internal method to handle NA filling of take. """ indices = ensure_platform_int(indices) # only fill if we are passing a non-None fill_value ...
Return the formatted data as a unicode string.
def _format_data(self, name=None): """ Return the formatted data as a unicode string. """ # do we want to justify (only do so for non-objects) is_justify = not (self.inferred_type in ('string', 'unicode') or (self.inferred_type == 'categorical' and ...
Render a string representation of the Index.
def format(self, name=False, formatter=None, **kwargs): """ Render a string representation of the Index. """ header = [] if name: header.append(pprint_thing(self.name, escape_chars=('\t', '\r', '\n')) if ...
Format specified values of self and return them.
def to_native_types(self, slicer=None, **kwargs): """ Format specified values of `self` and return them. Parameters ---------- slicer : int, array-like An indexer into `self` that specifies which values are used in the formatting process. kwargs :...
Actually format specific types of the index.
def _format_native_types(self, na_rep='', quoting=None, **kwargs): """ Actually format specific types of the index. """ mask = isna(self) if not self.is_object() and not quoting: values = np.asarray(self).astype(str) else: values = np.array(self, d...
Return a summarized representation.
def _summary(self, name=None): """ Return a summarized representation. Parameters ---------- name : str name to use in the summary representation Returns ------- String with a summarized representation of the index """ if len(...
Return a summarized representation.
def summary(self, name=None): """ Return a summarized representation. .. deprecated:: 0.23.0 """ warnings.warn("'summary' is deprecated and will be removed in a " "future version.", FutureWarning, stacklevel=2) return self._summary(name)
Create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index.
def to_series(self, index=None, name=None): """ Create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index. Parameters ---------- index : Index, optional index of resulting Series. If None, de...
Create a DataFrame with a column containing the Index.
def to_frame(self, index=True, name=None): """ Create a DataFrame with a column containing the Index. .. versionadded:: 0.24.0 Parameters ---------- index : boolean, default True Set the index of the returned DataFrame as the original Index. name : ...
Handles the quirks of having a singular name parameter for general Index and plural names parameter for MultiIndex.
def _validate_names(self, name=None, names=None, deep=False): """ Handles the quirks of having a singular 'name' parameter for general Index and plural 'names' parameter for MultiIndex. """ from copy import deepcopy if names is not None and name is not None: r...
Set new names on index. Each name has to be a hashable type.
def _set_names(self, values, level=None): """ Set new names on index. Each name has to be a hashable type. Parameters ---------- values : str or sequence name(s) to set level : int, level name, or sequence of int/level names (default None) If the ...
Set Index or MultiIndex name.
def set_names(self, names, level=None, inplace=False): """ Set Index or MultiIndex name. Able to set new names partially and by level. Parameters ---------- names : label or list of label Name(s) to set. level : int, label or list of int or label, op...
Alter Index or MultiIndex name.
def rename(self, name, inplace=False): """ Alter Index or MultiIndex name. Able to set new names without level. Defaults to returning new index. Length of names must match number of levels in MultiIndex. Parameters ---------- name : label or list of labels ...
Validate index level.
def _validate_index_level(self, level): """ Validate index level. For single-level Index getting level number is a no-op, but some verification must be done like in MultiIndex. """ if isinstance(level, int): if level < 0 and level != -1: rais...
For internal compatibility with with the Index API.
def sortlevel(self, level=None, ascending=True, sort_remaining=None): """ For internal compatibility with with the Index API. Sort the Index. This is for compat with MultiIndex Parameters ---------- ascending : boolean, default True False to sort in descendi...
Return index with requested level ( s ) removed.
def droplevel(self, level=0): """ Return index with requested level(s) removed. If resulting index has only 1 level left, the result will be of Index type, not MultiIndex. .. versionadded:: 0.23.1 (support for non-MultiIndex) Parameters ---------- level...
Return if each value is NaN.
def _isnan(self): """ Return if each value is NaN. """ if self._can_hold_na: return isna(self) else: # shouldn't reach to this condition by checking hasnans beforehand values = np.empty(len(self), dtype=np.bool_) values.fill(False) ...
Extract duplicated index elements.
def get_duplicates(self): """ Extract duplicated index elements. .. deprecated:: 0.23.0 Use idx[idx.duplicated()].unique() instead Returns a sorted list of index elements which appear more than once in the index. Returns ------- array-like ...
Returns an index containing unique values.
def _get_unique_index(self, dropna=False): """ Returns an index containing unique values. Parameters ---------- dropna : bool If True, NaN values are dropped. Returns ------- uniques : index """ if self.is_unique and not dropn...
If the result of a set operation will be self return self unless the name changes in which case make a shallow copy of self.
def _get_reconciled_name_object(self, other): """ If the result of a set operation will be self, return self, unless the name changes, in which case make a shallow copy of self. """ name = get_op_result_name(self, other) if self.name != name: return se...
Form the union of two Index objects.
def union(self, other, sort=None): """ Form the union of two Index objects. Parameters ---------- other : Index or array-like sort : bool or None, default None Whether to sort the resulting Index. * None : Sort the result, except when ...
Form the intersection of two Index objects.
def intersection(self, other, sort=False): """ Form the intersection of two Index objects. This returns a new Index with elements common to the index and `other`. Parameters ---------- other : Index or array-like sort : False or None, default False W...
Return a new Index with elements from the index that are not in other.
def difference(self, other, sort=None): """ Return a new Index with elements from the index that are not in `other`. This is the set difference of two Index objects. Parameters ---------- other : Index or array-like sort : False or None, default None ...
Compute the symmetric difference of two Index objects.
def symmetric_difference(self, other, result_name=None, sort=None): """ Compute the symmetric difference of two Index objects. Parameters ---------- other : Index or array-like result_name : str sort : False or None, default None Whether to sort the r...
Fallback pad/ backfill get_indexer that works for monotonic decreasing indexes and non - monotonic targets.
def _get_fill_indexer_searchsorted(self, target, method, limit=None): """ Fallback pad/backfill get_indexer that works for monotonic decreasing indexes and non-monotonic targets. """ if limit is not None: raise ValueError('limit argument for %r method only well-define...
Get the indexer for the nearest index labels ; requires an index with values that can be subtracted from each other ( e. g. not strings or tuples ).
def _get_nearest_indexer(self, target, limit, tolerance): """ Get the indexer for the nearest index labels; requires an index with values that can be subtracted from each other (e.g., not strings or tuples). """ left_indexer = self.get_indexer(target, 'pad', limit=limit) ...
Parameters ---------- keyarr: list - like Indexer to convert.
def _convert_listlike_indexer(self, keyarr, kind=None): """ Parameters ---------- keyarr : list-like Indexer to convert. Returns ------- indexer : numpy.ndarray or None Return an ndarray or None if cannot convert. keyarr : numpy.nd...
Consistent invalid indexer message.
def _invalid_indexer(self, form, key): """ Consistent invalid indexer message. """ raise TypeError("cannot do {form} indexing on {klass} with these " "indexers [{key}] of {kind}".format( form=form, klass=type(self), key=key, ...
Create index with target s values ( move/ add/ delete values as necessary ).
def reindex(self, target, method=None, level=None, limit=None, tolerance=None): """ Create index with target's values (move/add/delete values as necessary). Parameters ---------- target : an iterable Returns ------- new_index : pd...
Create a new index with target s values ( move/ add/ delete values as necessary ) use with non - unique Index and a possibly non - unique target.
def _reindex_non_unique(self, target): """ Create a new index with target's values (move/add/delete values as necessary) use with non-unique Index and a possibly non-unique target. Parameters ---------- target : an iterable Returns ------- new_in...
The join method * only * affects the level of the resulting MultiIndex. Otherwise it just exactly aligns the Index data to the labels of the level in the MultiIndex.
def _join_level(self, other, level, how='left', return_indexers=False, keep_order=True): """ The join method *only* affects the level of the resulting MultiIndex. Otherwise it just exactly aligns the Index data to the labels of the level in the MultiIndex. If...
Attempt to convert an array of data into an integer index.
def _try_convert_to_int_index(cls, data, copy, name, dtype): """ Attempt to convert an array of data into an integer index. Parameters ---------- data : The data to convert. copy : Whether to copy the data or not. name : The name of the index returned. R...
Coerces data to ndarray.
def _coerce_to_ndarray(cls, data): """ Coerces data to ndarray. Converts other iterables to list first and then to array. Does not touch ndarrays. Raises ------ TypeError When the data passed in is a scalar. """ if not isinstance(dat...
We need to coerce a scalar to a compat for our index type.
def _coerce_scalar_to_index(self, item): """ We need to coerce a scalar to a compat for our index type. Parameters ---------- item : scalar item to coerce """ dtype = self.dtype if self._is_numeric_dtype and isna(item): # We can't coerce to t...
Check value is valid for scalar op.
def _assert_can_do_op(self, value): """ Check value is valid for scalar op. """ if not is_scalar(value): msg = "'value' must be a scalar, passed: {0}" raise TypeError(msg.format(type(value).__name__))
Faster check for name in self when we know name is a Python identifier ( e. g. in NDFrame. __getattr__ which hits this to support. key lookup ). For indexes that can t hold identifiers ( everything but object & categorical ) we just return False.
def _can_hold_identifiers_and_holds_name(self, name): """ Faster check for ``name in self`` when we know `name` is a Python identifier (e.g. in NDFrame.__getattr__, which hits this to support . key lookup). For indexes that can't hold identifiers (everything but object & categori...
Append a collection of Index options together.
def append(self, other): """ Append a collection of Index options together. Parameters ---------- other : Index or list/tuple of indices Returns ------- appended : Index """ to_concat = [self] if isinstance(other, (list, tuple))...
Return a new Index of the values set with the mask.
def putmask(self, mask, value): """ Return a new Index of the values set with the mask. See Also -------- numpy.ndarray.putmask """ values = self.values.copy() try: np.putmask(values, mask, self._convert_for_op(value)) return self....
Determine if two Index objects contain the same elements.
def equals(self, other): """ Determine if two Index objects contain the same elements. """ if self.is_(other): return True if not isinstance(other, Index): return False if is_object_dtype(self) and not is_object_dtype(other): # if oth...
Similar to equals but check that other comparable attributes are also equal.
def identical(self, other): """ Similar to equals, but check that other comparable attributes are also equal. """ return (self.equals(other) and all((getattr(self, c, None) == getattr(other, c, None) for c in self._comparables)) and ...
Return the label from the index or if not present the previous one.
def asof(self, label): """ Return the label from the index, or, if not present, the previous one. Assuming that the index is sorted, return the passed index label if it is in the index, or return the previous index label if the passed one is not in the index. Parameters...
Find the locations ( indices ) of the labels from the index for every entry in the where argument.
def asof_locs(self, where, mask): """ Find the locations (indices) of the labels from the index for every entry in the `where` argument. As in the `asof` function, if the label (a particular entry in `where`) is not in the index, the latest index label upto the passed la...
Return a sorted copy of the index.
def sort_values(self, return_indexer=False, ascending=True): """ Return a sorted copy of the index. Return a sorted copy of the index, and optionally return the indices that sorted the index itself. Parameters ---------- return_indexer : bool, default False ...
Return the integer indices that would sort the index.
def argsort(self, *args, **kwargs): """ Return the integer indices that would sort the index. Parameters ---------- *args Passed to `numpy.ndarray.argsort`. **kwargs Passed to `numpy.ndarray.argsort`. Returns ------- numpy...
Fast lookup of value from 1 - dimensional ndarray. Only use this if you know what you re doing.
def get_value(self, series, key): """ Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing. """ # if we have something that is Index-like, then # use this, e.g. DatetimeIndex # Things like `Series._get_value` (via .at) pass...
Fast lookup of value from 1 - dimensional ndarray.
def set_value(self, arr, key, value): """ Fast lookup of value from 1-dimensional ndarray. Notes ----- Only use this if you know what you're doing. """ self._engine.set_value(com.values_from_object(arr), com.values_from_object(key),...
Guaranteed return of an indexer even when non - unique.
def get_indexer_for(self, target, **kwargs): """ Guaranteed return of an indexer even when non-unique. This dispatches to get_indexer or get_indexer_nonunique as appropriate. """ if self.is_unique: return self.get_indexer(target, **kwargs) indexer, _ ...
Group the index labels by a given array of values.
def groupby(self, values): """ Group the index labels by a given array of values. Parameters ---------- values : array Values used to determine the groups. Returns ------- groups : dict {group name -> group labels} """ ...
Map values using input correspondence ( a dict Series or function ).
def map(self, mapper, na_action=None): """ Map values using input correspondence (a dict, Series, or function). Parameters ---------- mapper : function, dict, or Series Mapping correspondence. na_action : {None, 'ignore'} If 'ignore', propagate NA...
Return a boolean array where the index values are in values.
def isin(self, values, level=None): """ Return a boolean array where the index values are in `values`. Compute boolean array of whether each index value is found in the passed set of values. The length of the returned boolean array matches the length of the index. Param...