partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
OpenAIGPTConfig.from_dict
Constructs a `OpenAIGPTConfig` from a Python dictionary of parameters.
pytorch_pretrained_bert/modeling_openai.py
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
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
[ "Constructs", "a", "OpenAIGPTConfig", "from", "a", "Python", "dictionary", "of", "parameters", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_openai.py#L200-L205
[ "def", "from_dict", "(", "cls", ",", "json_object", ")", ":", "config", "=", "OpenAIGPTConfig", "(", "vocab_size_or_config_json_file", "=", "-", "1", ")", "for", "key", ",", "value", "in", "json_object", ".", "items", "(", ")", ":", "config", ".", "__dict_...
b832d5bb8a6dfc5965015b828e577677eace601e
train
OpenAIGPTModel.set_num_special_tokens
Update input embeddings with new embedding matrice if needed
pytorch_pretrained_bert/modeling_openai.py
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...
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", "embeddings", "with", "new", "embedding", "matrice", "if", "needed" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_openai.py#L605-L617
[ "def", "set_num_special_tokens", "(", "self", ",", "num_special_tokens", ")", ":", "if", "self", ".", "config", ".", "n_special", "==", "num_special_tokens", ":", "return", "# Update config", "self", ".", "config", ".", "n_special", "=", "num_special_tokens", "# B...
b832d5bb8a6dfc5965015b828e577677eace601e
train
OpenAIGPTLMHeadModel.set_num_special_tokens
Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings
pytorch_pretrained_bert/modeling_openai.py
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...
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...
[ "Update", "input", "and", "output", "embeddings", "with", "new", "embedding", "matrice", "Make", "sure", "we", "are", "sharing", "the", "embeddings" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_openai.py#L710-L715
[ "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", ".",...
b832d5bb8a6dfc5965015b828e577677eace601e
train
OpenAIAdam.step
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
pytorch_pretrained_bert/optimization_openai.py
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...
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...
[ "Performs", "a", "single", "optimization", "step", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/optimization_openai.py#L70-L127
[ "def", "step", "(", "self", ",", "closure", "=", "None", ")", ":", "loss", "=", "None", "if", "closure", "is", "not", "None", ":", "loss", "=", "closure", "(", ")", "for", "group", "in", "self", ".", "param_groups", ":", "for", "p", "in", "group", ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
_LRSchedule.get_lr
: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
pytorch_pretrained_bert/optimization.py
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 < ...
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 < ...
[ ":", "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...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/optimization.py#L53-L70
[ "def", "get_lr", "(", "self", ",", "step", ",", "nowarn", "=", "False", ")", ":", "if", "self", ".", "t_total", "<", "0", ":", "return", "1.", "progress", "=", "float", "(", "step", ")", "/", "self", ".", "t_total", "ret", "=", "self", ".", "get_...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BertAdam.step
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
pytorch_pretrained_bert/optimization.py
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...
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...
[ "Performs", "a", "single", "optimization", "step", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/optimization.py#L237-L302
[ "def", "step", "(", "self", ",", "closure", "=", "None", ")", ":", "loss", "=", "None", "if", "closure", "is", "not", "None", ":", "loss", "=", "closure", "(", ")", "for", "group", "in", "self", ".", "param_groups", ":", "for", "p", "in", "group", ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
whitespace_tokenize
Runs basic whitespace cleaning and splitting on a piece of text.
pytorch_pretrained_bert/tokenization.py
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
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
[ "Runs", "basic", "whitespace", "cleaning", "and", "splitting", "on", "a", "piece", "of", "text", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L65-L71
[ "def", "whitespace_tokenize", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "not", "text", ":", "return", "[", "]", "tokens", "=", "text", ".", "split", "(", ")", "return", "tokens" ]
b832d5bb8a6dfc5965015b828e577677eace601e
train
_is_punctuation
Checks whether `chars` is a punctuation character.
pytorch_pretrained_bert/tokenization.py
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....
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....
[ "Checks", "whether", "chars", "is", "a", "punctuation", "character", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L402-L415
[ "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", "# ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BertTokenizer.convert_tokens_to_ids
Converts a sequence of tokens into ids using the vocab.
pytorch_pretrained_bert/tokenization.py
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 ...
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", "tokens", "into", "ids", "using", "the", "vocab", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L117-L128
[ "def", "convert_tokens_to_ids", "(", "self", ",", "tokens", ")", ":", "ids", "=", "[", "]", "for", "token", "in", "tokens", ":", "ids", ".", "append", "(", "self", ".", "vocab", "[", "token", "]", ")", "if", "len", "(", "ids", ")", ">", "self", "...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BertTokenizer.convert_ids_to_tokens
Converts a sequence of ids in wordpiece tokens using the vocab.
pytorch_pretrained_bert/tokenization.py
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
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
[ "Converts", "a", "sequence", "of", "ids", "in", "wordpiece", "tokens", "using", "the", "vocab", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L130-L135
[ "def", "convert_ids_to_tokens", "(", "self", ",", "ids", ")", ":", "tokens", "=", "[", "]", "for", "i", "in", "ids", ":", "tokens", ".", "append", "(", "self", ".", "ids_to_tokens", "[", "i", "]", ")", "return", "tokens" ]
b832d5bb8a6dfc5965015b828e577677eace601e
train
BertTokenizer.save_vocabulary
Save the tokenizer vocabulary to a directory or file.
pytorch_pretrained_bert/tokenization.py
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...
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...
[ "Save", "the", "tokenizer", "vocabulary", "to", "a", "directory", "or", "file", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L137-L150
[ "def", "save_vocabulary", "(", "self", ",", "vocab_path", ")", ":", "index", "=", "0", "if", "os", ".", "path", ".", "isdir", "(", "vocab_path", ")", ":", "vocab_file", "=", "os", ".", "path", ".", "join", "(", "vocab_path", ",", "VOCAB_NAME", ")", "...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BertTokenizer.from_pretrained
Instantiate a PreTrainedBertModel from a pre-trained model file. Download and cache the pre-trained model file if needed.
pytorch_pretrained_bert/tokenization.py
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...
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...
[ "Instantiate", "a", "PreTrainedBertModel", "from", "a", "pre", "-", "trained", "model", "file", ".", "Download", "and", "cache", "the", "pre", "-", "trained", "model", "file", "if", "needed", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L153-L198
[ "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", "=", "...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BasicTokenizer.tokenize
Tokenizes a piece of text.
pytorch_pretrained_bert/tokenization.py
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...
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...
[ "Tokenizes", "a", "piece", "of", "text", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L215-L234
[ "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...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BasicTokenizer._run_strip_accents
Strips accents from a piece of text.
pytorch_pretrained_bert/tokenization.py
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) ...
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) ...
[ "Strips", "accents", "from", "a", "piece", "of", "text", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L236-L245
[ "def", "_run_strip_accents", "(", "self", ",", "text", ")", ":", "text", "=", "unicodedata", ".", "normalize", "(", "\"NFD\"", ",", "text", ")", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cat", "=", "unicodedata", ".", "category", "(",...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BasicTokenizer._tokenize_chinese_chars
Adds whitespace around any CJK character.
pytorch_pretrained_bert/tokenization.py
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(" ") ...
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(" ") ...
[ "Adds", "whitespace", "around", "any", "CJK", "character", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L269-L280
[ "def", "_tokenize_chinese_chars", "(", "self", ",", "text", ")", ":", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cp", "=", "ord", "(", "char", ")", "if", "self", ".", "_is_chinese_char", "(", "cp", ")", ":", "output", ".", "append", ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BasicTokenizer._is_chinese_char
Checks whether CP is the codepoint of a CJK character.
pytorch_pretrained_bert/tokenization.py
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 ...
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 ...
[ "Checks", "whether", "CP", "is", "the", "codepoint", "of", "a", "CJK", "character", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L282-L302
[ "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 Japanese and Korean charac...
b832d5bb8a6dfc5965015b828e577677eace601e
train
WordpieceTokenizer.tokenize
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: text: A single token or whitespa...
pytorch_pretrained_bert/tokenization.py
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: ...
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: ...
[ "Tokenizes", "a", "piece", "of", "text", "into", "its", "word", "pieces", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/tokenization.py#L326-L375
[ "def", "tokenize", "(", "self", ",", "text", ")", ":", "output_tokens", "=", "[", "]", "for", "token", "in", "whitespace_tokenize", "(", "text", ")", ":", "chars", "=", "list", "(", "token", ")", "if", "len", "(", "chars", ")", ">", "self", ".", "m...
b832d5bb8a6dfc5965015b828e577677eace601e
train
load_rocstories_dataset
Output a list of tuples(story, 1st continuation, 2nd continuation, label)
examples/run_openai_gpt.py
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(...
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(...
[ "Output", "a", "list", "of", "tuples", "(", "story", "1st", "continuation", "2nd", "continuation", "label", ")" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_openai_gpt.py#L56-L64
[ "def", "load_rocstories_dataset", "(", "dataset_path", ")", ":", "with", "open", "(", "dataset_path", ",", "encoding", "=", "'utf_8'", ")", "as", "f", ":", "f", "=", "csv", ".", "reader", "(", "f", ")", "output", "=", "[", "]", "next", "(", "f", ")",...
b832d5bb8a6dfc5965015b828e577677eace601e
train
pre_process_datasets
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, continuation: input_ids[batch, alternative, :] = [start_token] + story[:cap_length] + [delimiter_token] + cont1[:c...
examples/run_openai_gpt.py
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...
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...
[ "Pre", "-", "process", "datasets", "containing", "lists", "of", "tuples", "(", "story", "1st", "continuation", "2nd", "continuation", "label", ")" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/run_openai_gpt.py#L66-L91
[ "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", "=", ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
random_word
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 L...
examples/lm_finetuning/simple_lm_finetuning.py
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...
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...
[ "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"...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/simple_lm_finetuning.py#L267-L303
[ "def", "random_word", "(", "tokens", ",", "tokenizer", ")", ":", "output_label", "=", "[", "]", "for", "i", ",", "token", "in", "enumerate", "(", "tokens", ")", ":", "prob", "=", "random", ".", "random", "(", ")", "# mask token with 15% probability", "if",...
b832d5bb8a6dfc5965015b828e577677eace601e
train
convert_example_to_features
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 tokeniz...
examples/lm_finetuning/simple_lm_finetuning.py
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...
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...
[ "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"...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/simple_lm_finetuning.py#L306-L397
[ "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...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BERTDataset.random_sent
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
examples/lm_finetuning/simple_lm_finetuning.py
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...
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", "two", "sentences", ".", "With", "prob", ".", "50%", "these", "are", "two", "subsequent", "sentences", "from", "one", "doc", ".", "With", "50%", "the", "second", "sentence", "will", "be", "a", ...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/simple_lm_finetuning.py#L141-L157
[ "def", "random_sent", "(", "self", ",", "index", ")", ":", "t1", ",", "t2", "=", "self", ".", "get_corpus_line", "(", "index", ")", "if", "random", ".", "random", "(", ")", ">", "0.5", ":", "label", "=", "0", "else", ":", "t2", "=", "self", ".", ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BERTDataset.get_corpus_line
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
examples/lm_finetuning/simple_lm_finetuning.py
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...
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", "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", "...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/simple_lm_finetuning.py#L159-L194
[ "def", "get_corpus_line", "(", "self", ",", "item", ")", ":", "t1", "=", "\"\"", "t2", "=", "\"\"", "assert", "item", "<", "self", ".", "corpus_lines", "if", "self", ".", "on_memory", ":", "sample", "=", "self", ".", "sample_to_doc", "[", "item", "]", ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BERTDataset.get_random_line
Get random line from another document for nextSentence task. :return: str, content of one line
examples/lm_finetuning/simple_lm_finetuning.py
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, ...
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, ...
[ "Get", "random", "line", "from", "another", "document", "for", "nextSentence", "task", ".", ":", "return", ":", "str", "content", "of", "one", "line" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/simple_lm_finetuning.py#L196-L217
[ "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 document we're processing.", "...
b832d5bb8a6dfc5965015b828e577677eace601e
train
BERTDataset.get_next_line
Gets next line of random_file and starts over when reaching end of file
examples/lm_finetuning/simple_lm_finetuning.py
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 == "": ...
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 == "": ...
[ "Gets", "next", "line", "of", "random_file", "and", "starts", "over", "when", "reaching", "end", "of", "file" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/simple_lm_finetuning.py#L219-L231
[ "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", "==", "\"\...
b832d5bb8a6dfc5965015b828e577677eace601e
train
create_masked_lm_predictions
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.
examples/lm_finetuning/pregenerate_training_data.py
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 = [] ...
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 = [] ...
[ "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",...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/pregenerate_training_data.py#L102-L131
[ "def", "create_masked_lm_predictions", "(", "tokens", ",", "masked_lm_prob", ",", "max_predictions_per_seq", ",", "vocab_list", ")", ":", "cand_indices", "=", "[", "]", "for", "(", "i", ",", "token", ")", "in", "enumerate", "(", "tokens", ")", ":", "if", "to...
b832d5bb8a6dfc5965015b828e577677eace601e
train
create_instances_from_document
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 ...
examples/lm_finetuning/pregenerate_training_data.py
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...
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...
[ "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", ...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/lm_finetuning/pregenerate_training_data.py#L134-L229
[ "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", "]", "# Acc...
b832d5bb8a6dfc5965015b828e577677eace601e
train
sample_logits
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]
pytorch_pretrained_bert/modeling_transfo_xl_utilities.py
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...
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...
[ "embedding", ":", "an", "nn", ".", "Embedding", "layer", "bias", ":", "[", "n_vocab", "]", "labels", ":", "[", "b1", "b2", "]", "inputs", ":", "[", "b1", "b2", "n_emb", "]", "sampler", ":", "you", "may", "use", "a", "LogUniformSampler", "Return", "lo...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl_utilities.py#L302-L333
[ "def", "sample_logits", "(", "embedding", ",", "bias", ",", "labels", ",", "inputs", ",", "sampler", ")", ":", "true_log_probs", ",", "samp_log_probs", ",", "neg_samples", "=", "sampler", ".", "sample", "(", "labels", ")", "n_sample", "=", "neg_samples", "."...
b832d5bb8a6dfc5965015b828e577677eace601e
train
ProjectedAdaptiveLogSoftmax.forward
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 vocabula...
pytorch_pretrained_bert/modeling_transfo_xl_utilities.py
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: ...
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: ...
[ "Params", ":", "hidden", "::", "[", "len", "*", "bsz", "x", "d_proj", "]", "target", "::", "[", "len", "*", "bsz", "]", "Return", ":", "if", "target", "is", "None", ":", "out", "::", "[", "len", "*", "bsz", "]", "Negative", "log", "likelihood", "...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl_utilities.py#L92-L195
[ "def", "forward", "(", "self", ",", "hidden", ",", "target", "=", "None", ",", "keep_order", "=", "False", ")", ":", "if", "target", "is", "not", "None", ":", "target", "=", "target", ".", "view", "(", "-", "1", ")", "if", "hidden", ".", "size", ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
ProjectedAdaptiveLogSoftmax.log_prob
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...
pytorch_pretrained_bert/modeling_transfo_xl_utilities.py
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...
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...
[ "r", "Computes", "log", "probabilities", "for", "all", ":", "math", ":", "n", "\\", "_classes", "From", ":", "https", ":", "//", "github", ".", "com", "/", "pytorch", "/", "pytorch", "/", "blob", "/", "master", "/", "torch", "/", "nn", "/", "modules"...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl_utilities.py#L198-L257
[ "def", "log_prob", "(", "self", ",", "hidden", ")", ":", "if", "self", ".", "n_clusters", "==", "0", ":", "logit", "=", "self", ".", "_compute_logit", "(", "hidden", ",", "self", ".", "out_layers", "[", "0", "]", ".", "weight", ",", "self", ".", "o...
b832d5bb8a6dfc5965015b828e577677eace601e
train
LogUniformSampler.sample
labels: [b1, b2] Return true_log_probs: [b1, b2] samp_log_probs: [n_sample] neg_samples: [n_sample]
pytorch_pretrained_bert/modeling_transfo_xl_utilities.py
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 ...
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 ...
[ "labels", ":", "[", "b1", "b2", "]", "Return", "true_log_probs", ":", "[", "b1", "b2", "]", "samp_log_probs", ":", "[", "n_sample", "]", "neg_samples", ":", "[", "n_sample", "]" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl_utilities.py#L281-L300
[ "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", ".", ...
b832d5bb8a6dfc5965015b828e577677eace601e
train
build_tf_to_pytorch_map
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.
pytorch_pretrained_bert/modeling_transfo_xl.py
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...
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...
[ "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", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl.py#L56-L126
[ "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", "...
b832d5bb8a6dfc5965015b828e577677eace601e
train
load_tf_weights_in_transfo_xl
Load tf checkpoints in a pytorch model
pytorch_pretrained_bert/modeling_transfo_xl.py
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 " ...
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 " ...
[ "Load", "tf", "checkpoints", "in", "a", "pytorch", "model" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl.py#L128-L181
[ "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, requi...
b832d5bb8a6dfc5965015b828e577677eace601e
train
TransfoXLPreTrainedModel.init_weights
Initialize the weights.
pytorch_pretrained_bert/modeling_transfo_xl.py
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...
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...
[ "Initialize", "the", "weights", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl.py#L846-L885
[ "def", "init_weights", "(", "self", ",", "m", ")", ":", "classname", "=", "m", ".", "__class__", ".", "__name__", "if", "classname", ".", "find", "(", "'Linear'", ")", "!=", "-", "1", ":", "if", "hasattr", "(", "m", ",", "'weight'", ")", "and", "m"...
b832d5bb8a6dfc5965015b828e577677eace601e
train
TransfoXLPreTrainedModel.from_pretrained
Instantiate a TransfoXLPreTrainedModel from a pre-trained model file or a pytorch state dict. Download and cache the pre-trained model file if needed. Params: pretrained_model_name_or_path: either: - a str with the name of a pre-trained model to load selected in the list of:...
pytorch_pretrained_bert/modeling_transfo_xl.py
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...
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...
[ "Instantiate", "a", "TransfoXLPreTrainedModel", "from", "a", "pre", "-", "trained", "model", "file", "or", "a", "pytorch", "state", "dict", ".", "Download", "and", "cache", "the", "pre", "-", "trained", "model", "file", "if", "needed", "." ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl.py#L891-L986
[ "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...
b832d5bb8a6dfc5965015b828e577677eace601e
train
TransfoXLModel.forward
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 t...
pytorch_pretrained_bert/modeling_transfo_xl.py
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,...
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,...
[ "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...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl.py#L1239-L1263
[ "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", "=", "...
b832d5bb8a6dfc5965015b828e577677eace601e
train
TransfoXLLMHeadModel.tie_weights
Run this to be sure output and input (adaptive) softmax weights are tied
pytorch_pretrained_bert/modeling_transfo_xl.py
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...
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...
[ "Run", "this", "to", "be", "sure", "output", "and", "input", "(", "adaptive", ")", "softmax", "weights", "are", "tied" ]
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl.py#L1331-L1347
[ "def", "tie_weights", "(", "self", ")", ":", "# sampled softmax", "if", "self", ".", "sample_softmax", ">", "0", ":", "if", "self", ".", "config", ".", "tie_weight", ":", "self", ".", "out_layer", ".", "weight", "=", "self", ".", "transformer", ".", "wor...
b832d5bb8a6dfc5965015b828e577677eace601e
train
TransfoXLLMHeadModel.forward
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...
pytorch_pretrained_bert/modeling_transfo_xl.py
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 ...
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 ...
[ "Params", ":", "input_ids", "::", "[", "bsz", "len", "]", "target", "::", "[", "bsz", "len", "]", "Returns", ":", "tuple", "(", "softmax_output", "new_mems", ")", "where", ":", "new_mems", ":", "list", "(", "num", "layers", ")", "of", "hidden", "states...
huggingface/pytorch-pretrained-BERT
python
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_transfo_xl.py#L1355-L1387
[ "def", "forward", "(", "self", ",", "input_ids", ",", "target", "=", "None", ",", "mems", "=", "None", ")", ":", "bsz", "=", "input_ids", ".", "size", "(", "0", ")", "tgt_len", "=", "input_ids", ".", "size", "(", "1", ")", "last_hidden", ",", "new_...
b832d5bb8a6dfc5965015b828e577677eace601e
train
to_offset
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 ------ ValueError If freq is an inv...
pandas/tseries/frequencies.py
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...
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", "from", "string", "or", "tuple", "representation", "or", "datetime", ".", "timedelta", "object" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/frequencies.py#L57-L164
[ "def", "to_offset", "(", "freq", ")", ":", "if", "freq", "is", "None", ":", "return", "None", "if", "isinstance", "(", "freq", ",", "DateOffset", ")", ":", "return", "freq", "if", "isinstance", "(", "freq", ",", "tuple", ")", ":", "name", "=", "freq"...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
get_offset
Return DateOffset object associated with rule name Examples -------- get_offset('EOM') --> BMonthEnd(1)
pandas/tseries/frequencies.py
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...
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...
[ "Return", "DateOffset", "object", "associated", "with", "rule", "name" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/frequencies.py#L167-L195
[ "def", "get_offset", "(", "name", ")", ":", "if", "name", "not", "in", "libfreqs", ".", "_dont_uppercase", ":", "name", "=", "name", ".", "upper", "(", ")", "name", "=", "libfreqs", ".", "_lite_rule_alias", ".", "get", "(", "name", ",", "name", ")", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
infer_freq
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) warn : boolean, default True Returns ---...
pandas/tseries/frequencies.py
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...
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...
[ "Infer", "the", "most", "likely", "frequency", "given", "the", "input", "index", ".", "If", "the", "frequency", "is", "uncertain", "a", "warning", "will", "be", "printed", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/frequencies.py#L202-L252
[ "def", "infer_freq", "(", "index", ",", "warn", "=", "True", ")", ":", "import", "pandas", "as", "pd", "if", "isinstance", "(", "index", ",", "ABCSeries", ")", ":", "values", "=", "index", ".", "_values", "if", "not", "(", "is_datetime64_dtype", "(", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_FrequencyInferer.get_freq
Find the appropriate frequency string to describe the inferred frequency of self.values Returns ------- str or None
pandas/tseries/frequencies.py
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] ...
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] ...
[ "Find", "the", "appropriate", "frequency", "string", "to", "describe", "the", "inferred", "frequency", "of", "self", ".", "values" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/frequencies.py#L294-L337
[ "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", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
load
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 : show exception output
pandas/compat/pickle_compat.py
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...
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...
[ "load", "a", "pickle", "with", "a", "provided", "encoding" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/compat/pickle_compat.py#L189-L213
[ "def", "load", "(", "fh", ",", "encoding", "=", "None", ",", "is_verbose", "=", "False", ")", ":", "try", ":", "fh", ".", "seek", "(", "0", ")", "if", "encoding", "is", "not", "None", ":", "up", "=", "Unpickler", "(", "fh", ",", "encoding", "=", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_new_Index
This is called upon unpickling, rather than the default which doesn't have arguments and breaks __new__.
pandas/core/indexes/base.py
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...
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...
[ "This", "is", "called", "upon", "unpickling", "rather", "than", "the", "default", "which", "doesn", "t", "have", "arguments", "and", "breaks", "__new__", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L153-L163
[ "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", ".", "in...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
ensure_index_from_sequences
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 ------- index : Index or MultiIndex Examples -------- >>> ensure...
pandas/core/indexes/base.py
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...
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...
[ "Construct", "an", "index", "from", "sequences", "of", "data", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5277-L5315
[ "def", "ensure_index_from_sequences", "(", "sequences", ",", "names", "=", "None", ")", ":", "from", ".", "multi", "import", "MultiIndex", "if", "len", "(", "sequences", ")", "==", "1", ":", "if", "names", "is", "not", "None", ":", "names", "=", "names",...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
ensure_index
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(['a', 'b']) Index(['a', 'b'], dtype='object') ...
pandas/core/indexes/base.py
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(...
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(...
[ "Ensure", "that", "we", "have", "an", "index", "from", "some", "index", "-", "like", "object", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5318-L5378
[ "def", "ensure_index", "(", "index_like", ",", "copy", "=", "False", ")", ":", "if", "isinstance", "(", "index_like", ",", "Index", ")", ":", "if", "copy", ":", "index_like", "=", "index_like", ".", "copy", "(", ")", "return", "index_like", "if", "hasatt...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_trim_front
Trims zeros and decimal points.
pandas/core/indexes/base.py
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
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
[ "Trims", "zeros", "and", "decimal", "points", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5393-L5400
[ "def", "_trim_front", "(", "strings", ")", ":", "trimmed", "=", "strings", "while", "len", "(", "strings", ")", ">", "0", "and", "all", "(", "x", "[", "0", "]", "==", "' '", "for", "x", "in", "trimmed", ")", ":", "trimmed", "=", "[", "x", "[", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._simple_new
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.
pandas/core/indexes/base.py
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'): ...
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'): ...
[ "We", "require", "that", "we", "have", "a", "dtype", "compat", "for", "the", "values", ".", "If", "we", "are", "passed", "a", "non", "-", "dtype", "compat", "then", "coerce", "using", "the", "constructor", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L506-L539
[ "def", "_simple_new", "(", "cls", ",", "values", ",", "name", "=", "None", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "values", ",", "'dtype'", ")", ":", "if", "(", "values", "is", "None", "or", "no...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._shallow_copy_with_infer
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 ---------- values : the values to create the new Index, optional...
pandas/core/indexes/base.py
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 ...
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 ...
[ "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", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L585-L608
[ "def", "_shallow_copy_with_infer", "(", "self", ",", "values", ",", "*", "*", "kwargs", ")", ":", "attributes", "=", "self", ".", "_get_attributes_dict", "(", ")", "attributes", ".", "update", "(", "kwargs", ")", "attributes", "[", "'copy'", "]", "=", "Fal...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.is_
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 compare against. Returns -...
pandas/core/indexes/base.py
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...
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...
[ "More", "flexible", "faster", "check", "like", "is", "but", "that", "works", "through", "views", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L614-L632
[ "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" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._assert_take_fillable
Internal method to handle NA filling of take.
pandas/core/indexes/base.py
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 ...
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 ...
[ "Internal", "method", "to", "handle", "NA", "filling", "of", "take", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L803-L822
[ "def", "_assert_take_fillable", "(", "self", ",", "values", ",", "indices", ",", "allow_fill", "=", "True", ",", "fill_value", "=", "None", ",", "na_value", "=", "np", ".", "nan", ")", ":", "indices", "=", "ensure_platform_int", "(", "indices", ")", "# onl...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._format_data
Return the formatted data as a unicode string.
pandas/core/indexes/base.py
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 ...
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 ...
[ "Return", "the", "formatted", "data", "as", "a", "unicode", "string", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L958-L969
[ "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", ".", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.format
Render a string representation of the Index.
pandas/core/indexes/base.py
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 ...
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 ...
[ "Render", "a", "string", "representation", "of", "the", "Index", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L981-L994
[ "def", "format", "(", "self", ",", "name", "=", "False", ",", "formatter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "header", "=", "[", "]", "if", "name", ":", "header", ".", "append", "(", "pprint_thing", "(", "self", ".", "name", ",", "e...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.to_native_types
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 : dict Options for specifying how the values should be form...
pandas/core/indexes/base.py
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 :...
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 :...
[ "Format", "specified", "values", "of", "self", "and", "return", "them", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1022-L1046
[ "def", "to_native_types", "(", "self", ",", "slicer", "=", "None", ",", "*", "*", "kwargs", ")", ":", "values", "=", "self", "if", "slicer", "is", "not", "None", ":", "values", "=", "values", "[", "slicer", "]", "return", "values", ".", "_format_native...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._format_native_types
Actually format specific types of the index.
pandas/core/indexes/base.py
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...
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...
[ "Actually", "format", "specific", "types", "of", "the", "index", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1048-L1059
[ "def", "_format_native_types", "(", "self", ",", "na_rep", "=", "''", ",", "quoting", "=", "None", ",", "*", "*", "kwargs", ")", ":", "mask", "=", "isna", "(", "self", ")", "if", "not", "self", ".", "is_object", "(", ")", "and", "not", "quoting", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._summary
Return a summarized representation. Parameters ---------- name : str name to use in the summary representation Returns ------- String with a summarized representation of the index
pandas/core/indexes/base.py
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(...
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", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1061-L1088
[ "def", "_summary", "(", "self", ",", "name", "=", "None", ")", ":", "if", "len", "(", "self", ")", ">", "0", ":", "head", "=", "self", "[", "0", "]", "if", "hasattr", "(", "head", ",", "'format'", ")", "and", "not", "isinstance", "(", "head", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.summary
Return a summarized representation. .. deprecated:: 0.23.0
pandas/core/indexes/base.py
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)
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)
[ "Return", "a", "summarized", "representation", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1090-L1098
[ "def", "summary", "(", "self", ",", "name", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"'summary' is deprecated and will be removed in a \"", "\"future version.\"", ",", "FutureWarning", ",", "stacklevel", "=", "2", ")", "return", "self", ".", "_summar...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.to_series
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, defaults to original index name : string, optional ...
pandas/core/indexes/base.py
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...
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", "Series", "with", "both", "index", "and", "values", "equal", "to", "the", "index", "keys", "useful", "with", "map", "for", "returning", "an", "indexer", "based", "on", "an", "index", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1123-L1148
[ "def", "to_series", "(", "self", ",", "index", "=", "None", ",", "name", "=", "None", ")", ":", "from", "pandas", "import", "Series", "if", "index", "is", "None", ":", "index", "=", "self", ".", "_shallow_copy", "(", ")", "if", "name", "is", "None", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.to_frame
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 : object, default None The passed name should substit...
pandas/core/indexes/base.py
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 : ...
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 : ...
[ "Create", "a", "DataFrame", "with", "a", "column", "containing", "the", "Index", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1150-L1209
[ "def", "to_frame", "(", "self", ",", "index", "=", "True", ",", "name", "=", "None", ")", ":", "from", "pandas", "import", "DataFrame", "if", "name", "is", "None", ":", "name", "=", "self", ".", "name", "or", "0", "result", "=", "DataFrame", "(", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._validate_names
Handles the quirks of having a singular 'name' parameter for general Index and plural 'names' parameter for MultiIndex.
pandas/core/indexes/base.py
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...
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...
[ "Handles", "the", "quirks", "of", "having", "a", "singular", "name", "parameter", "for", "general", "Index", "and", "plural", "names", "parameter", "for", "MultiIndex", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1214-L1231
[ "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...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._set_names
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 index is a MultiIndex (hierarchical), level(s) to set (None ...
pandas/core/indexes/base.py
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 ...
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", "new", "names", "on", "index", ".", "Each", "name", "has", "to", "be", "a", "hashable", "type", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1236-L1264
[ "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", ":", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.set_names
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, optional If the index is a MultiIndex, level(s) to set (None for ...
pandas/core/indexes/base.py
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...
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...
[ "Set", "Index", "or", "MultiIndex", "name", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1268-L1340
[ "def", "set_names", "(", "self", ",", "names", ",", "level", "=", "None", ",", "inplace", "=", "False", ")", ":", "if", "level", "is", "not", "None", "and", "not", "isinstance", "(", "self", ",", "ABCMultiIndex", ")", ":", "raise", "ValueError", "(", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.rename
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 Name(s) to set. inplace : boolean, default F...
pandas/core/indexes/base.py
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 ...
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 ...
[ "Alter", "Index", "or", "MultiIndex", "name", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1342-L1387
[ "def", "rename", "(", "self", ",", "name", ",", "inplace", "=", "False", ")", ":", "return", "self", ".", "set_names", "(", "[", "name", "]", ",", "inplace", "=", "inplace", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._validate_index_level
Validate index level. For single-level Index getting level number is a no-op, but some verification must be done like in MultiIndex.
pandas/core/indexes/base.py
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...
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...
[ "Validate", "index", "level", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1402-L1420
[ "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,...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.sortlevel
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 descending order level, sort_remaining are compat parameters Returns ---...
pandas/core/indexes/base.py
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...
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...
[ "For", "internal", "compatibility", "with", "with", "the", "Index", "API", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1426-L1443
[ "def", "sortlevel", "(", "self", ",", "level", "=", "None", ",", "ascending", "=", "True", ",", "sort_remaining", "=", "None", ")", ":", "return", "self", ".", "sort_values", "(", "return_indexer", "=", "True", ",", "ascending", "=", "ascending", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.droplevel
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 : int, str, or list-like, default 0 I...
pandas/core/indexes/base.py
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...
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", "index", "with", "requested", "level", "(", "s", ")", "removed", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1487-L1541
[ "def", "droplevel", "(", "self", ",", "level", "=", "0", ")", ":", "if", "not", "isinstance", "(", "level", ",", "(", "tuple", ",", "list", ")", ")", ":", "level", "=", "[", "level", "]", "levnums", "=", "sorted", "(", "self", ".", "_get_level_numb...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._isnan
Return if each value is NaN.
pandas/core/indexes/base.py
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) ...
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) ...
[ "Return", "if", "each", "value", "is", "NaN", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1782-L1792
[ "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", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.get_duplicates
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 List of duplicated indexes. ...
pandas/core/indexes/base.py
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 ...
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 ...
[ "Extract", "duplicated", "index", "elements", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2105-L2162
[ "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", ",", "stacklevel", "=", "2", ")"...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._get_unique_index
Returns an index containing unique values. Parameters ---------- dropna : bool If True, NaN values are dropped. Returns ------- uniques : index
pandas/core/indexes/base.py
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...
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...
[ "Returns", "an", "index", "containing", "unique", "values", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2164-L2192
[ "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", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._get_reconciled_name_object
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.
pandas/core/indexes/base.py
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...
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...
[ "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", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2234-L2243
[ "def", "_get_reconciled_name_object", "(", "self", ",", "other", ")", ":", "name", "=", "get_op_result_name", "(", "self", ",", "other", ")", "if", "self", ".", "name", "!=", "name", ":", "return", "self", ".", "_shallow_copy", "(", "name", "=", "name", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.union
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 1. `self` and `other` are equal. 2. `...
pandas/core/indexes/base.py
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 ...
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", "union", "of", "two", "Index", "objects", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2250-L2348
[ "def", "union", "(", "self", ",", "other", ",", "sort", "=", "None", ")", ":", "self", ".", "_validate_sort_keyword", "(", "sort", ")", "self", ".", "_assert_can_do_setop", "(", "other", ")", "other", "=", "ensure_index", "(", "other", ")", "if", "len", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.intersection
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 Whether to sort the resulting index. * False : do n...
pandas/core/indexes/base.py
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...
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...
[ "Form", "the", "intersection", "of", "two", "Index", "objects", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2353-L2439
[ "def", "intersection", "(", "self", ",", "other", ",", "sort", "=", "False", ")", ":", "self", ".", "_validate_sort_keyword", "(", "sort", ")", "self", ".", "_assert_can_do_setop", "(", "other", ")", "other", "=", "ensure_index", "(", "other", ")", "if", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.difference
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 Whether to sort the resulting index. By default, th...
pandas/core/indexes/base.py
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 ...
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 ...
[ "Return", "a", "new", "Index", "with", "elements", "from", "the", "index", "that", "are", "not", "in", "other", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2441-L2504
[ "def", "difference", "(", "self", ",", "other", ",", "sort", "=", "None", ")", ":", "self", ".", "_validate_sort_keyword", "(", "sort", ")", "self", ".", "_assert_can_do_setop", "(", "other", ")", "if", "self", ".", "equals", "(", "other", ")", ":", "#...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.symmetric_difference
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 resulting index. By default, the values are attempted to be sorted, but any T...
pandas/core/indexes/base.py
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...
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...
[ "Compute", "the", "symmetric", "difference", "of", "two", "Index", "objects", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2506-L2584
[ "def", "symmetric_difference", "(", "self", ",", "other", ",", "result_name", "=", "None", ",", "sort", "=", "None", ")", ":", "self", ".", "_validate_sort_keyword", "(", "sort", ")", "self", ".", "_assert_can_do_setop", "(", "other", ")", "other", ",", "r...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._get_fill_indexer_searchsorted
Fallback pad/backfill get_indexer that works for monotonic decreasing indexes and non-monotonic targets.
pandas/core/indexes/base.py
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...
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...
[ "Fallback", "pad", "/", "backfill", "get_indexer", "that", "works", "for", "monotonic", "decreasing", "indexes", "and", "non", "-", "monotonic", "targets", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2777-L2805
[ "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...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._get_nearest_indexer
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).
pandas/core/indexes/base.py
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) ...
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) ...
[ "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", ")", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2807-L2826
[ "def", "_get_nearest_indexer", "(", "self", ",", "target", ",", "limit", ",", "tolerance", ")", ":", "left_indexer", "=", "self", ".", "get_indexer", "(", "target", ",", "'pad'", ",", "limit", "=", "limit", ")", "right_indexer", "=", "self", ".", "get_inde...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._convert_listlike_indexer
Parameters ---------- keyarr : list-like Indexer to convert. Returns ------- indexer : numpy.ndarray or None Return an ndarray or None if cannot convert. keyarr : numpy.ndarray Return tuple-safe keys.
pandas/core/indexes/base.py
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...
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...
[ "Parameters", "----------", "keyarr", ":", "list", "-", "like", "Indexer", "to", "convert", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2961-L2981
[ "def", "_convert_listlike_indexer", "(", "self", ",", "keyarr", ",", "kind", "=", "None", ")", ":", "if", "isinstance", "(", "keyarr", ",", "Index", ")", ":", "keyarr", "=", "self", ".", "_convert_index_indexer", "(", "keyarr", ")", "else", ":", "keyarr", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._invalid_indexer
Consistent invalid indexer message.
pandas/core/indexes/base.py
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, ...
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, ...
[ "Consistent", "invalid", "indexer", "message", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3057-L3064
[ "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", "(", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.reindex
Create index with target's values (move/add/delete values as necessary). Parameters ---------- target : an iterable Returns ------- new_index : pd.Index Resulting index. indexer : np.ndarray or None Indices of output values in ori...
pandas/core/indexes/base.py
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...
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", "index", "with", "target", "s", "values", "(", "move", "/", "add", "/", "delete", "values", "as", "necessary", ")", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3086-L3142
[ "def", "reindex", "(", "self", ",", "target", ",", "method", "=", "None", ",", "level", "=", "None", ",", "limit", "=", "None", ",", "tolerance", "=", "None", ")", ":", "# GH6552: preserve names when reindexing to non-named target", "# (i.e. neither Index nor Series...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._reindex_non_unique
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_index : pd.Index Resulting index. indexer...
pandas/core/indexes/base.py
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...
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...
[ "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", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3144-L3201
[ "def", "_reindex_non_unique", "(", "self", ",", "target", ")", ":", "target", "=", "ensure_index", "(", "target", ")", "indexer", ",", "missing", "=", "self", ".", "get_indexer_non_unique", "(", "target", ")", "check", "=", "indexer", "!=", "-", "1", "new_...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._join_level
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 ```keep_order == True```, the order of the data indexed by the MultiIndex will not be changed; otherwise, it will tie ou...
pandas/core/indexes/base.py
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...
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...
[ "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...
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3420-L3550
[ "def", "_join_level", "(", "self", ",", "other", ",", "level", ",", "how", "=", "'left'", ",", "return_indexers", "=", "False", ",", "keep_order", "=", "True", ")", ":", "from", ".", "multi", "import", "MultiIndex", "def", "_get_leaf_sorter", "(", "labels"...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._try_convert_to_int_index
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. Returns ------- int_index : data converted to either an Int64Index...
pandas/core/indexes/base.py
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...
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...
[ "Attempt", "to", "convert", "an", "array", "of", "data", "into", "an", "integer", "index", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3746-L3786
[ "def", "_try_convert_to_int_index", "(", "cls", ",", "data", ",", "copy", ",", "name", ",", "dtype", ")", ":", "from", ".", "numeric", "import", "Int64Index", ",", "UInt64Index", "if", "not", "is_unsigned_integer_dtype", "(", "dtype", ")", ":", "# skip int64 c...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._coerce_to_ndarray
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.
pandas/core/indexes/base.py
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...
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...
[ "Coerces", "data", "to", "ndarray", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3800-L3821
[ "def", "_coerce_to_ndarray", "(", "cls", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "(", "np", ".", "ndarray", ",", "Index", ")", ")", ":", "if", "data", "is", "None", "or", "is_scalar", "(", "data", ")", ":", "cls", ".", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._coerce_scalar_to_index
We need to coerce a scalar to a compat for our index type. Parameters ---------- item : scalar item to coerce
pandas/core/indexes/base.py
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...
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...
[ "We", "need", "to", "coerce", "a", "scalar", "to", "a", "compat", "for", "our", "index", "type", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3823-L3838
[ "def", "_coerce_scalar_to_index", "(", "self", ",", "item", ")", ":", "dtype", "=", "self", ".", "dtype", "if", "self", ".", "_is_numeric_dtype", "and", "isna", "(", "item", ")", ":", "# We can't coerce to the numeric dtype of \"self\" (unless", "# it's float) if ther...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._assert_can_do_op
Check value is valid for scalar op.
pandas/core/indexes/base.py
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__))
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__))
[ "Check", "value", "is", "valid", "for", "scalar", "op", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3852-L3858
[ "def", "_assert_can_do_op", "(", "self", ",", "value", ")", ":", "if", "not", "is_scalar", "(", "value", ")", ":", "msg", "=", "\"'value' must be a scalar, passed: {0}\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "type", "(", "value", ")", ".", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index._can_hold_identifiers_and_holds_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. https://github.com/pandas-dev/pandas/i...
pandas/core/indexes/base.py
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...
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...
[ "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", ")", ".", "...
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3968-L3979
[ "def", "_can_hold_identifiers_and_holds_name", "(", "self", ",", "name", ")", ":", "if", "self", ".", "is_object", "(", ")", "or", "self", ".", "is_categorical", "(", ")", ":", "return", "name", "in", "self", "return", "False" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.append
Append a collection of Index options together. Parameters ---------- other : Index or list/tuple of indices Returns ------- appended : Index
pandas/core/indexes/base.py
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))...
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))...
[ "Append", "a", "collection", "of", "Index", "options", "together", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3981-L4008
[ "def", "append", "(", "self", ",", "other", ")", ":", "to_concat", "=", "[", "self", "]", "if", "isinstance", "(", "other", ",", "(", "list", ",", "tuple", ")", ")", ":", "to_concat", "=", "to_concat", "+", "list", "(", "other", ")", "else", ":", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.putmask
Return a new Index of the values set with the mask. See Also -------- numpy.ndarray.putmask
pandas/core/indexes/base.py
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....
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....
[ "Return", "a", "new", "Index", "of", "the", "values", "set", "with", "the", "mask", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4025-L4042
[ "def", "putmask", "(", "self", ",", "mask", ",", "value", ")", ":", "values", "=", "self", ".", "values", ".", "copy", "(", ")", "try", ":", "np", ".", "putmask", "(", "values", ",", "mask", ",", "self", ".", "_convert_for_op", "(", "value", ")", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.equals
Determine if two Index objects contain the same elements.
pandas/core/indexes/base.py
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...
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...
[ "Determine", "if", "two", "Index", "objects", "contain", "the", "same", "elements", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4044-L4062
[ "def", "equals", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_", "(", "other", ")", ":", "return", "True", "if", "not", "isinstance", "(", "other", ",", "Index", ")", ":", "return", "False", "if", "is_object_dtype", "(", "self", ")", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.identical
Similar to equals, but check that other comparable attributes are also equal.
pandas/core/indexes/base.py
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 ...
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 ...
[ "Similar", "to", "equals", "but", "check", "that", "other", "comparable", "attributes", "are", "also", "equal", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4064-L4072
[ "def", "identical", "(", "self", ",", "other", ")", ":", "return", "(", "self", ".", "equals", "(", "other", ")", "and", "all", "(", "(", "getattr", "(", "self", ",", "c", ",", "None", ")", "==", "getattr", "(", "other", ",", "c", ",", "None", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.asof
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 ---------- label : object ...
pandas/core/indexes/base.py
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...
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...
[ "Return", "the", "label", "from", "the", "index", "or", "if", "not", "present", "the", "previous", "one", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4074-L4137
[ "def", "asof", "(", "self", ",", "label", ")", ":", "try", ":", "loc", "=", "self", ".", "get_loc", "(", "label", ",", "method", "=", "'pad'", ")", "except", "KeyError", ":", "return", "self", ".", "_na_value", "else", ":", "if", "isinstance", "(", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.asof_locs
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 label is chosen and its index returned. If all ...
pandas/core/indexes/base.py
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...
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...
[ "Find", "the", "locations", "(", "indices", ")", "of", "the", "labels", "from", "the", "index", "for", "every", "entry", "in", "the", "where", "argument", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4139-L4176
[ "def", "asof_locs", "(", "self", ",", "where", ",", "mask", ")", ":", "locs", "=", "self", ".", "values", "[", "mask", "]", ".", "searchsorted", "(", "where", ".", "values", ",", "side", "=", "'right'", ")", "locs", "=", "np", ".", "where", "(", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.sort_values
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 Should the indices that would sort the index be returned. ascendi...
pandas/core/indexes/base.py
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 ...
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", "a", "sorted", "copy", "of", "the", "index", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4178-L4230
[ "def", "sort_values", "(", "self", ",", "return_indexer", "=", "False", ",", "ascending", "=", "True", ")", ":", "_as", "=", "self", ".", "argsort", "(", ")", "if", "not", "ascending", ":", "_as", "=", "_as", "[", ":", ":", "-", "1", "]", "sorted_i...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.argsort
Return the integer indices that would sort the index. Parameters ---------- *args Passed to `numpy.ndarray.argsort`. **kwargs Passed to `numpy.ndarray.argsort`. Returns ------- numpy.ndarray Integer indices that would sort the...
pandas/core/indexes/base.py
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...
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...
[ "Return", "the", "integer", "indices", "that", "would", "sort", "the", "index", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4295-L4333
[ "def", "argsort", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "asi8", "if", "result", "is", "None", ":", "result", "=", "np", ".", "array", "(", "self", ")", "return", "result", ".", "argsort", "(...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.get_value
Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing.
pandas/core/indexes/base.py
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...
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", ".", "Only", "use", "this", "if", "you", "know", "what", "you", "re", "doing", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4335-L4389
[ "def", "get_value", "(", "self", ",", "series", ",", "key", ")", ":", "# if we have something that is Index-like, then", "# use this, e.g. DatetimeIndex", "# Things like `Series._get_value` (via .at) pass the EA directly here.", "s", "=", "getattr", "(", "series", ",", "'_value...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.set_value
Fast lookup of value from 1-dimensional ndarray. Notes ----- Only use this if you know what you're doing.
pandas/core/indexes/base.py
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),...
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),...
[ "Fast", "lookup", "of", "value", "from", "1", "-", "dimensional", "ndarray", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4391-L4400
[ "def", "set_value", "(", "self", ",", "arr", ",", "key", ",", "value", ")", ":", "self", ".", "_engine", ".", "set_value", "(", "com", ".", "values_from_object", "(", "arr", ")", ",", "com", ".", "values_from_object", "(", "key", ")", ",", "value", "...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.get_indexer_for
Guaranteed return of an indexer even when non-unique. This dispatches to get_indexer or get_indexer_nonunique as appropriate.
pandas/core/indexes/base.py
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, _ ...
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, _ ...
[ "Guaranteed", "return", "of", "an", "indexer", "even", "when", "non", "-", "unique", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4440-L4450
[ "def", "get_indexer_for", "(", "self", ",", "target", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "is_unique", ":", "return", "self", ".", "get_indexer", "(", "target", ",", "*", "*", "kwargs", ")", "indexer", ",", "_", "=", "self", ".", ...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.groupby
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}
pandas/core/indexes/base.py
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} """ ...
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} """ ...
[ "Group", "the", "index", "labels", "by", "a", "given", "array", "of", "values", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4462-L4487
[ "def", "groupby", "(", "self", ",", "values", ")", ":", "# TODO: if we are a MultiIndex, we can do better", "# that converting to tuples", "if", "isinstance", "(", "values", ",", "ABCMultiIndex", ")", ":", "values", "=", "values", ".", "values", "values", "=", "ensu...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.map
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 values, without passing them to the mapping co...
pandas/core/indexes/base.py
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...
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...
[ "Map", "values", "using", "input", "correspondence", "(", "a", "dict", "Series", "or", "function", ")", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4489-L4530
[ "def", "map", "(", "self", ",", "mapper", ",", "na_action", "=", "None", ")", ":", "from", ".", "multi", "import", "MultiIndex", "new_values", "=", "super", "(", ")", ".", "_map_values", "(", "mapper", ",", "na_action", "=", "na_action", ")", "attributes...
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
Index.isin
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. Parameters ---------- values : set or list-li...
pandas/core/indexes/base.py
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...
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...
[ "Return", "a", "boolean", "array", "where", "the", "index", "values", "are", "in", "values", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4532-L4618
[ "def", "isin", "(", "self", ",", "values", ",", "level", "=", "None", ")", ":", "if", "level", "is", "not", "None", ":", "self", ".", "_validate_index_level", "(", "level", ")", "return", "algos", ".", "isin", "(", "self", ",", "values", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037