Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def from_pretrained( cls, pretrained_model_name_or_path, state_dict=None, cache_dir=None, from_tf=False, *inputs, **kwargs ): if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP: archive_file = PRETRAINED_MODEL_ARCHIVE_MA...
[ "\n Instantiate a GPT2PreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected ...
Please provide a description of the function:def convert_examples_to_features(examples, seq_length, tokenizer): features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tok...
[ "Loads a data file into a list of `InputFeature`s." ]
Please provide a description of the function:def read_examples(input_file): examples = [] unique_id = 0 with open(input_file, "r", encoding='utf-8') as reader: while True: line = reader.readline() if not line: break line = line.strip() ...
[ "Read a list of `InputExample`s from an input file." ]
Please provide a description of the function:def read_squad_examples(input_file, is_training, version_2_with_negative): with open(input_file, "r", encoding='utf-8') as reader: input_data = json.load(reader)["data"] def is_whitespace(c): if c == " " or c == "\t" or c == "\r" or c == "\n" or...
[ "Read a SQuAD json file into a list of SquadExample." ]
Please provide a description of the function:def convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training): unique_id = 1000000000 features = [] for (example_index, example) in enumerate(examples): query_token...
[ "Loads a data file into a list of `InputBatch`s." ]
Please provide a description of the function:def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): # The SQuAD annotations are character based. We first project them to # whitespace-tokenized words. But then after WordPiece tokenization, we can...
[ "Returns tokenized answer spans that better match the annotated answer." ]
Please provide a description of the function:def _check_is_max_context(doc_spans, cur_span_index, position): # Because of the sliding window approach taken to scoring documents, a single # token can appear in multiple documents. E.g. # Doc: the man went to the store and bought a gallon of milk # ...
[ "Check if this is the 'max context' doc span for the token." ]
Please provide a description of the function:def write_predictions(all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case, output_prediction_file, output_nbest_file, output_null_log_odds_file, verbose_logging, version_2_wi...
[ "Write final predictions to the json file and log-odds of null if needed." ]
Please provide a description of the function:def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False): # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_text` contains the...
[ "Project the tokenized prediction back to the original text." ]
Please provide a description of the function:def _get_best_indexes(logits, n_best_size): index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True) best_indexes = [] for i in range(len(index_and_score)): if i >= n_best_size: break best_indexes.append(inde...
[ "Get the n-best logits from a list." ]
Please provide a description of the function:def _compute_softmax(scores): if not scores: return [] max_score = None for score in scores: if max_score is None or score > max_score: max_score = score exp_scores = [] total_sum = 0.0 for score in scores: x...
[ "Compute softmax probability over raw logits." ]
Please provide a description of the function:def convert_examples_to_features(examples, tokenizer, max_seq_length, is_training): # Swag is a multiple choice task. To perform this task using Bert, # we will use the formatting proposed in "Improving Language # Understand...
[ "Loads a data file into a list of `InputBatch`s." ]
Please provide a description of the function:def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_mode): label_map = {label : i for i, label in enumerate(label_list)} features = [] for (ex_index, example) in enumerate(examples): ...
[ "Loads a data file into a list of `InputBatch`s." ]
Please provide a description of the function:def _read_tsv(cls, input_file, quotechar=None): with open(input_file, "r", encoding="utf-8") as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: if sys.version_i...
[ "Reads a tab separated value file." ]
Please provide a description of the function:def get_train_examples(self, data_dir): logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv"))) return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
[ "See base class." ]
Please provide a description of the function:def _create_examples(self, lines, set_type): examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, i) text_a = line[3] text_b = line[4] ...
[ "Creates examples for the training and dev sets." ]
Please provide a description of the function:def get_train_examples(self, data_dir): return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
[ "See base class." ]
Please provide a description of the function:def get_dev_examples(self, data_dir): return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched")
[ "See base class." ]
Please provide a description of the function:def top_k_logits(logits, k): if k == 0: return logits else: values = torch.topk(logits, k)[0] batch_mins = values[:, -1].view(-1, 1).expand_as(logits) return torch.where(logits < batch_mins, torch.ones_like(logits) * -1e10, logits...
[ "\n Masks everything but the k top entries as -infinity (1e10).\n Used to mask logits such that e^-infinity -> 0 won't contribute to the\n sum of the denominator.\n " ]
Please provide a description of the function:def load_tf_weights_in_bert(model, tf_checkpoint_path): try: import re import numpy as np import tensorflow as tf except ImportError: print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "...
[ " Load tf checkpoints in a pytorch model\n " ]
Please provide a description of the function:def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): state_dict = kwargs.get('state_dict', None) kwargs.pop('state_dict', None) cache_dir = kwargs.get('cache_dir', None) kwargs.pop('cache_dir', None) fro...
[ "\n Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected ...
Please provide a description of the function:def load_tf_weights_in_openai_gpt(model, openai_checkpoint_folder_path): import re import numpy as np print("Loading weights...") names = json.load(open(openai_checkpoint_folder_path + '/parameters_names.json', "r", encoding='utf-8')) shapes = json.l...
[ " Load tf pre-trained weights in a pytorch model (from NumPy arrays here)\n " ]
Please provide a description of the function:def from_dict(cls, json_object): config = OpenAIGPTConfig(vocab_size_or_config_json_file=-1) for key, value in json_object.items(): config.__dict__[key] = value return config
[ "Constructs a `OpenAIGPTConfig` from a Python dictionary of parameters." ]
Please provide a description of the function: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_token...
[]
Please provide a description of the function:def set_num_special_tokens(self, num_special_tokens): self.transformer.set_num_special_tokens(num_special_tokens) self.lm_head.set_embeddings_weights(self.transformer.tokens_embed.weight)
[ " Update input and output embeddings with new embedding matrice\n Make sure we are sharing the embeddings\n " ]
Please provide a description of the function:def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue ...
[ "Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n " ]
Please provide a description of the function:def get_lr(self, step, nowarn=False): if self.t_total < 0: return 1. progress = float(step) / self.t_total ret = self.get_lr_(progress) # warning for exceeding t_total (only active with warmup_linear if not nowarn ...
[ "\n :param step: which of t_total steps we're on\n :param nowarn: set to True to suppress warning regarding training beyond specified 't_total' steps\n :return: learning rate multiplier for current update\n " ]
Please provide a description of the function:def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue ...
[ "Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n " ]
Please provide a description of the function:def whitespace_tokenize(text): text = text.strip() if not text: return [] tokens = text.split() return tokens
[ "Runs basic whitespace cleaning and splitting on a piece of text." ]
Please provide a description of the function:def _is_punctuation(char): 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. if ((c...
[ "Checks whether `chars` is a punctuation character." ]
Please provide a description of the function:def convert_tokens_to_ids(self, tokens): ids = [] for token in tokens: ids.append(self.vocab[token]) if len(ids) > self.max_len: logger.warning( "Token indices sequence length is longer than the specifi...
[ "Converts a sequence of tokens into ids using the vocab." ]
Please provide a description of the function:def convert_ids_to_tokens(self, ids): tokens = [] for i in ids: tokens.append(self.ids_to_tokens[i]) return tokens
[ "Converts a sequence of ids in wordpiece tokens using the vocab." ]
Please provide a description of the function:def save_vocabulary(self, vocab_path): 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_index in sorted(...
[ "Save the tokenizer vocabulary to a directory or file." ]
Please provide a description of the function:def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHIVE_MAP: vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP[pretrained_model_name_or_path] if ...
[ "\n Instantiate a PreTrainedBertModel from a pre-trained model file.\n Download and cache the pre-trained model file if needed.\n " ]
Please provide a description of the function:def tokenize(self, 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...
[ "Tokenizes a piece of text." ]
Please provide a description of the function:def _run_strip_accents(self, text): text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": continue output.append(char) ...
[ "Strips accents from a piece of text." ]
Please provide a description of the function:def _tokenize_chinese_chars(self, text): output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") ...
[ "Adds whitespace around any CJK character." ]
Please provide a description of the function:def _is_chinese_char(self, cp): # 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 NOT all Japanes...
[ "Checks whether CP is the codepoint of a CJK character." ]
Please provide a description of the function:def tokenize(self, text): output_tokens = [] for token in whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) cont...
[ "Tokenizes a piece of text into its word pieces.\n\n This uses a greedy longest-match-first algorithm to perform tokenization\n using the given vocabulary.\n\n For example:\n input = \"unaffable\"\n output = [\"un\", \"##aff\", \"##able\"]\n\n Args:\n text: A s...
Please provide a description of the function:def load_rocstories_dataset(dataset_path): 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((' '.join(line[1:5]), line[5], line[...
[ " Output a list of tuples(story, 1st continuation, 2nd continuation, label) " ]
Please provide a description of the function:def pre_process_datasets(encoded_datasets, input_len, cap_length, start_token, delimiter_token, clf_token): tensor_datasets = [] for dataset in encoded_datasets: n_batch = len(dataset) input_ids = np.zeros((n_batch, 2, input_len), dtype=np.int64)...
[ " Pre-process datasets containing lists of tuples(story, 1st continuation, 2nd continuation, label)\n\n To Transformer inputs of shape (n_batch, n_alternative, length) comprising for each batch, continuation:\n input_ids[batch, alternative, :] = [start_token] + story[:cap_length] + [delimiter_token] +...
Please provide a description of the function:def random_word(tokens, tokenizer): output_label = [] for i, token in enumerate(tokens): prob = random.random() # mask token with 15% probability if prob < 0.15: prob /= 0.15 # 80% randomly change token to mask t...
[ "\n Masking some random tokens for Language Model task with probabilities as in the original BERT paper.\n :param tokens: list of str, tokenized sentence.\n :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)\n :return: (list of str, list of int), masked tokens and relate...
Please provide a description of the function:def convert_example_to_features(example, max_seq_length, tokenizer): tokens_a = example.tokens_a tokens_b = example.tokens_b # Modifies `tokens_a` and `tokens_b` in place so that the total # length is less than the specified length. # Account for [CL...
[ "\n Convert a raw sample (pair of sentences as tokenized strings) into a proper training sample with\n IDs, LM labels, input_mask, CLS and SEP tokens etc.\n :param example: InputExample, containing sentence input as strings and is_next label\n :param max_seq_length: int, maximum length of sequence.\n ...
Please provide a description of the function:def random_sent(self, index): t1, t2 = self.get_corpus_line(index) if random.random() > 0.5: label = 0 else: t2 = self.get_random_line() label = 1 assert len(t1) > 0 assert len(t2) > 0 ...
[ "\n Get one sample from corpus consisting of two sentences. With prob. 50% these are two subsequent sentences\n from one doc. With 50% the second sentence will be a random one from another doc.\n :param index: int, index of sample.\n :return: (str, str, int), sentence 1, sentence 2, isNe...
Please provide a description of the function:def get_corpus_line(self, item): t1 = "" t2 = "" assert item < self.corpus_lines if self.on_memory: sample = self.sample_to_doc[item] t1 = self.all_docs[sample["doc_id"]][sample["line"]] t2 = self.a...
[ "\n Get one sample from corpus consisting of a pair of two subsequent lines from the same doc.\n :param item: int, index of sample.\n :return: (str, str), two subsequent sentences from corpus\n " ]
Please provide a description of the function:def get_random_line(self): # Similar to original tf repo: This outer loop should rarely go for more than one iteration for large # corpora. However, just to be careful, we try to make sure that # the random document is not the same as the doc...
[ "\n Get random line from another document for nextSentence task.\n :return: str, content of one line\n " ]
Please provide a description of the function:def get_next_line(self): 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 == "": self.current_random_doc ...
[ " Gets next line of random_file and starts over when reaching end of file" ]
Please provide a description of the function:def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_list): cand_indices = [] for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[SEP]": continue cand_indices.append(i) num_to...
[ "Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but\n with several refactors to clean it up and remove a lot of unnecessary variables." ]
Please provide a description of the function:def create_instances_from_document( doc_database, doc_idx, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_list): document = doc_database[doc_idx] # Account for [CLS], [SEP], [SEP] max_num_tokens = max_seq_lengt...
[ "This code is mostly a duplicate of the equivalent function from Google BERT's repo.\n However, we make some changes and improvements. Sampling is improved and no longer requires a loop in this function.\n Also, documents are sampled proportionally to the number of sentences they contain, which means each sen...
Please provide a description of the function:def sample_logits(embedding, bias, labels, inputs, sampler): true_log_probs, samp_log_probs, neg_samples = sampler.sample(labels) n_sample = neg_samples.size(0) b1, b2 = labels.size(0), labels.size(1) all_ids = torch.cat([labels.view(-1), neg_samples]) ...
[ "\n embedding: an nn.Embedding layer\n bias: [n_vocab]\n labels: [b1, b2]\n inputs: [b1, b2, n_emb]\n sampler: you may use a LogUniformSampler\n Return\n logits: [b1, b2, 1 + n_sample]\n " ]
Please provide a description of the function: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...
[]
Please provide a description of the function:def log_prob(self, hidden): r if self.n_clusters == 0: logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0]) return F.log_softmax(logit, dim=-...
[ " Computes log probabilities for all :math:`n\\_classes`\n From: https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.py\n Args:\n hidden (Tensor): a minibatch of examples\n Returns:\n log-probabilities of for each class :math:`c`\n in range ...
Please provide a description of the function:def sample(self, labels): # neg_samples = torch.empty(0).long() n_sample = self.n_sample n_tries = 2 * n_sample with torch.no_grad(): neg_samples = torch.multinomial(self.dist, n_tries, replacement=True).unique() ...
[ "\n labels: [b1, b2]\n Return\n true_log_probs: [b1, b2]\n samp_log_probs: [n_sample]\n neg_samples: [n_sample]\n " ]
Please provide a description of the function:def build_tf_to_pytorch_map(model, config): tf_to_pt_map = {} if hasattr(model, 'transformer'): # We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax tf_to_pt_map.update({ "transformer/adaptive_softmax/...
[ " A map of modules from TF to PyTorch.\n This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible.\n " ]
Please provide a description of the function:def load_tf_weights_in_transfo_xl(model, config, tf_path): 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 " "h...
[ " Load tf checkpoints in a pytorch model\n " ]
Please provide a description of the function:def init_weights(self, m): 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 no...
[ " Initialize the weights.\n " ]
Please provide a description of the function:def from_pretrained(cls, pretrained_model_name_or_path, state_dict=None, cache_dir=None, from_tf=False, *inputs, **kwargs): if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP: archive_file = PRETRAINED_MODEL_...
[ "\n Instantiate a TransfoXLPreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load sele...
Please provide a description of the function:def forward(self, input_ids, mems=None): # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library # so we transpose here from shape [bsz, len] to shape [len, bsz] input_ids = input_ids.trans...
[ " Params:\n input_ids :: [bsz, len]\n mems :: optional mems from previous forwar passes (or init_mems)\n list (num layers) of mem states at the entry of each layer\n shape :: [self.config.mem_len, bsz, self.config.d_model]\n ...
Please provide a description of the function:def tie_weights(self): # sampled softmax if self.sample_softmax > 0: if self.config.tie_weight: self.out_layer.weight = self.transformer.word_emb.weight # adaptive softmax (including standard softmax) else:...
[ " Run this to be sure output and input (adaptive) softmax weights are tied " ]
Please provide a description of the function:def forward(self, input_ids, target=None, mems=None): bsz = input_ids.size(0) tgt_len = input_ids.size(1) last_hidden, new_mems = self.transformer(input_ids, mems) pred_hid = last_hidden[:, -tgt_len:] if self.sample_softmax ...
[ " Params:\n input_ids :: [bsz, len]\n target :: [bsz, len]\n Returns:\n tuple(softmax_output, new_mems) where:\n new_mems: list (num layers) of hidden states at the entry of each layer\n shape :: [mem_len, bsz, self.co...
Please provide a description of the function:def to_offset(freq): if freq is None: return None if isinstance(freq, DateOffset): return freq if isinstance(freq, tuple): name = freq[0] stride = freq[1] if isinstance(stride, str): name, stride = stride...
[ "\n Return DateOffset object from string or tuple representation\n or datetime.timedelta object\n\n Parameters\n ----------\n freq : str, tuple, datetime.timedelta, DateOffset or None\n\n Returns\n -------\n DateOffset\n None if freq is None.\n\n Raises\n ------\n ValueError\...
Please provide a description of the function:def get_offset(name): if name not in libfreqs._dont_uppercase: name = name.upper() name = libfreqs._lite_rule_alias.get(name, name) name = libfreqs._lite_rule_alias.get(name.lower(), name) else: name = libfreqs._lite_rule_alias.ge...
[ "\n Return DateOffset object associated with rule name\n\n Examples\n --------\n get_offset('EOM') --> BMonthEnd(1)\n " ]
Please provide a description of the function:def infer_freq(index, warn=True): import pandas as pd if isinstance(index, ABCSeries): values = index._values if not (is_datetime64_dtype(values) or is_timedelta64_dtype(values) or values.dtype == object): ...
[ "\n Infer the most likely frequency given the input index. If the frequency is\n uncertain, a warning will be printed.\n\n Parameters\n ----------\n index : DatetimeIndex or TimedeltaIndex\n if passed a Series will use the values of the series (NOT THE INDEX)\n warn : boolean, default True\n\...
Please provide a description of the function:def get_freq(self): if not self.is_monotonic or not self.index._is_unique: return None delta = self.deltas[0] if _is_multiple(delta, _ONE_DAY): return self._infer_daily_rule() # Business hourly, maybe. 17: on...
[ "\n Find the appropriate frequency string to describe the inferred\n frequency of self.values\n\n Returns\n -------\n str or None\n " ]
Please provide a description of the function:def load(fh, encoding=None, is_verbose=False): try: fh.seek(0) if encoding is not None: up = Unpickler(fh, encoding=encoding) else: up = Unpickler(fh) up.is_verbose = is_verbose return up.load() e...
[ "load a pickle, with a provided encoding\n\n if compat is True:\n fake the old class hierarchy\n if it works, then return the new type objects\n\n Parameters\n ----------\n fh : a filelike object\n encoding : an optional encoding\n is_verbose : show exception output\n " ]
Please provide a description of the function:def _new_Index(cls, d): # required for backward compat, because PI can't be instantiated with # ordinals through __new__ GH #13277 if issubclass(cls, ABCPeriodIndex): from pandas.core.indexes.period import _new_PeriodIndex return _new_PeriodI...
[ "\n This is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__.\n " ]
Please provide a description of the function:def ensure_index_from_sequences(sequences, names=None): from .multi import MultiIndex if len(sequences) == 1: if names is not None: names = names[0] return Index(sequences[0], name=names) else: return MultiIndex.from_arra...
[ "\n Construct an index from sequences of data.\n\n A single sequence returns an Index. Many sequences returns a\n MultiIndex.\n\n Parameters\n ----------\n sequences : sequence of sequences\n names : sequence of str\n\n Returns\n -------\n index : Index or MultiIndex\n\n Examples\n ...
Please provide a description of the function:def ensure_index(index_like, copy=False): if isinstance(index_like, Index): if copy: index_like = index_like.copy() return index_like if hasattr(index_like, 'name'): return Index(index_like, name=index_like.name, copy=copy) ...
[ "\n Ensure that we have an index from some index-like object.\n\n Parameters\n ----------\n index : sequence\n An Index or other sequence\n copy : bool\n\n Returns\n -------\n index : Index or MultiIndex\n\n Examples\n --------\n >>> ensure_index(['a', 'b'])\n Index(['a', ...
Please provide a description of the function:def _trim_front(strings): trimmed = strings while len(strings) > 0 and all(x[0] == ' ' for x in trimmed): trimmed = [x[1:] for x in trimmed] return trimmed
[ "\n Trims zeros and decimal points.\n " ]
Please provide a description of the function:def _simple_new(cls, values, name=None, dtype=None, **kwargs): if not hasattr(values, 'dtype'): if (values is None or not len(values)) and dtype is not None: values = np.empty(0, dtype=dtype) else: valu...
[ "\n We require that we have a dtype compat for the values. If we are passed\n a non-dtype compat, then coerce using the constructor.\n\n Must be careful not to recurse.\n " ]
Please provide a description of the function:def _shallow_copy_with_infer(self, values, **kwargs): attributes = self._get_attributes_dict() attributes.update(kwargs) attributes['copy'] = False if not len(values) and 'dtype' not in kwargs: attributes['dtype'] = self.d...
[ "\n Create a new Index inferring the class with passed value, don't copy\n the data, use the same object attributes with passed in attributes\n taking precedence.\n\n *this is an internal non-public method*\n\n Parameters\n ----------\n values : the values to create ...
Please provide a description of the function:def is_(self, other): # use something other than None to be clearer return self._id is getattr( other, '_id', Ellipsis) and self._id is not None
[ "\n More flexible, faster check like ``is`` but that works through views.\n\n Note: this is *not* the same as ``Index.identical()``, which checks\n that metadata is also the same.\n\n Parameters\n ----------\n other : object\n other object to compare against.\n\n...
Please provide a description of the function:def _assert_take_fillable(self, values, indices, allow_fill=True, fill_value=None, na_value=np.nan): indices = ensure_platform_int(indices) # only fill if we are passing a non-None fill_value if allow_fill and f...
[ "\n Internal method to handle NA filling of take.\n " ]
Please provide a description of the function:def _format_data(self, name=None): # 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 is...
[ "\n Return the formatted data as a unicode string.\n " ]
Please provide a description of the function:def format(self, name=False, formatter=None, **kwargs): header = [] if name: header.append(pprint_thing(self.name, escape_chars=('\t', '\r', '\n')) if self.name is not None ...
[ "\n Render a string representation of the Index.\n " ]
Please provide a description of the function:def to_native_types(self, slicer=None, **kwargs): values = self if slicer is not None: values = values[slicer] return values._format_native_types(**kwargs)
[ "\n Format specified values of `self` and return them.\n\n Parameters\n ----------\n slicer : int, array-like\n An indexer into `self` that specifies which values\n are used in the formatting process.\n kwargs : dict\n Options for specifying how th...
Please provide a description of the function:def _format_native_types(self, na_rep='', quoting=None, **kwargs): mask = isna(self) if not self.is_object() and not quoting: values = np.asarray(self).astype(str) else: values = np.array(self, dtype=object, copy=True)...
[ "\n Actually format specific types of the index.\n " ]
Please provide a description of the function:def _summary(self, name=None): if len(self) > 0: head = self[0] if hasattr(head, 'format') and not isinstance(head, str): head = head.format() tail = self[-1] if hasattr(tail, 'format') and not ...
[ "\n Return a summarized representation.\n\n Parameters\n ----------\n name : str\n name to use in the summary representation\n\n Returns\n -------\n String with a summarized representation of the index\n " ]
Please provide a description of the function:def summary(self, name=None): warnings.warn("'summary' is deprecated and will be removed in a " "future version.", FutureWarning, stacklevel=2) return self._summary(name)
[ "\n Return a summarized representation.\n\n .. deprecated:: 0.23.0\n " ]
Please provide a description of the function:def to_series(self, index=None, name=None): from pandas import Series if index is None: index = self._shallow_copy() if name is None: name = self.name return Series(self.values.copy(), index=index, name=name...
[ "\n Create a Series with both index and values equal to the index keys\n useful with map for returning an indexer based on an index.\n\n Parameters\n ----------\n index : Index, optional\n index of resulting Series. If None, defaults to original index\n name : st...
Please provide a description of the function:def to_frame(self, index=True, name=None): from pandas import DataFrame if name is None: name = self.name or 0 result = DataFrame({name: self._values.copy()}) if index: result.index = self return resu...
[ "\n Create a DataFrame with a column containing the Index.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n index : boolean, default True\n Set the index of the returned DataFrame as the original Index.\n\n name : object, default None\n The p...
Please provide a description of the function:def _validate_names(self, name=None, names=None, deep=False): from copy import deepcopy if names is not None and name is not None: raise TypeError("Can only provide one of `names` and `name`") elif names is None and name is None: ...
[ "\n Handles the quirks of having a singular 'name' parameter for general\n Index and plural 'names' parameter for MultiIndex.\n " ]
Please provide a description of the function:def _set_names(self, values, level=None): if not is_list_like(values): raise ValueError('Names must be a list-like') if len(values) != 1: raise ValueError('Length of new names must be 1, got %d' % ...
[ "\n Set new names on index. Each name has to be a hashable type.\n\n Parameters\n ----------\n values : str or sequence\n name(s) to set\n level : int, level name, or sequence of int/level names (default None)\n If the index is a MultiIndex (hierarchical), le...
Please provide a description of the function:def set_names(self, names, level=None, inplace=False): if level is not None and not isinstance(self, ABCMultiIndex): raise ValueError('Level must be None for non-MultiIndex') if level is not None and not is_list_like(level) and is_list_...
[ "\n Set Index or MultiIndex name.\n\n Able to set new names partially and by level.\n\n Parameters\n ----------\n names : label or list of label\n Name(s) to set.\n level : int, label or list of int or label, optional\n If the index is a MultiIndex, le...
Please provide a description of the function:def rename(self, name, inplace=False): return self.set_names([name], inplace=inplace)
[ "\n Alter Index or MultiIndex name.\n\n Able to set new names without level. Defaults to returning new index.\n Length of names must match number of levels in MultiIndex.\n\n Parameters\n ----------\n name : label or list of labels\n Name(s) to set.\n inpl...
Please provide a description of the function:def _validate_index_level(self, level): if isinstance(level, int): if level < 0 and level != -1: raise IndexError("Too many levels: Index has only 1 level," " %d is not a valid level number" % (lev...
[ "\n Validate index level.\n\n For single-level Index getting level number is a no-op, but some\n verification must be done like in MultiIndex.\n\n " ]
Please provide a description of the function:def sortlevel(self, level=None, ascending=True, sort_remaining=None): return self.sort_values(return_indexer=True, ascending=ascending)
[ "\n For internal compatibility with with the Index API.\n\n Sort the Index. This is for compat with MultiIndex\n\n Parameters\n ----------\n ascending : boolean, default True\n False to sort in descending order\n\n level, sort_remaining are compat parameters\n\n ...
Please provide a description of the function:def droplevel(self, level=0): if not isinstance(level, (tuple, list)): level = [level] levnums = sorted(self._get_level_number(lev) for lev in level)[::-1] if len(level) == 0: return self if len(level) >= sel...
[ "\n Return index with requested level(s) removed.\n\n If resulting index has only 1 level left, the result will be\n of Index type, not MultiIndex.\n\n .. versionadded:: 0.23.1 (support for non-MultiIndex)\n\n Parameters\n ----------\n level : int, str, or list-like,...
Please provide a description of the function:def _isnan(self): 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) ...
[ "\n Return if each value is NaN.\n " ]
Please provide a description of the function:def get_duplicates(self): warnings.warn("'get_duplicates' is deprecated and will be removed in " "a future release. You can use " "idx[idx.duplicated()].unique() instead", FutureWarning, stack...
[ "\n Extract duplicated index elements.\n\n .. deprecated:: 0.23.0\n Use idx[idx.duplicated()].unique() instead\n\n Returns a sorted list of index elements which appear more than once in\n the index.\n\n Returns\n -------\n array-like\n List of d...
Please provide a description of the function:def _get_unique_index(self, dropna=False): if self.is_unique and not dropna: return self values = self.values if not self.is_unique: values = self.unique() if dropna: try: if self...
[ "\n Returns an index containing unique values.\n\n Parameters\n ----------\n dropna : bool\n If True, NaN values are dropped.\n\n Returns\n -------\n uniques : index\n " ]
Please provide a description of the function:def _get_reconciled_name_object(self, other): name = get_op_result_name(self, other) if self.name != name: return self._shallow_copy(name=name) return self
[ "\n If the result of a set operation will be self,\n return self, unless the name changes, in which\n case make a shallow copy of self.\n " ]
Please provide a description of the function:def union(self, other, sort=None): self._validate_sort_keyword(sort) self._assert_can_do_setop(other) other = ensure_index(other) if len(other) == 0 or self.equals(other): return self._get_reconciled_name_object(other) ...
[ "\n Form the union of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : bool or None, default None\n Whether to sort the resulting Index.\n\n * None : Sort the result, except when\n\n 1. `self` and `other` are ...
Please provide a description of the function:def intersection(self, other, sort=False): self._validate_sort_keyword(sort) self._assert_can_do_setop(other) other = ensure_index(other) if self.equals(other): return self._get_reconciled_name_object(other) if n...
[ "\n Form the intersection of two Index objects.\n\n This returns a new Index with elements common to the index and `other`.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default False\n Whether to sort the resulting index.\n\n ...
Please provide a description of the function:def difference(self, other, sort=None): self._validate_sort_keyword(sort) self._assert_can_do_setop(other) if self.equals(other): # pass an empty np.ndarray with the appropriate dtype return self._shallow_copy(self._d...
[ "\n Return a new Index with elements from the index that are not in\n `other`.\n\n This is the set difference of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default None\n Whether to sort the resulti...
Please provide a description of the function:def symmetric_difference(self, other, result_name=None, sort=None): self._validate_sort_keyword(sort) self._assert_can_do_setop(other) other, result_name_update = self._convert_can_do_setop(other) if result_name is None: r...
[ "\n Compute the symmetric difference of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n result_name : str\n sort : False or None, default None\n Whether to sort the resulting index. By default, the\n values are attempted ...
Please provide a description of the function:def _get_fill_indexer_searchsorted(self, target, method, limit=None): if limit is not None: raise ValueError('limit argument for %r method only well-defined ' 'if index and target are monotonic' % method) sid...
[ "\n Fallback pad/backfill get_indexer that works for monotonic decreasing\n indexes and non-monotonic targets.\n " ]
Please provide a description of the function:def _get_nearest_indexer(self, target, limit, tolerance): left_indexer = self.get_indexer(target, 'pad', limit=limit) right_indexer = self.get_indexer(target, 'backfill', limit=limit) target = np.asarray(target) left_distances = abs(...
[ "\n Get the indexer for the nearest index labels; requires an index with\n values that can be subtracted from each other (e.g., not strings or\n tuples).\n " ]
Please provide a description of the function:def _convert_listlike_indexer(self, keyarr, kind=None): if isinstance(keyarr, Index): keyarr = self._convert_index_indexer(keyarr) else: keyarr = self._convert_arr_indexer(keyarr) indexer = self._convert_list_indexer(...
[ "\n Parameters\n ----------\n keyarr : list-like\n Indexer to convert.\n\n Returns\n -------\n indexer : numpy.ndarray or None\n Return an ndarray or None if cannot convert.\n keyarr : numpy.ndarray\n Return tuple-safe keys.\n ...
Please provide a description of the function:def _invalid_indexer(self, form, key): raise TypeError("cannot do {form} indexing on {klass} with these " "indexers [{key}] of {kind}".format( form=form, klass=type(self), key=key, ...
[ "\n Consistent invalid indexer message.\n " ]