id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
19,400
pandas-dev/pandas
pandas/core/indexes/base.py
Index.to_series
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, defaults to original index name : string, optional name of resulting Series. If None, defaults to name of original index Returns ------- Series : dtype will be based on the type of the Index values. """ from pandas import Series if index is None: index = self._shallow_copy() if name is None: name = self.name return Series(self.values.copy(), index=index, name=name)
python
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, defaults to original index name : string, optional name of resulting Series. If None, defaults to name of original index Returns ------- Series : dtype will be based on the type of the Index values. """ from pandas import Series if index is None: index = self._shallow_copy() if name is None: name = self.name return Series(self.values.copy(), index=index, name=name)
[ "def", "to_series", "(", "self", ",", "index", "=", "None", ",", "name", "=", "None", ")", ":", "from", "pandas", "import", "Series", "if", "index", "is", "None", ":", "index", "=", "self", ".", "_shallow_copy", "(", ")", "if", "name", "is", "None", ":", "name", "=", "self", ".", "name", "return", "Series", "(", "self", ".", "values", ".", "copy", "(", ")", ",", "index", "=", "index", ",", "name", "=", "name", ")" ]
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 name of resulting Series. If None, defaults to name of original index Returns ------- Series : dtype will be based on the type of the Index values.
[ "Create", "a", "Series", "with", "both", "index", "and", "values", "equal", "to", "the", "index", "keys", "useful", "with", "map", "for", "returning", "an", "indexer", "based", "on", "an", "index", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1123-L1148
19,401
pandas-dev/pandas
pandas/core/indexes/base.py
Index.to_frame
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 : object, default None The passed name should substitute for the index name (if it has one). Returns ------- DataFrame DataFrame containing the original Index data. See Also -------- Index.to_series : Convert an Index to a Series. Series.to_frame : Convert Series to DataFrame. Examples -------- >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') >>> idx.to_frame() animal animal Ant Ant Bear Bear Cow Cow By default, the original Index is reused. To enforce a new Index: >>> idx.to_frame(index=False) animal 0 Ant 1 Bear 2 Cow To override the name of the resulting column, specify `name`: >>> idx.to_frame(index=False, name='zoo') zoo 0 Ant 1 Bear 2 Cow """ from pandas import DataFrame if name is None: name = self.name or 0 result = DataFrame({name: self._values.copy()}) if index: result.index = self return result
python
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 : object, default None The passed name should substitute for the index name (if it has one). Returns ------- DataFrame DataFrame containing the original Index data. See Also -------- Index.to_series : Convert an Index to a Series. Series.to_frame : Convert Series to DataFrame. Examples -------- >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') >>> idx.to_frame() animal animal Ant Ant Bear Bear Cow Cow By default, the original Index is reused. To enforce a new Index: >>> idx.to_frame(index=False) animal 0 Ant 1 Bear 2 Cow To override the name of the resulting column, specify `name`: >>> idx.to_frame(index=False, name='zoo') zoo 0 Ant 1 Bear 2 Cow """ from pandas import DataFrame if name is None: name = self.name or 0 result = DataFrame({name: self._values.copy()}) if index: result.index = self return result
[ "def", "to_frame", "(", "self", ",", "index", "=", "True", ",", "name", "=", "None", ")", ":", "from", "pandas", "import", "DataFrame", "if", "name", "is", "None", ":", "name", "=", "self", ".", "name", "or", "0", "result", "=", "DataFrame", "(", "{", "name", ":", "self", ".", "_values", ".", "copy", "(", ")", "}", ")", "if", "index", ":", "result", ".", "index", "=", "self", "return", "result" ]
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 substitute for the index name (if it has one). Returns ------- DataFrame DataFrame containing the original Index data. See Also -------- Index.to_series : Convert an Index to a Series. Series.to_frame : Convert Series to DataFrame. Examples -------- >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') >>> idx.to_frame() animal animal Ant Ant Bear Bear Cow Cow By default, the original Index is reused. To enforce a new Index: >>> idx.to_frame(index=False) animal 0 Ant 1 Bear 2 Cow To override the name of the resulting column, specify `name`: >>> idx.to_frame(index=False, name='zoo') zoo 0 Ant 1 Bear 2 Cow
[ "Create", "a", "DataFrame", "with", "a", "column", "containing", "the", "Index", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1150-L1209
19,402
pandas-dev/pandas
pandas/core/indexes/base.py
Index._validate_names
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: raise TypeError("Can only provide one of `names` and `name`") elif names is None and name is None: return deepcopy(self.names) if deep else self.names elif names is not None: if not is_list_like(names): raise TypeError("Must pass list-like as `names`.") return names else: if not is_list_like(name): return [name] return name
python
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: raise TypeError("Can only provide one of `names` and `name`") elif names is None and name is None: return deepcopy(self.names) if deep else self.names elif names is not None: if not is_list_like(names): raise TypeError("Must pass list-like as `names`.") return names else: if not is_list_like(name): return [name] return name
[ "def", "_validate_names", "(", "self", ",", "name", "=", "None", ",", "names", "=", "None", ",", "deep", "=", "False", ")", ":", "from", "copy", "import", "deepcopy", "if", "names", "is", "not", "None", "and", "name", "is", "not", "None", ":", "raise", "TypeError", "(", "\"Can only provide one of `names` and `name`\"", ")", "elif", "names", "is", "None", "and", "name", "is", "None", ":", "return", "deepcopy", "(", "self", ".", "names", ")", "if", "deep", "else", "self", ".", "names", "elif", "names", "is", "not", "None", ":", "if", "not", "is_list_like", "(", "names", ")", ":", "raise", "TypeError", "(", "\"Must pass list-like as `names`.\"", ")", "return", "names", "else", ":", "if", "not", "is_list_like", "(", "name", ")", ":", "return", "[", "name", "]", "return", "name" ]
Handles the quirks of having a singular 'name' parameter for general Index and plural 'names' parameter for MultiIndex.
[ "Handles", "the", "quirks", "of", "having", "a", "singular", "name", "parameter", "for", "general", "Index", "and", "plural", "names", "parameter", "for", "MultiIndex", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1214-L1231
19,403
pandas-dev/pandas
pandas/core/indexes/base.py
Index.set_names
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, optional If the index is a MultiIndex, level(s) to set (None for all levels). Otherwise level must be None. inplace : bool, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns ------- Index The same type as the caller or None if inplace is True. See Also -------- Index.rename : Able to set new names without level. Examples -------- >>> idx = pd.Index([1, 2, 3, 4]) >>> idx Int64Index([1, 2, 3, 4], dtype='int64') >>> idx.set_names('quarter') Int64Index([1, 2, 3, 4], dtype='int64', name='quarter') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]]) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]]) >>> idx.set_names(['kind', 'year'], inplace=True) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['kind', 'year']) >>> idx.set_names('species', level=0) MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['species', 'year']) """ if level is not None and not isinstance(self, ABCMultiIndex): raise ValueError('Level must be None for non-MultiIndex') if level is not None and not is_list_like(level) and is_list_like( names): msg = "Names must be a string when a single level is provided." raise TypeError(msg) if not is_list_like(names) and level is None and self.nlevels > 1: raise TypeError("Must pass list-like as `names`.") if not is_list_like(names): names = [names] if level is not None and not is_list_like(level): level = [level] if inplace: idx = self else: idx = self._shallow_copy() idx._set_names(names, level=level) if not inplace: return idx
python
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, optional If the index is a MultiIndex, level(s) to set (None for all levels). Otherwise level must be None. inplace : bool, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns ------- Index The same type as the caller or None if inplace is True. See Also -------- Index.rename : Able to set new names without level. Examples -------- >>> idx = pd.Index([1, 2, 3, 4]) >>> idx Int64Index([1, 2, 3, 4], dtype='int64') >>> idx.set_names('quarter') Int64Index([1, 2, 3, 4], dtype='int64', name='quarter') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]]) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]]) >>> idx.set_names(['kind', 'year'], inplace=True) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['kind', 'year']) >>> idx.set_names('species', level=0) MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['species', 'year']) """ if level is not None and not isinstance(self, ABCMultiIndex): raise ValueError('Level must be None for non-MultiIndex') if level is not None and not is_list_like(level) and is_list_like( names): msg = "Names must be a string when a single level is provided." raise TypeError(msg) if not is_list_like(names) and level is None and self.nlevels > 1: raise TypeError("Must pass list-like as `names`.") if not is_list_like(names): names = [names] if level is not None and not is_list_like(level): level = [level] if inplace: idx = self else: idx = self._shallow_copy() idx._set_names(names, level=level) if not inplace: return idx
[ "def", "set_names", "(", "self", ",", "names", ",", "level", "=", "None", ",", "inplace", "=", "False", ")", ":", "if", "level", "is", "not", "None", "and", "not", "isinstance", "(", "self", ",", "ABCMultiIndex", ")", ":", "raise", "ValueError", "(", "'Level must be None for non-MultiIndex'", ")", "if", "level", "is", "not", "None", "and", "not", "is_list_like", "(", "level", ")", "and", "is_list_like", "(", "names", ")", ":", "msg", "=", "\"Names must be a string when a single level is provided.\"", "raise", "TypeError", "(", "msg", ")", "if", "not", "is_list_like", "(", "names", ")", "and", "level", "is", "None", "and", "self", ".", "nlevels", ">", "1", ":", "raise", "TypeError", "(", "\"Must pass list-like as `names`.\"", ")", "if", "not", "is_list_like", "(", "names", ")", ":", "names", "=", "[", "names", "]", "if", "level", "is", "not", "None", "and", "not", "is_list_like", "(", "level", ")", ":", "level", "=", "[", "level", "]", "if", "inplace", ":", "idx", "=", "self", "else", ":", "idx", "=", "self", ".", "_shallow_copy", "(", ")", "idx", ".", "_set_names", "(", "names", ",", "level", "=", "level", ")", "if", "not", "inplace", ":", "return", "idx" ]
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 all levels). Otherwise level must be None. inplace : bool, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns ------- Index The same type as the caller or None if inplace is True. See Also -------- Index.rename : Able to set new names without level. Examples -------- >>> idx = pd.Index([1, 2, 3, 4]) >>> idx Int64Index([1, 2, 3, 4], dtype='int64') >>> idx.set_names('quarter') Int64Index([1, 2, 3, 4], dtype='int64', name='quarter') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]]) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]]) >>> idx.set_names(['kind', 'year'], inplace=True) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['kind', 'year']) >>> idx.set_names('species', level=0) MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['species', 'year'])
[ "Set", "Index", "or", "MultiIndex", "name", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1268-L1340
19,404
pandas-dev/pandas
pandas/core/indexes/base.py
Index.rename
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 Name(s) to set. inplace : boolean, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns ------- Index The same type as the caller or None if inplace is True. See Also -------- Index.set_names : Able to set new names partially and by level. Examples -------- >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score') >>> idx.rename('grade') Index(['A', 'C', 'A', 'B'], dtype='object', name='grade') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]], ... names=['kind', 'year']) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['kind', 'year']) >>> idx.rename(['species', 'year']) MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['species', 'year']) >>> idx.rename('species') Traceback (most recent call last): TypeError: Must pass list-like as `names`. """ return self.set_names([name], inplace=inplace)
python
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 Name(s) to set. inplace : boolean, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns ------- Index The same type as the caller or None if inplace is True. See Also -------- Index.set_names : Able to set new names partially and by level. Examples -------- >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score') >>> idx.rename('grade') Index(['A', 'C', 'A', 'B'], dtype='object', name='grade') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]], ... names=['kind', 'year']) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['kind', 'year']) >>> idx.rename(['species', 'year']) MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['species', 'year']) >>> idx.rename('species') Traceback (most recent call last): TypeError: Must pass list-like as `names`. """ return self.set_names([name], inplace=inplace)
[ "def", "rename", "(", "self", ",", "name", ",", "inplace", "=", "False", ")", ":", "return", "self", ".", "set_names", "(", "[", "name", "]", ",", "inplace", "=", "inplace", ")" ]
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 False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns ------- Index The same type as the caller or None if inplace is True. See Also -------- Index.set_names : Able to set new names partially and by level. Examples -------- >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score') >>> idx.rename('grade') Index(['A', 'C', 'A', 'B'], dtype='object', name='grade') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]], ... names=['kind', 'year']) >>> idx MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['kind', 'year']) >>> idx.rename(['species', 'year']) MultiIndex(levels=[['cobra', 'python'], [2018, 2019]], codes=[[1, 1, 0, 0], [0, 1, 0, 1]], names=['species', 'year']) >>> idx.rename('species') Traceback (most recent call last): TypeError: Must pass list-like as `names`.
[ "Alter", "Index", "or", "MultiIndex", "name", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1342-L1387
19,405
pandas-dev/pandas
pandas/core/indexes/base.py
Index._validate_index_level
def _validate_index_level(self, level): """ Validate index level. For single-level Index getting level number is a no-op, but some verification must be done like in MultiIndex. """ if isinstance(level, int): if level < 0 and level != -1: raise IndexError("Too many levels: Index has only 1 level," " %d is not a valid level number" % (level, )) elif level > 0: raise IndexError("Too many levels:" " Index has only 1 level, not %d" % (level + 1)) elif level != self.name: raise KeyError('Level %s must be same as name (%s)' % (level, self.name))
python
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: raise IndexError("Too many levels: Index has only 1 level," " %d is not a valid level number" % (level, )) elif level > 0: raise IndexError("Too many levels:" " Index has only 1 level, not %d" % (level + 1)) elif level != self.name: raise KeyError('Level %s must be same as name (%s)' % (level, self.name))
[ "def", "_validate_index_level", "(", "self", ",", "level", ")", ":", "if", "isinstance", "(", "level", ",", "int", ")", ":", "if", "level", "<", "0", "and", "level", "!=", "-", "1", ":", "raise", "IndexError", "(", "\"Too many levels: Index has only 1 level,\"", "\" %d is not a valid level number\"", "%", "(", "level", ",", ")", ")", "elif", "level", ">", "0", ":", "raise", "IndexError", "(", "\"Too many levels:\"", "\" Index has only 1 level, not %d\"", "%", "(", "level", "+", "1", ")", ")", "elif", "level", "!=", "self", ".", "name", ":", "raise", "KeyError", "(", "'Level %s must be same as name (%s)'", "%", "(", "level", ",", "self", ".", "name", ")", ")" ]
Validate index level. For single-level Index getting level number is a no-op, but some verification must be done like in MultiIndex.
[ "Validate", "index", "level", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1402-L1420
19,406
pandas-dev/pandas
pandas/core/indexes/base.py
Index.sortlevel
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 descending order level, sort_remaining are compat parameters Returns ------- Index """ return self.sort_values(return_indexer=True, ascending=ascending)
python
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 descending order level, sort_remaining are compat parameters Returns ------- Index """ return self.sort_values(return_indexer=True, ascending=ascending)
[ "def", "sortlevel", "(", "self", ",", "level", "=", "None", ",", "ascending", "=", "True", ",", "sort_remaining", "=", "None", ")", ":", "return", "self", ".", "sort_values", "(", "return_indexer", "=", "True", ",", "ascending", "=", "ascending", ")" ]
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 ------- Index
[ "For", "internal", "compatibility", "with", "with", "the", "Index", "API", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1426-L1443
19,407
pandas-dev/pandas
pandas/core/indexes/base.py
Index._isnan
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 values
python
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 values
[ "def", "_isnan", "(", "self", ")", ":", "if", "self", ".", "_can_hold_na", ":", "return", "isna", "(", "self", ")", "else", ":", "# shouldn't reach to this condition by checking hasnans beforehand", "values", "=", "np", ".", "empty", "(", "len", "(", "self", ")", ",", "dtype", "=", "np", ".", "bool_", ")", "values", ".", "fill", "(", "False", ")", "return", "values" ]
Return if each value is NaN.
[ "Return", "if", "each", "value", "is", "NaN", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1782-L1792
19,408
pandas-dev/pandas
pandas/core/indexes/base.py
Index.get_duplicates
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 List of duplicated indexes. See Also -------- Index.duplicated : Return boolean array denoting duplicates. Index.drop_duplicates : Return Index with duplicates removed. Examples -------- Works on different Index of types. >>> pd.Index([1, 2, 2, 3, 3, 3, 4]).get_duplicates() # doctest: +SKIP [2, 3] Note that for a DatetimeIndex, it does not return a list but a new DatetimeIndex: >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03', ... '2018-01-03', '2018-01-04', '2018-01-04'], ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() # doctest: +SKIP DatetimeIndex(['2018-01-03', '2018-01-04'], dtype='datetime64[ns]', freq=None) Sorts duplicated elements even when indexes are unordered. >>> pd.Index([1, 2, 3, 2, 3, 4, 3]).get_duplicates() # doctest: +SKIP [2, 3] Return empty array-like structure when all elements are unique. >>> pd.Index([1, 2, 3, 4]).get_duplicates() # doctest: +SKIP [] >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03'], ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() # doctest: +SKIP DatetimeIndex([], dtype='datetime64[ns]', freq=None) """ 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) return self[self.duplicated()].unique()
python
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 List of duplicated indexes. See Also -------- Index.duplicated : Return boolean array denoting duplicates. Index.drop_duplicates : Return Index with duplicates removed. Examples -------- Works on different Index of types. >>> pd.Index([1, 2, 2, 3, 3, 3, 4]).get_duplicates() # doctest: +SKIP [2, 3] Note that for a DatetimeIndex, it does not return a list but a new DatetimeIndex: >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03', ... '2018-01-03', '2018-01-04', '2018-01-04'], ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() # doctest: +SKIP DatetimeIndex(['2018-01-03', '2018-01-04'], dtype='datetime64[ns]', freq=None) Sorts duplicated elements even when indexes are unordered. >>> pd.Index([1, 2, 3, 2, 3, 4, 3]).get_duplicates() # doctest: +SKIP [2, 3] Return empty array-like structure when all elements are unique. >>> pd.Index([1, 2, 3, 4]).get_duplicates() # doctest: +SKIP [] >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03'], ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() # doctest: +SKIP DatetimeIndex([], dtype='datetime64[ns]', freq=None) """ 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) return self[self.duplicated()].unique()
[ "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", ")", "return", "self", "[", "self", ".", "duplicated", "(", ")", "]", ".", "unique", "(", ")" ]
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. See Also -------- Index.duplicated : Return boolean array denoting duplicates. Index.drop_duplicates : Return Index with duplicates removed. Examples -------- Works on different Index of types. >>> pd.Index([1, 2, 2, 3, 3, 3, 4]).get_duplicates() # doctest: +SKIP [2, 3] Note that for a DatetimeIndex, it does not return a list but a new DatetimeIndex: >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03', ... '2018-01-03', '2018-01-04', '2018-01-04'], ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() # doctest: +SKIP DatetimeIndex(['2018-01-03', '2018-01-04'], dtype='datetime64[ns]', freq=None) Sorts duplicated elements even when indexes are unordered. >>> pd.Index([1, 2, 3, 2, 3, 4, 3]).get_duplicates() # doctest: +SKIP [2, 3] Return empty array-like structure when all elements are unique. >>> pd.Index([1, 2, 3, 4]).get_duplicates() # doctest: +SKIP [] >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03'], ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() # doctest: +SKIP DatetimeIndex([], dtype='datetime64[ns]', freq=None)
[ "Extract", "duplicated", "index", "elements", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2105-L2162
19,409
pandas-dev/pandas
pandas/core/indexes/base.py
Index._get_unique_index
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 dropna: return self values = self.values if not self.is_unique: values = self.unique() if dropna: try: if self.hasnans: values = values[~isna(values)] except NotImplementedError: pass return self._shallow_copy(values)
python
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 dropna: return self values = self.values if not self.is_unique: values = self.unique() if dropna: try: if self.hasnans: values = values[~isna(values)] except NotImplementedError: pass return self._shallow_copy(values)
[ "def", "_get_unique_index", "(", "self", ",", "dropna", "=", "False", ")", ":", "if", "self", ".", "is_unique", "and", "not", "dropna", ":", "return", "self", "values", "=", "self", ".", "values", "if", "not", "self", ".", "is_unique", ":", "values", "=", "self", ".", "unique", "(", ")", "if", "dropna", ":", "try", ":", "if", "self", ".", "hasnans", ":", "values", "=", "values", "[", "~", "isna", "(", "values", ")", "]", "except", "NotImplementedError", ":", "pass", "return", "self", ".", "_shallow_copy", "(", "values", ")" ]
Returns an index containing unique values. Parameters ---------- dropna : bool If True, NaN values are dropped. Returns ------- uniques : index
[ "Returns", "an", "index", "containing", "unique", "values", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2164-L2192
19,410
pandas-dev/pandas
pandas/core/indexes/base.py
Index._get_reconciled_name_object
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 self._shallow_copy(name=name) return self
python
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 self._shallow_copy(name=name) return self
[ "def", "_get_reconciled_name_object", "(", "self", ",", "other", ")", ":", "name", "=", "get_op_result_name", "(", "self", ",", "other", ")", "if", "self", ".", "name", "!=", "name", ":", "return", "self", ".", "_shallow_copy", "(", "name", "=", "name", ")", "return", "self" ]
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.
[ "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", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2234-L2243
19,411
pandas-dev/pandas
pandas/core/indexes/base.py
Index.union
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 1. `self` and `other` are equal. 2. `self` or `other` has length 0. 3. Some values in `self` or `other` cannot be compared. A RuntimeWarning is issued in this case. * False : do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- union : Index Examples -------- >>> idx1 = pd.Index([1, 2, 3, 4]) >>> idx2 = pd.Index([3, 4, 5, 6]) >>> idx1.union(idx2) Int64Index([1, 2, 3, 4, 5, 6], dtype='int64') """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) other = ensure_index(other) if len(other) == 0 or self.equals(other): return self._get_reconciled_name_object(other) if len(self) == 0: return other._get_reconciled_name_object(self) # TODO: is_dtype_union_equal is a hack around # 1. buggy set ops with duplicates (GH #13432) # 2. CategoricalIndex lacking setops (GH #10186) # Once those are fixed, this workaround can be removed if not is_dtype_union_equal(self.dtype, other.dtype): this = self.astype('O') other = other.astype('O') return this.union(other, sort=sort) # TODO(EA): setops-refactor, clean all this up if is_period_dtype(self) or is_datetime64tz_dtype(self): lvals = self._ndarray_values else: lvals = self._values if is_period_dtype(other) or is_datetime64tz_dtype(other): rvals = other._ndarray_values else: rvals = other._values if sort is None and self.is_monotonic and other.is_monotonic: try: result = self._outer_indexer(lvals, rvals)[0] except TypeError: # incomparable objects result = list(lvals) # worth making this faster? a very unusual case value_set = set(lvals) result.extend([x for x in rvals if x not in value_set]) else: indexer = self.get_indexer(other) indexer, = (indexer == -1).nonzero() if len(indexer) > 0: other_diff = algos.take_nd(rvals, indexer, allow_fill=False) result = _concat._concat_compat((lvals, other_diff)) else: result = lvals if sort is None: try: result = sorting.safe_sort(result) except TypeError as e: warnings.warn("{}, sort order is undefined for " "incomparable objects".format(e), RuntimeWarning, stacklevel=3) # for subclasses return self._wrap_setop_result(other, result)
python
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 1. `self` and `other` are equal. 2. `self` or `other` has length 0. 3. Some values in `self` or `other` cannot be compared. A RuntimeWarning is issued in this case. * False : do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- union : Index Examples -------- >>> idx1 = pd.Index([1, 2, 3, 4]) >>> idx2 = pd.Index([3, 4, 5, 6]) >>> idx1.union(idx2) Int64Index([1, 2, 3, 4, 5, 6], dtype='int64') """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) other = ensure_index(other) if len(other) == 0 or self.equals(other): return self._get_reconciled_name_object(other) if len(self) == 0: return other._get_reconciled_name_object(self) # TODO: is_dtype_union_equal is a hack around # 1. buggy set ops with duplicates (GH #13432) # 2. CategoricalIndex lacking setops (GH #10186) # Once those are fixed, this workaround can be removed if not is_dtype_union_equal(self.dtype, other.dtype): this = self.astype('O') other = other.astype('O') return this.union(other, sort=sort) # TODO(EA): setops-refactor, clean all this up if is_period_dtype(self) or is_datetime64tz_dtype(self): lvals = self._ndarray_values else: lvals = self._values if is_period_dtype(other) or is_datetime64tz_dtype(other): rvals = other._ndarray_values else: rvals = other._values if sort is None and self.is_monotonic and other.is_monotonic: try: result = self._outer_indexer(lvals, rvals)[0] except TypeError: # incomparable objects result = list(lvals) # worth making this faster? a very unusual case value_set = set(lvals) result.extend([x for x in rvals if x not in value_set]) else: indexer = self.get_indexer(other) indexer, = (indexer == -1).nonzero() if len(indexer) > 0: other_diff = algos.take_nd(rvals, indexer, allow_fill=False) result = _concat._concat_compat((lvals, other_diff)) else: result = lvals if sort is None: try: result = sorting.safe_sort(result) except TypeError as e: warnings.warn("{}, sort order is undefined for " "incomparable objects".format(e), RuntimeWarning, stacklevel=3) # for subclasses return self._wrap_setop_result(other, result)
[ "def", "union", "(", "self", ",", "other", ",", "sort", "=", "None", ")", ":", "self", ".", "_validate_sort_keyword", "(", "sort", ")", "self", ".", "_assert_can_do_setop", "(", "other", ")", "other", "=", "ensure_index", "(", "other", ")", "if", "len", "(", "other", ")", "==", "0", "or", "self", ".", "equals", "(", "other", ")", ":", "return", "self", ".", "_get_reconciled_name_object", "(", "other", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "other", ".", "_get_reconciled_name_object", "(", "self", ")", "# TODO: is_dtype_union_equal is a hack around", "# 1. buggy set ops with duplicates (GH #13432)", "# 2. CategoricalIndex lacking setops (GH #10186)", "# Once those are fixed, this workaround can be removed", "if", "not", "is_dtype_union_equal", "(", "self", ".", "dtype", ",", "other", ".", "dtype", ")", ":", "this", "=", "self", ".", "astype", "(", "'O'", ")", "other", "=", "other", ".", "astype", "(", "'O'", ")", "return", "this", ".", "union", "(", "other", ",", "sort", "=", "sort", ")", "# TODO(EA): setops-refactor, clean all this up", "if", "is_period_dtype", "(", "self", ")", "or", "is_datetime64tz_dtype", "(", "self", ")", ":", "lvals", "=", "self", ".", "_ndarray_values", "else", ":", "lvals", "=", "self", ".", "_values", "if", "is_period_dtype", "(", "other", ")", "or", "is_datetime64tz_dtype", "(", "other", ")", ":", "rvals", "=", "other", ".", "_ndarray_values", "else", ":", "rvals", "=", "other", ".", "_values", "if", "sort", "is", "None", "and", "self", ".", "is_monotonic", "and", "other", ".", "is_monotonic", ":", "try", ":", "result", "=", "self", ".", "_outer_indexer", "(", "lvals", ",", "rvals", ")", "[", "0", "]", "except", "TypeError", ":", "# incomparable objects", "result", "=", "list", "(", "lvals", ")", "# worth making this faster? a very unusual case", "value_set", "=", "set", "(", "lvals", ")", "result", ".", "extend", "(", "[", "x", "for", "x", "in", "rvals", "if", "x", "not", "in", "value_set", "]", ")", "else", ":", "indexer", "=", "self", ".", "get_indexer", "(", "other", ")", "indexer", ",", "=", "(", "indexer", "==", "-", "1", ")", ".", "nonzero", "(", ")", "if", "len", "(", "indexer", ")", ">", "0", ":", "other_diff", "=", "algos", ".", "take_nd", "(", "rvals", ",", "indexer", ",", "allow_fill", "=", "False", ")", "result", "=", "_concat", ".", "_concat_compat", "(", "(", "lvals", ",", "other_diff", ")", ")", "else", ":", "result", "=", "lvals", "if", "sort", "is", "None", ":", "try", ":", "result", "=", "sorting", ".", "safe_sort", "(", "result", ")", "except", "TypeError", "as", "e", ":", "warnings", ".", "warn", "(", "\"{}, sort order is undefined for \"", "\"incomparable objects\"", ".", "format", "(", "e", ")", ",", "RuntimeWarning", ",", "stacklevel", "=", "3", ")", "# for subclasses", "return", "self", ".", "_wrap_setop_result", "(", "other", ",", "result", ")" ]
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. `self` or `other` has length 0. 3. Some values in `self` or `other` cannot be compared. A RuntimeWarning is issued in this case. * False : do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- union : Index Examples -------- >>> idx1 = pd.Index([1, 2, 3, 4]) >>> idx2 = pd.Index([3, 4, 5, 6]) >>> idx1.union(idx2) Int64Index([1, 2, 3, 4, 5, 6], dtype='int64')
[ "Form", "the", "union", "of", "two", "Index", "objects", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2250-L2348
19,412
pandas-dev/pandas
pandas/core/indexes/base.py
Index.difference
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 Whether to sort the resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. * None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. * False : Do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- difference : Index Examples -------- >>> idx1 = pd.Index([2, 1, 3, 4]) >>> idx2 = pd.Index([3, 4, 5, 6]) >>> idx1.difference(idx2) Int64Index([1, 2], dtype='int64') >>> idx1.difference(idx2, sort=False) Int64Index([2, 1], dtype='int64') """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) if self.equals(other): # pass an empty np.ndarray with the appropriate dtype return self._shallow_copy(self._data[:0]) other, result_name = self._convert_can_do_setop(other) this = self._get_unique_index() indexer = this.get_indexer(other) indexer = indexer.take((indexer != -1).nonzero()[0]) label_diff = np.setdiff1d(np.arange(this.size), indexer, assume_unique=True) the_diff = this.values.take(label_diff) if sort is None: try: the_diff = sorting.safe_sort(the_diff) except TypeError: pass return this._shallow_copy(the_diff, name=result_name, freq=None)
python
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 Whether to sort the resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. * None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. * False : Do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- difference : Index Examples -------- >>> idx1 = pd.Index([2, 1, 3, 4]) >>> idx2 = pd.Index([3, 4, 5, 6]) >>> idx1.difference(idx2) Int64Index([1, 2], dtype='int64') >>> idx1.difference(idx2, sort=False) Int64Index([2, 1], dtype='int64') """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) if self.equals(other): # pass an empty np.ndarray with the appropriate dtype return self._shallow_copy(self._data[:0]) other, result_name = self._convert_can_do_setop(other) this = self._get_unique_index() indexer = this.get_indexer(other) indexer = indexer.take((indexer != -1).nonzero()[0]) label_diff = np.setdiff1d(np.arange(this.size), indexer, assume_unique=True) the_diff = this.values.take(label_diff) if sort is None: try: the_diff = sorting.safe_sort(the_diff) except TypeError: pass return this._shallow_copy(the_diff, name=result_name, freq=None)
[ "def", "difference", "(", "self", ",", "other", ",", "sort", "=", "None", ")", ":", "self", ".", "_validate_sort_keyword", "(", "sort", ")", "self", ".", "_assert_can_do_setop", "(", "other", ")", "if", "self", ".", "equals", "(", "other", ")", ":", "# pass an empty np.ndarray with the appropriate dtype", "return", "self", ".", "_shallow_copy", "(", "self", ".", "_data", "[", ":", "0", "]", ")", "other", ",", "result_name", "=", "self", ".", "_convert_can_do_setop", "(", "other", ")", "this", "=", "self", ".", "_get_unique_index", "(", ")", "indexer", "=", "this", ".", "get_indexer", "(", "other", ")", "indexer", "=", "indexer", ".", "take", "(", "(", "indexer", "!=", "-", "1", ")", ".", "nonzero", "(", ")", "[", "0", "]", ")", "label_diff", "=", "np", ".", "setdiff1d", "(", "np", ".", "arange", "(", "this", ".", "size", ")", ",", "indexer", ",", "assume_unique", "=", "True", ")", "the_diff", "=", "this", ".", "values", ".", "take", "(", "label_diff", ")", "if", "sort", "is", "None", ":", "try", ":", "the_diff", "=", "sorting", ".", "safe_sort", "(", "the_diff", ")", "except", "TypeError", ":", "pass", "return", "this", ".", "_shallow_copy", "(", "the_diff", ",", "name", "=", "result_name", ",", "freq", "=", "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 Whether to sort the resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. * None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. * False : Do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- difference : Index Examples -------- >>> idx1 = pd.Index([2, 1, 3, 4]) >>> idx2 = pd.Index([3, 4, 5, 6]) >>> idx1.difference(idx2) Int64Index([1, 2], dtype='int64') >>> idx1.difference(idx2, sort=False) Int64Index([2, 1], dtype='int64')
[ "Return", "a", "new", "Index", "with", "elements", "from", "the", "index", "that", "are", "not", "in", "other", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2441-L2504
19,413
pandas-dev/pandas
pandas/core/indexes/base.py
Index.symmetric_difference
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 resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. * None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. * False : Do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- symmetric_difference : Index Notes ----- ``symmetric_difference`` contains elements that appear in either ``idx1`` or ``idx2`` but not both. Equivalent to the Index created by ``idx1.difference(idx2) | idx2.difference(idx1)`` with duplicates dropped. Examples -------- >>> idx1 = pd.Index([1, 2, 3, 4]) >>> idx2 = pd.Index([2, 3, 4, 5]) >>> idx1.symmetric_difference(idx2) Int64Index([1, 5], dtype='int64') You can also use the ``^`` operator: >>> idx1 ^ idx2 Int64Index([1, 5], dtype='int64') """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) other, result_name_update = self._convert_can_do_setop(other) if result_name is None: result_name = result_name_update this = self._get_unique_index() other = other._get_unique_index() indexer = this.get_indexer(other) # {this} minus {other} common_indexer = indexer.take((indexer != -1).nonzero()[0]) left_indexer = np.setdiff1d(np.arange(this.size), common_indexer, assume_unique=True) left_diff = this.values.take(left_indexer) # {other} minus {this} right_indexer = (indexer == -1).nonzero()[0] right_diff = other.values.take(right_indexer) the_diff = _concat._concat_compat([left_diff, right_diff]) if sort is None: try: the_diff = sorting.safe_sort(the_diff) except TypeError: pass attribs = self._get_attributes_dict() attribs['name'] = result_name if 'freq' in attribs: attribs['freq'] = None return self._shallow_copy_with_infer(the_diff, **attribs)
python
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 resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. * None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. * False : Do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- symmetric_difference : Index Notes ----- ``symmetric_difference`` contains elements that appear in either ``idx1`` or ``idx2`` but not both. Equivalent to the Index created by ``idx1.difference(idx2) | idx2.difference(idx1)`` with duplicates dropped. Examples -------- >>> idx1 = pd.Index([1, 2, 3, 4]) >>> idx2 = pd.Index([2, 3, 4, 5]) >>> idx1.symmetric_difference(idx2) Int64Index([1, 5], dtype='int64') You can also use the ``^`` operator: >>> idx1 ^ idx2 Int64Index([1, 5], dtype='int64') """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) other, result_name_update = self._convert_can_do_setop(other) if result_name is None: result_name = result_name_update this = self._get_unique_index() other = other._get_unique_index() indexer = this.get_indexer(other) # {this} minus {other} common_indexer = indexer.take((indexer != -1).nonzero()[0]) left_indexer = np.setdiff1d(np.arange(this.size), common_indexer, assume_unique=True) left_diff = this.values.take(left_indexer) # {other} minus {this} right_indexer = (indexer == -1).nonzero()[0] right_diff = other.values.take(right_indexer) the_diff = _concat._concat_compat([left_diff, right_diff]) if sort is None: try: the_diff = sorting.safe_sort(the_diff) except TypeError: pass attribs = self._get_attributes_dict() attribs['name'] = result_name if 'freq' in attribs: attribs['freq'] = None return self._shallow_copy_with_infer(the_diff, **attribs)
[ "def", "symmetric_difference", "(", "self", ",", "other", ",", "result_name", "=", "None", ",", "sort", "=", "None", ")", ":", "self", ".", "_validate_sort_keyword", "(", "sort", ")", "self", ".", "_assert_can_do_setop", "(", "other", ")", "other", ",", "result_name_update", "=", "self", ".", "_convert_can_do_setop", "(", "other", ")", "if", "result_name", "is", "None", ":", "result_name", "=", "result_name_update", "this", "=", "self", ".", "_get_unique_index", "(", ")", "other", "=", "other", ".", "_get_unique_index", "(", ")", "indexer", "=", "this", ".", "get_indexer", "(", "other", ")", "# {this} minus {other}", "common_indexer", "=", "indexer", ".", "take", "(", "(", "indexer", "!=", "-", "1", ")", ".", "nonzero", "(", ")", "[", "0", "]", ")", "left_indexer", "=", "np", ".", "setdiff1d", "(", "np", ".", "arange", "(", "this", ".", "size", ")", ",", "common_indexer", ",", "assume_unique", "=", "True", ")", "left_diff", "=", "this", ".", "values", ".", "take", "(", "left_indexer", ")", "# {other} minus {this}", "right_indexer", "=", "(", "indexer", "==", "-", "1", ")", ".", "nonzero", "(", ")", "[", "0", "]", "right_diff", "=", "other", ".", "values", ".", "take", "(", "right_indexer", ")", "the_diff", "=", "_concat", ".", "_concat_compat", "(", "[", "left_diff", ",", "right_diff", "]", ")", "if", "sort", "is", "None", ":", "try", ":", "the_diff", "=", "sorting", ".", "safe_sort", "(", "the_diff", ")", "except", "TypeError", ":", "pass", "attribs", "=", "self", ".", "_get_attributes_dict", "(", ")", "attribs", "[", "'name'", "]", "=", "result_name", "if", "'freq'", "in", "attribs", ":", "attribs", "[", "'freq'", "]", "=", "None", "return", "self", ".", "_shallow_copy_with_infer", "(", "the_diff", ",", "*", "*", "attribs", ")" ]
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 TypeError from incomparable elements is caught by pandas. * None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. * False : Do not sort the result. .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- symmetric_difference : Index Notes ----- ``symmetric_difference`` contains elements that appear in either ``idx1`` or ``idx2`` but not both. Equivalent to the Index created by ``idx1.difference(idx2) | idx2.difference(idx1)`` with duplicates dropped. Examples -------- >>> idx1 = pd.Index([1, 2, 3, 4]) >>> idx2 = pd.Index([2, 3, 4, 5]) >>> idx1.symmetric_difference(idx2) Int64Index([1, 5], dtype='int64') You can also use the ``^`` operator: >>> idx1 ^ idx2 Int64Index([1, 5], dtype='int64')
[ "Compute", "the", "symmetric", "difference", "of", "two", "Index", "objects", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L2506-L2584
19,414
pandas-dev/pandas
pandas/core/indexes/base.py
Index._invalid_indexer
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, kind=type(key)))
python
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, kind=type(key)))
[ "def", "_invalid_indexer", "(", "self", ",", "form", ",", "key", ")", ":", "raise", "TypeError", "(", "\"cannot do {form} indexing on {klass} with these \"", "\"indexers [{key}] of {kind}\"", ".", "format", "(", "form", "=", "form", ",", "klass", "=", "type", "(", "self", ")", ",", "key", "=", "key", ",", "kind", "=", "type", "(", "key", ")", ")", ")" ]
Consistent invalid indexer message.
[ "Consistent", "invalid", "indexer", "message", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3057-L3064
19,415
pandas-dev/pandas
pandas/core/indexes/base.py
Index._try_convert_to_int_index
def _try_convert_to_int_index(cls, data, copy, name, dtype): """ Attempt to convert an array of data into an integer index. Parameters ---------- data : The data to convert. copy : Whether to copy the data or not. name : The name of the index returned. Returns ------- int_index : data converted to either an Int64Index or a UInt64Index Raises ------ ValueError if the conversion was not successful. """ from .numeric import Int64Index, UInt64Index if not is_unsigned_integer_dtype(dtype): # skip int64 conversion attempt if uint-like dtype is passed, as # this could return Int64Index when UInt64Index is what's desrired try: res = data.astype('i8', copy=False) if (res == data).all(): return Int64Index(res, copy=copy, name=name) except (OverflowError, TypeError, ValueError): pass # Conversion to int64 failed (possibly due to overflow) or was skipped, # so let's try now with uint64. try: res = data.astype('u8', copy=False) if (res == data).all(): return UInt64Index(res, copy=copy, name=name) except (OverflowError, TypeError, ValueError): pass raise ValueError
python
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. Returns ------- int_index : data converted to either an Int64Index or a UInt64Index Raises ------ ValueError if the conversion was not successful. """ from .numeric import Int64Index, UInt64Index if not is_unsigned_integer_dtype(dtype): # skip int64 conversion attempt if uint-like dtype is passed, as # this could return Int64Index when UInt64Index is what's desrired try: res = data.astype('i8', copy=False) if (res == data).all(): return Int64Index(res, copy=copy, name=name) except (OverflowError, TypeError, ValueError): pass # Conversion to int64 failed (possibly due to overflow) or was skipped, # so let's try now with uint64. try: res = data.astype('u8', copy=False) if (res == data).all(): return UInt64Index(res, copy=copy, name=name) except (OverflowError, TypeError, ValueError): pass raise ValueError
[ "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 conversion attempt if uint-like dtype is passed, as", "# this could return Int64Index when UInt64Index is what's desrired", "try", ":", "res", "=", "data", ".", "astype", "(", "'i8'", ",", "copy", "=", "False", ")", "if", "(", "res", "==", "data", ")", ".", "all", "(", ")", ":", "return", "Int64Index", "(", "res", ",", "copy", "=", "copy", ",", "name", "=", "name", ")", "except", "(", "OverflowError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "# Conversion to int64 failed (possibly due to overflow) or was skipped,", "# so let's try now with uint64.", "try", ":", "res", "=", "data", ".", "astype", "(", "'u8'", ",", "copy", "=", "False", ")", "if", "(", "res", "==", "data", ")", ".", "all", "(", ")", ":", "return", "UInt64Index", "(", "res", ",", "copy", "=", "copy", ",", "name", "=", "name", ")", "except", "(", "OverflowError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "raise", "ValueError" ]
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 or a UInt64Index Raises ------ ValueError if the conversion was not successful.
[ "Attempt", "to", "convert", "an", "array", "of", "data", "into", "an", "integer", "index", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3746-L3786
19,416
pandas-dev/pandas
pandas/core/indexes/base.py
Index._coerce_to_ndarray
def _coerce_to_ndarray(cls, data): """ Coerces data to ndarray. Converts other iterables to list first and then to array. Does not touch ndarrays. Raises ------ TypeError When the data passed in is a scalar. """ if not isinstance(data, (np.ndarray, Index)): if data is None or is_scalar(data): cls._scalar_data_error(data) # other iterable of some kind if not isinstance(data, (ABCSeries, list, tuple)): data = list(data) data = np.asarray(data) return data
python
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(data, (np.ndarray, Index)): if data is None or is_scalar(data): cls._scalar_data_error(data) # other iterable of some kind if not isinstance(data, (ABCSeries, list, tuple)): data = list(data) data = np.asarray(data) return data
[ "def", "_coerce_to_ndarray", "(", "cls", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "(", "np", ".", "ndarray", ",", "Index", ")", ")", ":", "if", "data", "is", "None", "or", "is_scalar", "(", "data", ")", ":", "cls", ".", "_scalar_data_error", "(", "data", ")", "# other iterable of some kind", "if", "not", "isinstance", "(", "data", ",", "(", "ABCSeries", ",", "list", ",", "tuple", ")", ")", ":", "data", "=", "list", "(", "data", ")", "data", "=", "np", ".", "asarray", "(", "data", ")", "return", "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.
[ "Coerces", "data", "to", "ndarray", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3800-L3821
19,417
pandas-dev/pandas
pandas/core/indexes/base.py
Index._coerce_scalar_to_index
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 the numeric dtype of "self" (unless # it's float) if there are NaN values in our output. dtype = None return Index([item], dtype=dtype, **self._get_attributes_dict())
python
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 the numeric dtype of "self" (unless # it's float) if there are NaN values in our output. dtype = None return Index([item], dtype=dtype, **self._get_attributes_dict())
[ "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 there are NaN values in our output.", "dtype", "=", "None", "return", "Index", "(", "[", "item", "]", ",", "dtype", "=", "dtype", ",", "*", "*", "self", ".", "_get_attributes_dict", "(", ")", ")" ]
We need to coerce a scalar to a compat for our index type. Parameters ---------- item : scalar item to coerce
[ "We", "need", "to", "coerce", "a", "scalar", "to", "a", "compat", "for", "our", "index", "type", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3823-L3838
19,418
pandas-dev/pandas
pandas/core/indexes/base.py
Index._assert_can_do_op
def _assert_can_do_op(self, value): """ Check value is valid for scalar op. """ if not is_scalar(value): msg = "'value' must be a scalar, passed: {0}" raise TypeError(msg.format(type(value).__name__))
python
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", ")", ":", "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.
[ "Check", "value", "is", "valid", "for", "scalar", "op", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3852-L3858
19,419
pandas-dev/pandas
pandas/core/indexes/base.py
Index.append
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)): to_concat = to_concat + list(other) else: to_concat.append(other) for obj in to_concat: if not isinstance(obj, Index): raise TypeError('all inputs must be Index') names = {obj.name for obj in to_concat} name = None if len(names) > 1 else self.name return self._concat(to_concat, name)
python
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)): to_concat = to_concat + list(other) else: to_concat.append(other) for obj in to_concat: if not isinstance(obj, Index): raise TypeError('all inputs must be Index') names = {obj.name for obj in to_concat} name = None if len(names) > 1 else self.name return self._concat(to_concat, name)
[ "def", "append", "(", "self", ",", "other", ")", ":", "to_concat", "=", "[", "self", "]", "if", "isinstance", "(", "other", ",", "(", "list", ",", "tuple", ")", ")", ":", "to_concat", "=", "to_concat", "+", "list", "(", "other", ")", "else", ":", "to_concat", ".", "append", "(", "other", ")", "for", "obj", "in", "to_concat", ":", "if", "not", "isinstance", "(", "obj", ",", "Index", ")", ":", "raise", "TypeError", "(", "'all inputs must be Index'", ")", "names", "=", "{", "obj", ".", "name", "for", "obj", "in", "to_concat", "}", "name", "=", "None", "if", "len", "(", "names", ")", ">", "1", "else", "self", ".", "name", "return", "self", ".", "_concat", "(", "to_concat", ",", "name", ")" ]
Append a collection of Index options together. Parameters ---------- other : Index or list/tuple of indices Returns ------- appended : Index
[ "Append", "a", "collection", "of", "Index", "options", "together", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L3981-L4008
19,420
pandas-dev/pandas
pandas/core/indexes/base.py
Index.putmask
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._shallow_copy(values) except (ValueError, TypeError) as err: if is_object_dtype(self): raise err # coerces to object return self.astype(object).putmask(mask, value)
python
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._shallow_copy(values) except (ValueError, TypeError) as err: if is_object_dtype(self): raise err # coerces to object return self.astype(object).putmask(mask, value)
[ "def", "putmask", "(", "self", ",", "mask", ",", "value", ")", ":", "values", "=", "self", ".", "values", ".", "copy", "(", ")", "try", ":", "np", ".", "putmask", "(", "values", ",", "mask", ",", "self", ".", "_convert_for_op", "(", "value", ")", ")", "return", "self", ".", "_shallow_copy", "(", "values", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "err", ":", "if", "is_object_dtype", "(", "self", ")", ":", "raise", "err", "# coerces to object", "return", "self", ".", "astype", "(", "object", ")", ".", "putmask", "(", "mask", ",", "value", ")" ]
Return a new Index of the values set with the mask. See Also -------- numpy.ndarray.putmask
[ "Return", "a", "new", "Index", "of", "the", "values", "set", "with", "the", "mask", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4025-L4042
19,421
pandas-dev/pandas
pandas/core/indexes/base.py
Index.equals
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 other is not object, use other's logic for coercion return other.equals(self) try: return array_equivalent(com.values_from_object(self), com.values_from_object(other)) except Exception: return False
python
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 other is not object, use other's logic for coercion return other.equals(self) try: return array_equivalent(com.values_from_object(self), com.values_from_object(other)) except Exception: return False
[ "def", "equals", "(", "self", ",", "other", ")", ":", "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 other is not object, use other's logic for coercion", "return", "other", ".", "equals", "(", "self", ")", "try", ":", "return", "array_equivalent", "(", "com", ".", "values_from_object", "(", "self", ")", ",", "com", ".", "values_from_object", "(", "other", ")", ")", "except", "Exception", ":", "return", "False" ]
Determine if two Index objects contain the same elements.
[ "Determine", "if", "two", "Index", "objects", "contain", "the", "same", "elements", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4044-L4062
19,422
pandas-dev/pandas
pandas/core/indexes/base.py
Index.identical
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 type(self) == type(other))
python
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 type(self) == type(other))
[ "def", "identical", "(", "self", ",", "other", ")", ":", "return", "(", "self", ".", "equals", "(", "other", ")", "and", "all", "(", "(", "getattr", "(", "self", ",", "c", ",", "None", ")", "==", "getattr", "(", "other", ",", "c", ",", "None", ")", "for", "c", "in", "self", ".", "_comparables", ")", ")", "and", "type", "(", "self", ")", "==", "type", "(", "other", ")", ")" ]
Similar to equals, but check that other comparable attributes are also equal.
[ "Similar", "to", "equals", "but", "check", "that", "other", "comparable", "attributes", "are", "also", "equal", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4064-L4072
19,423
pandas-dev/pandas
pandas/core/indexes/base.py
Index.asof
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 ---------- label : object The label up to which the method returns the latest index label. Returns ------- object The passed label if it is in the index. The previous label if the passed label is not in the sorted index or `NaN` if there is no such label. See Also -------- Series.asof : Return the latest value in a Series up to the passed index. merge_asof : Perform an asof merge (similar to left join but it matches on nearest key rather than equal key). Index.get_loc : An `asof` is a thin wrapper around `get_loc` with method='pad'. Examples -------- `Index.asof` returns the latest index label up to the passed label. >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03']) >>> idx.asof('2014-01-01') '2013-12-31' If the label is in the index, the method returns the passed label. >>> idx.asof('2014-01-02') '2014-01-02' If all of the labels in the index are later than the passed label, NaN is returned. >>> idx.asof('1999-01-02') nan If the index is not sorted, an error is raised. >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02', ... '2014-01-03']) >>> idx_not_sorted.asof('2013-12-31') Traceback (most recent call last): ValueError: index must be monotonic increasing or decreasing """ try: loc = self.get_loc(label, method='pad') except KeyError: return self._na_value else: if isinstance(loc, slice): loc = loc.indices(len(self))[-1] return self[loc]
python
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 ---------- label : object The label up to which the method returns the latest index label. Returns ------- object The passed label if it is in the index. The previous label if the passed label is not in the sorted index or `NaN` if there is no such label. See Also -------- Series.asof : Return the latest value in a Series up to the passed index. merge_asof : Perform an asof merge (similar to left join but it matches on nearest key rather than equal key). Index.get_loc : An `asof` is a thin wrapper around `get_loc` with method='pad'. Examples -------- `Index.asof` returns the latest index label up to the passed label. >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03']) >>> idx.asof('2014-01-01') '2013-12-31' If the label is in the index, the method returns the passed label. >>> idx.asof('2014-01-02') '2014-01-02' If all of the labels in the index are later than the passed label, NaN is returned. >>> idx.asof('1999-01-02') nan If the index is not sorted, an error is raised. >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02', ... '2014-01-03']) >>> idx_not_sorted.asof('2013-12-31') Traceback (most recent call last): ValueError: index must be monotonic increasing or decreasing """ try: loc = self.get_loc(label, method='pad') except KeyError: return self._na_value else: if isinstance(loc, slice): loc = loc.indices(len(self))[-1] return self[loc]
[ "def", "asof", "(", "self", ",", "label", ")", ":", "try", ":", "loc", "=", "self", ".", "get_loc", "(", "label", ",", "method", "=", "'pad'", ")", "except", "KeyError", ":", "return", "self", ".", "_na_value", "else", ":", "if", "isinstance", "(", "loc", ",", "slice", ")", ":", "loc", "=", "loc", ".", "indices", "(", "len", "(", "self", ")", ")", "[", "-", "1", "]", "return", "self", "[", "loc", "]" ]
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 The label up to which the method returns the latest index label. Returns ------- object The passed label if it is in the index. The previous label if the passed label is not in the sorted index or `NaN` if there is no such label. See Also -------- Series.asof : Return the latest value in a Series up to the passed index. merge_asof : Perform an asof merge (similar to left join but it matches on nearest key rather than equal key). Index.get_loc : An `asof` is a thin wrapper around `get_loc` with method='pad'. Examples -------- `Index.asof` returns the latest index label up to the passed label. >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03']) >>> idx.asof('2014-01-01') '2013-12-31' If the label is in the index, the method returns the passed label. >>> idx.asof('2014-01-02') '2014-01-02' If all of the labels in the index are later than the passed label, NaN is returned. >>> idx.asof('1999-01-02') nan If the index is not sorted, an error is raised. >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02', ... '2014-01-03']) >>> idx_not_sorted.asof('2013-12-31') Traceback (most recent call last): ValueError: index must be monotonic increasing or decreasing
[ "Return", "the", "label", "from", "the", "index", "or", "if", "not", "present", "the", "previous", "one", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4074-L4137
19,424
pandas-dev/pandas
pandas/core/indexes/base.py
Index.sort_values
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 Should the indices that would sort the index be returned. ascending : bool, default True Should the index values be sorted in an ascending order. Returns ------- sorted_index : pandas.Index Sorted copy of the index. indexer : numpy.ndarray, optional The indices that the index itself was sorted by. See Also -------- Series.sort_values : Sort values of a Series. DataFrame.sort_values : Sort values in a DataFrame. Examples -------- >>> idx = pd.Index([10, 100, 1, 1000]) >>> idx Int64Index([10, 100, 1, 1000], dtype='int64') Sort values in ascending order (default behavior). >>> idx.sort_values() Int64Index([1, 10, 100, 1000], dtype='int64') Sort values in descending order, and also get the indices `idx` was sorted by. >>> idx.sort_values(ascending=False, return_indexer=True) (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2])) """ _as = self.argsort() if not ascending: _as = _as[::-1] sorted_index = self.take(_as) if return_indexer: return sorted_index, _as else: return sorted_index
python
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 Should the indices that would sort the index be returned. ascending : bool, default True Should the index values be sorted in an ascending order. Returns ------- sorted_index : pandas.Index Sorted copy of the index. indexer : numpy.ndarray, optional The indices that the index itself was sorted by. See Also -------- Series.sort_values : Sort values of a Series. DataFrame.sort_values : Sort values in a DataFrame. Examples -------- >>> idx = pd.Index([10, 100, 1, 1000]) >>> idx Int64Index([10, 100, 1, 1000], dtype='int64') Sort values in ascending order (default behavior). >>> idx.sort_values() Int64Index([1, 10, 100, 1000], dtype='int64') Sort values in descending order, and also get the indices `idx` was sorted by. >>> idx.sort_values(ascending=False, return_indexer=True) (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2])) """ _as = self.argsort() if not ascending: _as = _as[::-1] sorted_index = self.take(_as) if return_indexer: return sorted_index, _as else: return sorted_index
[ "def", "sort_values", "(", "self", ",", "return_indexer", "=", "False", ",", "ascending", "=", "True", ")", ":", "_as", "=", "self", ".", "argsort", "(", ")", "if", "not", "ascending", ":", "_as", "=", "_as", "[", ":", ":", "-", "1", "]", "sorted_index", "=", "self", ".", "take", "(", "_as", ")", "if", "return_indexer", ":", "return", "sorted_index", ",", "_as", "else", ":", "return", "sorted_index" ]
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. ascending : bool, default True Should the index values be sorted in an ascending order. Returns ------- sorted_index : pandas.Index Sorted copy of the index. indexer : numpy.ndarray, optional The indices that the index itself was sorted by. See Also -------- Series.sort_values : Sort values of a Series. DataFrame.sort_values : Sort values in a DataFrame. Examples -------- >>> idx = pd.Index([10, 100, 1, 1000]) >>> idx Int64Index([10, 100, 1, 1000], dtype='int64') Sort values in ascending order (default behavior). >>> idx.sort_values() Int64Index([1, 10, 100, 1000], dtype='int64') Sort values in descending order, and also get the indices `idx` was sorted by. >>> idx.sort_values(ascending=False, return_indexer=True) (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))
[ "Return", "a", "sorted", "copy", "of", "the", "index", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4178-L4230
19,425
pandas-dev/pandas
pandas/core/indexes/base.py
Index.argsort
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.ndarray Integer indices that would sort the index if used as an indexer. See Also -------- numpy.argsort : Similar method for NumPy arrays. Index.sort_values : Return sorted copy of Index. Examples -------- >>> idx = pd.Index(['b', 'a', 'd', 'c']) >>> idx Index(['b', 'a', 'd', 'c'], dtype='object') >>> order = idx.argsort() >>> order array([1, 0, 3, 2]) >>> idx[order] Index(['a', 'b', 'c', 'd'], dtype='object') """ result = self.asi8 if result is None: result = np.array(self) return result.argsort(*args, **kwargs)
python
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.ndarray Integer indices that would sort the index if used as an indexer. See Also -------- numpy.argsort : Similar method for NumPy arrays. Index.sort_values : Return sorted copy of Index. Examples -------- >>> idx = pd.Index(['b', 'a', 'd', 'c']) >>> idx Index(['b', 'a', 'd', 'c'], dtype='object') >>> order = idx.argsort() >>> order array([1, 0, 3, 2]) >>> idx[order] Index(['a', 'b', 'c', 'd'], dtype='object') """ result = self.asi8 if result is None: result = np.array(self) return result.argsort(*args, **kwargs)
[ "def", "argsort", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "asi8", "if", "result", "is", "None", ":", "result", "=", "np", ".", "array", "(", "self", ")", "return", "result", ".", "argsort", "(", "*", "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.ndarray Integer indices that would sort the index if used as an indexer. See Also -------- numpy.argsort : Similar method for NumPy arrays. Index.sort_values : Return sorted copy of Index. Examples -------- >>> idx = pd.Index(['b', 'a', 'd', 'c']) >>> idx Index(['b', 'a', 'd', 'c'], dtype='object') >>> order = idx.argsort() >>> order array([1, 0, 3, 2]) >>> idx[order] Index(['a', 'b', 'c', 'd'], dtype='object')
[ "Return", "the", "integer", "indices", "that", "would", "sort", "the", "index", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4295-L4333
19,426
pandas-dev/pandas
pandas/core/indexes/base.py
Index.get_value
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 the EA directly here. s = getattr(series, '_values', series) if isinstance(s, (ExtensionArray, Index)) and is_scalar(key): # GH 20882, 21257 # Unify Index and ExtensionArray treatment # First try to convert the key to a location # If that fails, raise a KeyError if an integer # index, otherwise, see if key is an integer, and # try that try: iloc = self.get_loc(key) return s[iloc] except KeyError: if (len(self) > 0 and (self.holds_integer() or self.is_boolean())): raise elif is_integer(key): return s[key] s = com.values_from_object(series) k = com.values_from_object(key) k = self._convert_scalar_indexer(k, kind='getitem') try: return self._engine.get_value(s, k, tz=getattr(series.dtype, 'tz', None)) except KeyError as e1: if len(self) > 0 and (self.holds_integer() or self.is_boolean()): raise try: return libindex.get_value_box(s, key) except IndexError: raise except TypeError: # generator/iterator-like if is_iterator(key): raise InvalidIndexError(key) else: raise e1 except Exception: # pragma: no cover raise e1 except TypeError: # python 3 if is_scalar(key): # pragma: no cover raise IndexError(key) raise InvalidIndexError(key)
python
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 the EA directly here. s = getattr(series, '_values', series) if isinstance(s, (ExtensionArray, Index)) and is_scalar(key): # GH 20882, 21257 # Unify Index and ExtensionArray treatment # First try to convert the key to a location # If that fails, raise a KeyError if an integer # index, otherwise, see if key is an integer, and # try that try: iloc = self.get_loc(key) return s[iloc] except KeyError: if (len(self) > 0 and (self.holds_integer() or self.is_boolean())): raise elif is_integer(key): return s[key] s = com.values_from_object(series) k = com.values_from_object(key) k = self._convert_scalar_indexer(k, kind='getitem') try: return self._engine.get_value(s, k, tz=getattr(series.dtype, 'tz', None)) except KeyError as e1: if len(self) > 0 and (self.holds_integer() or self.is_boolean()): raise try: return libindex.get_value_box(s, key) except IndexError: raise except TypeError: # generator/iterator-like if is_iterator(key): raise InvalidIndexError(key) else: raise e1 except Exception: # pragma: no cover raise e1 except TypeError: # python 3 if is_scalar(key): # pragma: no cover raise IndexError(key) raise InvalidIndexError(key)
[ "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", ",", "'_values'", ",", "series", ")", "if", "isinstance", "(", "s", ",", "(", "ExtensionArray", ",", "Index", ")", ")", "and", "is_scalar", "(", "key", ")", ":", "# GH 20882, 21257", "# Unify Index and ExtensionArray treatment", "# First try to convert the key to a location", "# If that fails, raise a KeyError if an integer", "# index, otherwise, see if key is an integer, and", "# try that", "try", ":", "iloc", "=", "self", ".", "get_loc", "(", "key", ")", "return", "s", "[", "iloc", "]", "except", "KeyError", ":", "if", "(", "len", "(", "self", ")", ">", "0", "and", "(", "self", ".", "holds_integer", "(", ")", "or", "self", ".", "is_boolean", "(", ")", ")", ")", ":", "raise", "elif", "is_integer", "(", "key", ")", ":", "return", "s", "[", "key", "]", "s", "=", "com", ".", "values_from_object", "(", "series", ")", "k", "=", "com", ".", "values_from_object", "(", "key", ")", "k", "=", "self", ".", "_convert_scalar_indexer", "(", "k", ",", "kind", "=", "'getitem'", ")", "try", ":", "return", "self", ".", "_engine", ".", "get_value", "(", "s", ",", "k", ",", "tz", "=", "getattr", "(", "series", ".", "dtype", ",", "'tz'", ",", "None", ")", ")", "except", "KeyError", "as", "e1", ":", "if", "len", "(", "self", ")", ">", "0", "and", "(", "self", ".", "holds_integer", "(", ")", "or", "self", ".", "is_boolean", "(", ")", ")", ":", "raise", "try", ":", "return", "libindex", ".", "get_value_box", "(", "s", ",", "key", ")", "except", "IndexError", ":", "raise", "except", "TypeError", ":", "# generator/iterator-like", "if", "is_iterator", "(", "key", ")", ":", "raise", "InvalidIndexError", "(", "key", ")", "else", ":", "raise", "e1", "except", "Exception", ":", "# pragma: no cover", "raise", "e1", "except", "TypeError", ":", "# python 3", "if", "is_scalar", "(", "key", ")", ":", "# pragma: no cover", "raise", "IndexError", "(", "key", ")", "raise", "InvalidIndexError", "(", "key", ")" ]
Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing.
[ "Fast", "lookup", "of", "value", "from", "1", "-", "dimensional", "ndarray", ".", "Only", "use", "this", "if", "you", "know", "what", "you", "re", "doing", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4335-L4389
19,427
pandas-dev/pandas
pandas/core/indexes/base.py
Index.set_value
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), value)
python
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), value)
[ "def", "set_value", "(", "self", ",", "arr", ",", "key", ",", "value", ")", ":", "self", ".", "_engine", ".", "set_value", "(", "com", ".", "values_from_object", "(", "arr", ")", ",", "com", ".", "values_from_object", "(", "key", ")", ",", "value", ")" ]
Fast lookup of value from 1-dimensional ndarray. Notes ----- Only use this if you know what you're doing.
[ "Fast", "lookup", "of", "value", "from", "1", "-", "dimensional", "ndarray", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4391-L4400
19,428
pandas-dev/pandas
pandas/core/indexes/base.py
Index.get_indexer_for
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, _ = self.get_indexer_non_unique(target, **kwargs) return indexer
python
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, _ = self.get_indexer_non_unique(target, **kwargs) return indexer
[ "def", "get_indexer_for", "(", "self", ",", "target", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "is_unique", ":", "return", "self", ".", "get_indexer", "(", "target", ",", "*", "*", "kwargs", ")", "indexer", ",", "_", "=", "self", ".", "get_indexer_non_unique", "(", "target", ",", "*", "*", "kwargs", ")", "return", "indexer" ]
Guaranteed return of an indexer even when non-unique. This dispatches to get_indexer or get_indexer_nonunique as appropriate.
[ "Guaranteed", "return", "of", "an", "indexer", "even", "when", "non", "-", "unique", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4440-L4450
19,429
pandas-dev/pandas
pandas/core/indexes/base.py
Index.groupby
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} """ # TODO: if we are a MultiIndex, we can do better # that converting to tuples if isinstance(values, ABCMultiIndex): values = values.values values = ensure_categorical(values) result = values._reverse_indexer() # map to the label result = {k: self.take(v) for k, v in result.items()} return result
python
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} """ # TODO: if we are a MultiIndex, we can do better # that converting to tuples if isinstance(values, ABCMultiIndex): values = values.values values = ensure_categorical(values) result = values._reverse_indexer() # map to the label result = {k: self.take(v) for k, v in result.items()} return result
[ "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", "=", "ensure_categorical", "(", "values", ")", "result", "=", "values", ".", "_reverse_indexer", "(", ")", "# map to the label", "result", "=", "{", "k", ":", "self", ".", "take", "(", "v", ")", "for", "k", ",", "v", "in", "result", ".", "items", "(", ")", "}", "return", "result" ]
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", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4462-L4487
19,430
pandas-dev/pandas
pandas/core/indexes/base.py
Index.isin
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. Parameters ---------- values : set or list-like Sought values. .. versionadded:: 0.18.1 Support for values as a set. level : str or int, optional Name or position of the index level to use (if the index is a `MultiIndex`). Returns ------- is_contained : ndarray NumPy array of boolean values. See Also -------- Series.isin : Same for Series. DataFrame.isin : Same method for DataFrames. Notes ----- In the case of `MultiIndex` you must either specify `values` as a list-like object containing tuples that are the same length as the number of levels, or specify `level`. Otherwise it will raise a ``ValueError``. If `level` is specified: - if it is the name of one *and only one* index level, use that level; - otherwise it should be a number indicating level position. Examples -------- >>> idx = pd.Index([1,2,3]) >>> idx Int64Index([1, 2, 3], dtype='int64') Check whether each index value in a list of values. >>> idx.isin([1, 4]) array([ True, False, False]) >>> midx = pd.MultiIndex.from_arrays([[1,2,3], ... ['red', 'blue', 'green']], ... names=('number', 'color')) >>> midx MultiIndex(levels=[[1, 2, 3], ['blue', 'green', 'red']], codes=[[0, 1, 2], [2, 0, 1]], names=['number', 'color']) Check whether the strings in the 'color' level of the MultiIndex are in a list of colors. >>> midx.isin(['red', 'orange', 'yellow'], level='color') array([ True, False, False]) To check across the levels of a MultiIndex, pass a list of tuples: >>> midx.isin([(1, 'red'), (3, 'red')]) array([ True, False, False]) For a DatetimeIndex, string values in `values` are converted to Timestamps. >>> dates = ['2000-03-11', '2000-03-12', '2000-03-13'] >>> dti = pd.to_datetime(dates) >>> dti DatetimeIndex(['2000-03-11', '2000-03-12', '2000-03-13'], dtype='datetime64[ns]', freq=None) >>> dti.isin(['2000-03-11']) array([ True, False, False]) """ if level is not None: self._validate_index_level(level) return algos.isin(self, values)
python
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. Parameters ---------- values : set or list-like Sought values. .. versionadded:: 0.18.1 Support for values as a set. level : str or int, optional Name or position of the index level to use (if the index is a `MultiIndex`). Returns ------- is_contained : ndarray NumPy array of boolean values. See Also -------- Series.isin : Same for Series. DataFrame.isin : Same method for DataFrames. Notes ----- In the case of `MultiIndex` you must either specify `values` as a list-like object containing tuples that are the same length as the number of levels, or specify `level`. Otherwise it will raise a ``ValueError``. If `level` is specified: - if it is the name of one *and only one* index level, use that level; - otherwise it should be a number indicating level position. Examples -------- >>> idx = pd.Index([1,2,3]) >>> idx Int64Index([1, 2, 3], dtype='int64') Check whether each index value in a list of values. >>> idx.isin([1, 4]) array([ True, False, False]) >>> midx = pd.MultiIndex.from_arrays([[1,2,3], ... ['red', 'blue', 'green']], ... names=('number', 'color')) >>> midx MultiIndex(levels=[[1, 2, 3], ['blue', 'green', 'red']], codes=[[0, 1, 2], [2, 0, 1]], names=['number', 'color']) Check whether the strings in the 'color' level of the MultiIndex are in a list of colors. >>> midx.isin(['red', 'orange', 'yellow'], level='color') array([ True, False, False]) To check across the levels of a MultiIndex, pass a list of tuples: >>> midx.isin([(1, 'red'), (3, 'red')]) array([ True, False, False]) For a DatetimeIndex, string values in `values` are converted to Timestamps. >>> dates = ['2000-03-11', '2000-03-12', '2000-03-13'] >>> dti = pd.to_datetime(dates) >>> dti DatetimeIndex(['2000-03-11', '2000-03-12', '2000-03-13'], dtype='datetime64[ns]', freq=None) >>> dti.isin(['2000-03-11']) array([ True, False, False]) """ if level is not None: self._validate_index_level(level) return algos.isin(self, values)
[ "def", "isin", "(", "self", ",", "values", ",", "level", "=", "None", ")", ":", "if", "level", "is", "not", "None", ":", "self", ".", "_validate_index_level", "(", "level", ")", "return", "algos", ".", "isin", "(", "self", ",", "values", ")" ]
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-like Sought values. .. versionadded:: 0.18.1 Support for values as a set. level : str or int, optional Name or position of the index level to use (if the index is a `MultiIndex`). Returns ------- is_contained : ndarray NumPy array of boolean values. See Also -------- Series.isin : Same for Series. DataFrame.isin : Same method for DataFrames. Notes ----- In the case of `MultiIndex` you must either specify `values` as a list-like object containing tuples that are the same length as the number of levels, or specify `level`. Otherwise it will raise a ``ValueError``. If `level` is specified: - if it is the name of one *and only one* index level, use that level; - otherwise it should be a number indicating level position. Examples -------- >>> idx = pd.Index([1,2,3]) >>> idx Int64Index([1, 2, 3], dtype='int64') Check whether each index value in a list of values. >>> idx.isin([1, 4]) array([ True, False, False]) >>> midx = pd.MultiIndex.from_arrays([[1,2,3], ... ['red', 'blue', 'green']], ... names=('number', 'color')) >>> midx MultiIndex(levels=[[1, 2, 3], ['blue', 'green', 'red']], codes=[[0, 1, 2], [2, 0, 1]], names=['number', 'color']) Check whether the strings in the 'color' level of the MultiIndex are in a list of colors. >>> midx.isin(['red', 'orange', 'yellow'], level='color') array([ True, False, False]) To check across the levels of a MultiIndex, pass a list of tuples: >>> midx.isin([(1, 'red'), (3, 'red')]) array([ True, False, False]) For a DatetimeIndex, string values in `values` are converted to Timestamps. >>> dates = ['2000-03-11', '2000-03-12', '2000-03-13'] >>> dti = pd.to_datetime(dates) >>> dti DatetimeIndex(['2000-03-11', '2000-03-12', '2000-03-13'], dtype='datetime64[ns]', freq=None) >>> dti.isin(['2000-03-11']) array([ True, False, False])
[ "Return", "a", "boolean", "array", "where", "the", "index", "values", "are", "in", "values", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4532-L4618
19,431
pandas-dev/pandas
pandas/core/indexes/base.py
Index.slice_indexer
def slice_indexer(self, start=None, end=None, step=None, kind=None): """ For an ordered or unique index, compute the slice indexer for input labels and step. Parameters ---------- start : label, default None If None, defaults to the beginning end : label, default None If None, defaults to the end step : int, default None kind : string, default None Returns ------- indexer : slice Raises ------ KeyError : If key does not exist, or key is not unique and index is not ordered. Notes ----- This function assumes that the data is sorted, so use at your own peril Examples --------- This is a method on all index types. For example you can do: >>> idx = pd.Index(list('abcd')) >>> idx.slice_indexer(start='b', end='c') slice(1, 3) >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')]) >>> idx.slice_indexer(start='b', end=('c', 'g')) slice(1, 3) """ start_slice, end_slice = self.slice_locs(start, end, step=step, kind=kind) # return a slice if not is_scalar(start_slice): raise AssertionError("Start slice bound is non-scalar") if not is_scalar(end_slice): raise AssertionError("End slice bound is non-scalar") return slice(start_slice, end_slice, step)
python
def slice_indexer(self, start=None, end=None, step=None, kind=None): """ For an ordered or unique index, compute the slice indexer for input labels and step. Parameters ---------- start : label, default None If None, defaults to the beginning end : label, default None If None, defaults to the end step : int, default None kind : string, default None Returns ------- indexer : slice Raises ------ KeyError : If key does not exist, or key is not unique and index is not ordered. Notes ----- This function assumes that the data is sorted, so use at your own peril Examples --------- This is a method on all index types. For example you can do: >>> idx = pd.Index(list('abcd')) >>> idx.slice_indexer(start='b', end='c') slice(1, 3) >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')]) >>> idx.slice_indexer(start='b', end=('c', 'g')) slice(1, 3) """ start_slice, end_slice = self.slice_locs(start, end, step=step, kind=kind) # return a slice if not is_scalar(start_slice): raise AssertionError("Start slice bound is non-scalar") if not is_scalar(end_slice): raise AssertionError("End slice bound is non-scalar") return slice(start_slice, end_slice, step)
[ "def", "slice_indexer", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "step", "=", "None", ",", "kind", "=", "None", ")", ":", "start_slice", ",", "end_slice", "=", "self", ".", "slice_locs", "(", "start", ",", "end", ",", "step", "=", "step", ",", "kind", "=", "kind", ")", "# return a slice", "if", "not", "is_scalar", "(", "start_slice", ")", ":", "raise", "AssertionError", "(", "\"Start slice bound is non-scalar\"", ")", "if", "not", "is_scalar", "(", "end_slice", ")", ":", "raise", "AssertionError", "(", "\"End slice bound is non-scalar\"", ")", "return", "slice", "(", "start_slice", ",", "end_slice", ",", "step", ")" ]
For an ordered or unique index, compute the slice indexer for input labels and step. Parameters ---------- start : label, default None If None, defaults to the beginning end : label, default None If None, defaults to the end step : int, default None kind : string, default None Returns ------- indexer : slice Raises ------ KeyError : If key does not exist, or key is not unique and index is not ordered. Notes ----- This function assumes that the data is sorted, so use at your own peril Examples --------- This is a method on all index types. For example you can do: >>> idx = pd.Index(list('abcd')) >>> idx.slice_indexer(start='b', end='c') slice(1, 3) >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')]) >>> idx.slice_indexer(start='b', end=('c', 'g')) slice(1, 3)
[ "For", "an", "ordered", "or", "unique", "index", "compute", "the", "slice", "indexer", "for", "input", "labels", "and", "step", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4625-L4673
19,432
pandas-dev/pandas
pandas/core/indexes/base.py
Index._maybe_cast_indexer
def _maybe_cast_indexer(self, key): """ If we have a float key and are not a floating index, then try to cast to an int if equivalent. """ if is_float(key) and not self.is_floating(): try: ckey = int(key) if ckey == key: key = ckey except (OverflowError, ValueError, TypeError): pass return key
python
def _maybe_cast_indexer(self, key): """ If we have a float key and are not a floating index, then try to cast to an int if equivalent. """ if is_float(key) and not self.is_floating(): try: ckey = int(key) if ckey == key: key = ckey except (OverflowError, ValueError, TypeError): pass return key
[ "def", "_maybe_cast_indexer", "(", "self", ",", "key", ")", ":", "if", "is_float", "(", "key", ")", "and", "not", "self", ".", "is_floating", "(", ")", ":", "try", ":", "ckey", "=", "int", "(", "key", ")", "if", "ckey", "==", "key", ":", "key", "=", "ckey", "except", "(", "OverflowError", ",", "ValueError", ",", "TypeError", ")", ":", "pass", "return", "key" ]
If we have a float key and are not a floating index, then try to cast to an int if equivalent.
[ "If", "we", "have", "a", "float", "key", "and", "are", "not", "a", "floating", "index", "then", "try", "to", "cast", "to", "an", "int", "if", "equivalent", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4675-L4688
19,433
pandas-dev/pandas
pandas/core/indexes/base.py
Index._validate_indexer
def _validate_indexer(self, form, key, kind): """ If we are positional indexer, validate that we have appropriate typed bounds must be an integer. """ assert kind in ['ix', 'loc', 'getitem', 'iloc'] if key is None: pass elif is_integer(key): pass elif kind in ['iloc', 'getitem']: self._invalid_indexer(form, key) return key
python
def _validate_indexer(self, form, key, kind): """ If we are positional indexer, validate that we have appropriate typed bounds must be an integer. """ assert kind in ['ix', 'loc', 'getitem', 'iloc'] if key is None: pass elif is_integer(key): pass elif kind in ['iloc', 'getitem']: self._invalid_indexer(form, key) return key
[ "def", "_validate_indexer", "(", "self", ",", "form", ",", "key", ",", "kind", ")", ":", "assert", "kind", "in", "[", "'ix'", ",", "'loc'", ",", "'getitem'", ",", "'iloc'", "]", "if", "key", "is", "None", ":", "pass", "elif", "is_integer", "(", "key", ")", ":", "pass", "elif", "kind", "in", "[", "'iloc'", ",", "'getitem'", "]", ":", "self", ".", "_invalid_indexer", "(", "form", ",", "key", ")", "return", "key" ]
If we are positional indexer, validate that we have appropriate typed bounds must be an integer.
[ "If", "we", "are", "positional", "indexer", "validate", "that", "we", "have", "appropriate", "typed", "bounds", "must", "be", "an", "integer", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4690-L4703
19,434
pandas-dev/pandas
pandas/core/indexes/base.py
Index.get_slice_bound
def get_slice_bound(self, label, side, kind): """ Calculate slice bound that corresponds to given label. Returns leftmost (one-past-the-rightmost if ``side=='right'``) position of given label. Parameters ---------- label : object side : {'left', 'right'} kind : {'ix', 'loc', 'getitem'} """ assert kind in ['ix', 'loc', 'getitem', None] if side not in ('left', 'right'): raise ValueError("Invalid value for side kwarg," " must be either 'left' or 'right': %s" % (side, )) original_label = label # For datetime indices label may be a string that has to be converted # to datetime boundary according to its resolution. label = self._maybe_cast_slice_bound(label, side, kind) # we need to look up the label try: slc = self._get_loc_only_exact_matches(label) except KeyError as err: try: return self._searchsorted_monotonic(label, side) except ValueError: # raise the original KeyError raise err if isinstance(slc, np.ndarray): # get_loc may return a boolean array or an array of indices, which # is OK as long as they are representable by a slice. if is_bool_dtype(slc): slc = lib.maybe_booleans_to_slice(slc.view('u1')) else: slc = lib.maybe_indices_to_slice(slc.astype('i8'), len(self)) if isinstance(slc, np.ndarray): raise KeyError("Cannot get %s slice bound for non-unique " "label: %r" % (side, original_label)) if isinstance(slc, slice): if side == 'left': return slc.start else: return slc.stop else: if side == 'right': return slc + 1 else: return slc
python
def get_slice_bound(self, label, side, kind): """ Calculate slice bound that corresponds to given label. Returns leftmost (one-past-the-rightmost if ``side=='right'``) position of given label. Parameters ---------- label : object side : {'left', 'right'} kind : {'ix', 'loc', 'getitem'} """ assert kind in ['ix', 'loc', 'getitem', None] if side not in ('left', 'right'): raise ValueError("Invalid value for side kwarg," " must be either 'left' or 'right': %s" % (side, )) original_label = label # For datetime indices label may be a string that has to be converted # to datetime boundary according to its resolution. label = self._maybe_cast_slice_bound(label, side, kind) # we need to look up the label try: slc = self._get_loc_only_exact_matches(label) except KeyError as err: try: return self._searchsorted_monotonic(label, side) except ValueError: # raise the original KeyError raise err if isinstance(slc, np.ndarray): # get_loc may return a boolean array or an array of indices, which # is OK as long as they are representable by a slice. if is_bool_dtype(slc): slc = lib.maybe_booleans_to_slice(slc.view('u1')) else: slc = lib.maybe_indices_to_slice(slc.astype('i8'), len(self)) if isinstance(slc, np.ndarray): raise KeyError("Cannot get %s slice bound for non-unique " "label: %r" % (side, original_label)) if isinstance(slc, slice): if side == 'left': return slc.start else: return slc.stop else: if side == 'right': return slc + 1 else: return slc
[ "def", "get_slice_bound", "(", "self", ",", "label", ",", "side", ",", "kind", ")", ":", "assert", "kind", "in", "[", "'ix'", ",", "'loc'", ",", "'getitem'", ",", "None", "]", "if", "side", "not", "in", "(", "'left'", ",", "'right'", ")", ":", "raise", "ValueError", "(", "\"Invalid value for side kwarg,\"", "\" must be either 'left' or 'right': %s\"", "%", "(", "side", ",", ")", ")", "original_label", "=", "label", "# For datetime indices label may be a string that has to be converted", "# to datetime boundary according to its resolution.", "label", "=", "self", ".", "_maybe_cast_slice_bound", "(", "label", ",", "side", ",", "kind", ")", "# we need to look up the label", "try", ":", "slc", "=", "self", ".", "_get_loc_only_exact_matches", "(", "label", ")", "except", "KeyError", "as", "err", ":", "try", ":", "return", "self", ".", "_searchsorted_monotonic", "(", "label", ",", "side", ")", "except", "ValueError", ":", "# raise the original KeyError", "raise", "err", "if", "isinstance", "(", "slc", ",", "np", ".", "ndarray", ")", ":", "# get_loc may return a boolean array or an array of indices, which", "# is OK as long as they are representable by a slice.", "if", "is_bool_dtype", "(", "slc", ")", ":", "slc", "=", "lib", ".", "maybe_booleans_to_slice", "(", "slc", ".", "view", "(", "'u1'", ")", ")", "else", ":", "slc", "=", "lib", ".", "maybe_indices_to_slice", "(", "slc", ".", "astype", "(", "'i8'", ")", ",", "len", "(", "self", ")", ")", "if", "isinstance", "(", "slc", ",", "np", ".", "ndarray", ")", ":", "raise", "KeyError", "(", "\"Cannot get %s slice bound for non-unique \"", "\"label: %r\"", "%", "(", "side", ",", "original_label", ")", ")", "if", "isinstance", "(", "slc", ",", "slice", ")", ":", "if", "side", "==", "'left'", ":", "return", "slc", ".", "start", "else", ":", "return", "slc", ".", "stop", "else", ":", "if", "side", "==", "'right'", ":", "return", "slc", "+", "1", "else", ":", "return", "slc" ]
Calculate slice bound that corresponds to given label. Returns leftmost (one-past-the-rightmost if ``side=='right'``) position of given label. Parameters ---------- label : object side : {'left', 'right'} kind : {'ix', 'loc', 'getitem'}
[ "Calculate", "slice", "bound", "that", "corresponds", "to", "given", "label", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4766-L4822
19,435
pandas-dev/pandas
pandas/core/indexes/base.py
Index.slice_locs
def slice_locs(self, start=None, end=None, step=None, kind=None): """ Compute slice locations for input labels. Parameters ---------- start : label, default None If None, defaults to the beginning end : label, default None If None, defaults to the end step : int, defaults None If None, defaults to 1 kind : {'ix', 'loc', 'getitem'} or None Returns ------- start, end : int See Also -------- Index.get_loc : Get location for a single label. Notes ----- This method only works if the index is monotonic or unique. Examples --------- >>> idx = pd.Index(list('abcd')) >>> idx.slice_locs(start='b', end='c') (1, 3) """ inc = (step is None or step >= 0) if not inc: # If it's a reverse slice, temporarily swap bounds. start, end = end, start # GH 16785: If start and end happen to be date strings with UTC offsets # attempt to parse and check that the offsets are the same if (isinstance(start, (str, datetime)) and isinstance(end, (str, datetime))): try: ts_start = Timestamp(start) ts_end = Timestamp(end) except (ValueError, TypeError): pass else: if not tz_compare(ts_start.tzinfo, ts_end.tzinfo): raise ValueError("Both dates must have the " "same UTC offset") start_slice = None if start is not None: start_slice = self.get_slice_bound(start, 'left', kind) if start_slice is None: start_slice = 0 end_slice = None if end is not None: end_slice = self.get_slice_bound(end, 'right', kind) if end_slice is None: end_slice = len(self) if not inc: # Bounds at this moment are swapped, swap them back and shift by 1. # # slice_locs('B', 'A', step=-1): s='B', e='A' # # s='A' e='B' # AFTER SWAP: | | # v ------------------> V # ----------------------------------- # | | |A|A|A|A| | | | | |B|B| | | | | # ----------------------------------- # ^ <------------------ ^ # SHOULD BE: | | # end=s-1 start=e-1 # end_slice, start_slice = start_slice - 1, end_slice - 1 # i == -1 triggers ``len(self) + i`` selection that points to the # last element, not before-the-first one, subtracting len(self) # compensates that. if end_slice == -1: end_slice -= len(self) if start_slice == -1: start_slice -= len(self) return start_slice, end_slice
python
def slice_locs(self, start=None, end=None, step=None, kind=None): """ Compute slice locations for input labels. Parameters ---------- start : label, default None If None, defaults to the beginning end : label, default None If None, defaults to the end step : int, defaults None If None, defaults to 1 kind : {'ix', 'loc', 'getitem'} or None Returns ------- start, end : int See Also -------- Index.get_loc : Get location for a single label. Notes ----- This method only works if the index is monotonic or unique. Examples --------- >>> idx = pd.Index(list('abcd')) >>> idx.slice_locs(start='b', end='c') (1, 3) """ inc = (step is None or step >= 0) if not inc: # If it's a reverse slice, temporarily swap bounds. start, end = end, start # GH 16785: If start and end happen to be date strings with UTC offsets # attempt to parse and check that the offsets are the same if (isinstance(start, (str, datetime)) and isinstance(end, (str, datetime))): try: ts_start = Timestamp(start) ts_end = Timestamp(end) except (ValueError, TypeError): pass else: if not tz_compare(ts_start.tzinfo, ts_end.tzinfo): raise ValueError("Both dates must have the " "same UTC offset") start_slice = None if start is not None: start_slice = self.get_slice_bound(start, 'left', kind) if start_slice is None: start_slice = 0 end_slice = None if end is not None: end_slice = self.get_slice_bound(end, 'right', kind) if end_slice is None: end_slice = len(self) if not inc: # Bounds at this moment are swapped, swap them back and shift by 1. # # slice_locs('B', 'A', step=-1): s='B', e='A' # # s='A' e='B' # AFTER SWAP: | | # v ------------------> V # ----------------------------------- # | | |A|A|A|A| | | | | |B|B| | | | | # ----------------------------------- # ^ <------------------ ^ # SHOULD BE: | | # end=s-1 start=e-1 # end_slice, start_slice = start_slice - 1, end_slice - 1 # i == -1 triggers ``len(self) + i`` selection that points to the # last element, not before-the-first one, subtracting len(self) # compensates that. if end_slice == -1: end_slice -= len(self) if start_slice == -1: start_slice -= len(self) return start_slice, end_slice
[ "def", "slice_locs", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "step", "=", "None", ",", "kind", "=", "None", ")", ":", "inc", "=", "(", "step", "is", "None", "or", "step", ">=", "0", ")", "if", "not", "inc", ":", "# If it's a reverse slice, temporarily swap bounds.", "start", ",", "end", "=", "end", ",", "start", "# GH 16785: If start and end happen to be date strings with UTC offsets", "# attempt to parse and check that the offsets are the same", "if", "(", "isinstance", "(", "start", ",", "(", "str", ",", "datetime", ")", ")", "and", "isinstance", "(", "end", ",", "(", "str", ",", "datetime", ")", ")", ")", ":", "try", ":", "ts_start", "=", "Timestamp", "(", "start", ")", "ts_end", "=", "Timestamp", "(", "end", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", "else", ":", "if", "not", "tz_compare", "(", "ts_start", ".", "tzinfo", ",", "ts_end", ".", "tzinfo", ")", ":", "raise", "ValueError", "(", "\"Both dates must have the \"", "\"same UTC offset\"", ")", "start_slice", "=", "None", "if", "start", "is", "not", "None", ":", "start_slice", "=", "self", ".", "get_slice_bound", "(", "start", ",", "'left'", ",", "kind", ")", "if", "start_slice", "is", "None", ":", "start_slice", "=", "0", "end_slice", "=", "None", "if", "end", "is", "not", "None", ":", "end_slice", "=", "self", ".", "get_slice_bound", "(", "end", ",", "'right'", ",", "kind", ")", "if", "end_slice", "is", "None", ":", "end_slice", "=", "len", "(", "self", ")", "if", "not", "inc", ":", "# Bounds at this moment are swapped, swap them back and shift by 1.", "#", "# slice_locs('B', 'A', step=-1): s='B', e='A'", "#", "# s='A' e='B'", "# AFTER SWAP: | |", "# v ------------------> V", "# -----------------------------------", "# | | |A|A|A|A| | | | | |B|B| | | | |", "# -----------------------------------", "# ^ <------------------ ^", "# SHOULD BE: | |", "# end=s-1 start=e-1", "#", "end_slice", ",", "start_slice", "=", "start_slice", "-", "1", ",", "end_slice", "-", "1", "# i == -1 triggers ``len(self) + i`` selection that points to the", "# last element, not before-the-first one, subtracting len(self)", "# compensates that.", "if", "end_slice", "==", "-", "1", ":", "end_slice", "-=", "len", "(", "self", ")", "if", "start_slice", "==", "-", "1", ":", "start_slice", "-=", "len", "(", "self", ")", "return", "start_slice", ",", "end_slice" ]
Compute slice locations for input labels. Parameters ---------- start : label, default None If None, defaults to the beginning end : label, default None If None, defaults to the end step : int, defaults None If None, defaults to 1 kind : {'ix', 'loc', 'getitem'} or None Returns ------- start, end : int See Also -------- Index.get_loc : Get location for a single label. Notes ----- This method only works if the index is monotonic or unique. Examples --------- >>> idx = pd.Index(list('abcd')) >>> idx.slice_locs(start='b', end='c') (1, 3)
[ "Compute", "slice", "locations", "for", "input", "labels", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4824-L4913
19,436
pandas-dev/pandas
pandas/core/indexes/base.py
Index.insert
def insert(self, loc, item): """ Make new Index inserting new item at location. Follows Python list.append semantics for negative values. Parameters ---------- loc : int item : object Returns ------- new_index : Index """ _self = np.asarray(self) item = self._coerce_scalar_to_index(item)._ndarray_values idx = np.concatenate((_self[:loc], item, _self[loc:])) return self._shallow_copy_with_infer(idx)
python
def insert(self, loc, item): """ Make new Index inserting new item at location. Follows Python list.append semantics for negative values. Parameters ---------- loc : int item : object Returns ------- new_index : Index """ _self = np.asarray(self) item = self._coerce_scalar_to_index(item)._ndarray_values idx = np.concatenate((_self[:loc], item, _self[loc:])) return self._shallow_copy_with_infer(idx)
[ "def", "insert", "(", "self", ",", "loc", ",", "item", ")", ":", "_self", "=", "np", ".", "asarray", "(", "self", ")", "item", "=", "self", ".", "_coerce_scalar_to_index", "(", "item", ")", ".", "_ndarray_values", "idx", "=", "np", ".", "concatenate", "(", "(", "_self", "[", ":", "loc", "]", ",", "item", ",", "_self", "[", "loc", ":", "]", ")", ")", "return", "self", ".", "_shallow_copy_with_infer", "(", "idx", ")" ]
Make new Index inserting new item at location. Follows Python list.append semantics for negative values. Parameters ---------- loc : int item : object Returns ------- new_index : Index
[ "Make", "new", "Index", "inserting", "new", "item", "at", "location", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4925-L4943
19,437
pandas-dev/pandas
pandas/core/indexes/base.py
Index.drop
def drop(self, labels, errors='raise'): """ Make new Index with passed list of labels deleted. Parameters ---------- labels : array-like errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and existing labels are dropped. Returns ------- dropped : Index Raises ------ KeyError If not all of the labels are found in the selected axis """ arr_dtype = 'object' if self.dtype == 'object' else None labels = com.index_labels_to_array(labels, dtype=arr_dtype) indexer = self.get_indexer(labels) mask = indexer == -1 if mask.any(): if errors != 'ignore': raise KeyError( '{} not found in axis'.format(labels[mask])) indexer = indexer[~mask] return self.delete(indexer)
python
def drop(self, labels, errors='raise'): """ Make new Index with passed list of labels deleted. Parameters ---------- labels : array-like errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and existing labels are dropped. Returns ------- dropped : Index Raises ------ KeyError If not all of the labels are found in the selected axis """ arr_dtype = 'object' if self.dtype == 'object' else None labels = com.index_labels_to_array(labels, dtype=arr_dtype) indexer = self.get_indexer(labels) mask = indexer == -1 if mask.any(): if errors != 'ignore': raise KeyError( '{} not found in axis'.format(labels[mask])) indexer = indexer[~mask] return self.delete(indexer)
[ "def", "drop", "(", "self", ",", "labels", ",", "errors", "=", "'raise'", ")", ":", "arr_dtype", "=", "'object'", "if", "self", ".", "dtype", "==", "'object'", "else", "None", "labels", "=", "com", ".", "index_labels_to_array", "(", "labels", ",", "dtype", "=", "arr_dtype", ")", "indexer", "=", "self", ".", "get_indexer", "(", "labels", ")", "mask", "=", "indexer", "==", "-", "1", "if", "mask", ".", "any", "(", ")", ":", "if", "errors", "!=", "'ignore'", ":", "raise", "KeyError", "(", "'{} not found in axis'", ".", "format", "(", "labels", "[", "mask", "]", ")", ")", "indexer", "=", "indexer", "[", "~", "mask", "]", "return", "self", ".", "delete", "(", "indexer", ")" ]
Make new Index with passed list of labels deleted. Parameters ---------- labels : array-like errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and existing labels are dropped. Returns ------- dropped : Index Raises ------ KeyError If not all of the labels are found in the selected axis
[ "Make", "new", "Index", "with", "passed", "list", "of", "labels", "deleted", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L4945-L4973
19,438
pandas-dev/pandas
pandas/core/indexes/base.py
Index._add_comparison_methods
def _add_comparison_methods(cls): """ Add in comparison methods. """ cls.__eq__ = _make_comparison_op(operator.eq, cls) cls.__ne__ = _make_comparison_op(operator.ne, cls) cls.__lt__ = _make_comparison_op(operator.lt, cls) cls.__gt__ = _make_comparison_op(operator.gt, cls) cls.__le__ = _make_comparison_op(operator.le, cls) cls.__ge__ = _make_comparison_op(operator.ge, cls)
python
def _add_comparison_methods(cls): """ Add in comparison methods. """ cls.__eq__ = _make_comparison_op(operator.eq, cls) cls.__ne__ = _make_comparison_op(operator.ne, cls) cls.__lt__ = _make_comparison_op(operator.lt, cls) cls.__gt__ = _make_comparison_op(operator.gt, cls) cls.__le__ = _make_comparison_op(operator.le, cls) cls.__ge__ = _make_comparison_op(operator.ge, cls)
[ "def", "_add_comparison_methods", "(", "cls", ")", ":", "cls", ".", "__eq__", "=", "_make_comparison_op", "(", "operator", ".", "eq", ",", "cls", ")", "cls", ".", "__ne__", "=", "_make_comparison_op", "(", "operator", ".", "ne", ",", "cls", ")", "cls", ".", "__lt__", "=", "_make_comparison_op", "(", "operator", ".", "lt", ",", "cls", ")", "cls", ".", "__gt__", "=", "_make_comparison_op", "(", "operator", ".", "gt", ",", "cls", ")", "cls", ".", "__le__", "=", "_make_comparison_op", "(", "operator", ".", "le", ",", "cls", ")", "cls", ".", "__ge__", "=", "_make_comparison_op", "(", "operator", ".", "ge", ",", "cls", ")" ]
Add in comparison methods.
[ "Add", "in", "comparison", "methods", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5004-L5013
19,439
pandas-dev/pandas
pandas/core/indexes/base.py
Index._validate_for_numeric_unaryop
def _validate_for_numeric_unaryop(self, op, opstr): """ Validate if we can perform a numeric unary operation. """ if not self._is_numeric_dtype: raise TypeError("cannot evaluate a numeric op " "{opstr} for type: {typ}" .format(opstr=opstr, typ=type(self).__name__))
python
def _validate_for_numeric_unaryop(self, op, opstr): """ Validate if we can perform a numeric unary operation. """ if not self._is_numeric_dtype: raise TypeError("cannot evaluate a numeric op " "{opstr} for type: {typ}" .format(opstr=opstr, typ=type(self).__name__))
[ "def", "_validate_for_numeric_unaryop", "(", "self", ",", "op", ",", "opstr", ")", ":", "if", "not", "self", ".", "_is_numeric_dtype", ":", "raise", "TypeError", "(", "\"cannot evaluate a numeric op \"", "\"{opstr} for type: {typ}\"", ".", "format", "(", "opstr", "=", "opstr", ",", "typ", "=", "type", "(", "self", ")", ".", "__name__", ")", ")" ]
Validate if we can perform a numeric unary operation.
[ "Validate", "if", "we", "can", "perform", "a", "numeric", "unary", "operation", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5053-L5060
19,440
pandas-dev/pandas
pandas/core/indexes/base.py
Index._validate_for_numeric_binop
def _validate_for_numeric_binop(self, other, op): """ Return valid other; evaluate or raise TypeError if we are not of the appropriate type. Notes ----- This is an internal method called by ops. """ opstr = '__{opname}__'.format(opname=op.__name__) # if we are an inheritor of numeric, # but not actually numeric (e.g. DatetimeIndex/PeriodIndex) if not self._is_numeric_dtype: raise TypeError("cannot evaluate a numeric op {opstr} " "for type: {typ}" .format(opstr=opstr, typ=type(self).__name__)) if isinstance(other, Index): if not other._is_numeric_dtype: raise TypeError("cannot evaluate a numeric op " "{opstr} with type: {typ}" .format(opstr=opstr, typ=type(other))) elif isinstance(other, np.ndarray) and not other.ndim: other = other.item() if isinstance(other, (Index, ABCSeries, np.ndarray)): if len(self) != len(other): raise ValueError("cannot evaluate a numeric op with " "unequal lengths") other = com.values_from_object(other) if other.dtype.kind not in ['f', 'i', 'u']: raise TypeError("cannot evaluate a numeric op " "with a non-numeric dtype") elif isinstance(other, (ABCDateOffset, np.timedelta64, timedelta)): # higher up to handle pass elif isinstance(other, (datetime, np.datetime64)): # higher up to handle pass else: if not (is_float(other) or is_integer(other)): raise TypeError("can only perform ops with scalar values") return other
python
def _validate_for_numeric_binop(self, other, op): """ Return valid other; evaluate or raise TypeError if we are not of the appropriate type. Notes ----- This is an internal method called by ops. """ opstr = '__{opname}__'.format(opname=op.__name__) # if we are an inheritor of numeric, # but not actually numeric (e.g. DatetimeIndex/PeriodIndex) if not self._is_numeric_dtype: raise TypeError("cannot evaluate a numeric op {opstr} " "for type: {typ}" .format(opstr=opstr, typ=type(self).__name__)) if isinstance(other, Index): if not other._is_numeric_dtype: raise TypeError("cannot evaluate a numeric op " "{opstr} with type: {typ}" .format(opstr=opstr, typ=type(other))) elif isinstance(other, np.ndarray) and not other.ndim: other = other.item() if isinstance(other, (Index, ABCSeries, np.ndarray)): if len(self) != len(other): raise ValueError("cannot evaluate a numeric op with " "unequal lengths") other = com.values_from_object(other) if other.dtype.kind not in ['f', 'i', 'u']: raise TypeError("cannot evaluate a numeric op " "with a non-numeric dtype") elif isinstance(other, (ABCDateOffset, np.timedelta64, timedelta)): # higher up to handle pass elif isinstance(other, (datetime, np.datetime64)): # higher up to handle pass else: if not (is_float(other) or is_integer(other)): raise TypeError("can only perform ops with scalar values") return other
[ "def", "_validate_for_numeric_binop", "(", "self", ",", "other", ",", "op", ")", ":", "opstr", "=", "'__{opname}__'", ".", "format", "(", "opname", "=", "op", ".", "__name__", ")", "# if we are an inheritor of numeric,", "# but not actually numeric (e.g. DatetimeIndex/PeriodIndex)", "if", "not", "self", ".", "_is_numeric_dtype", ":", "raise", "TypeError", "(", "\"cannot evaluate a numeric op {opstr} \"", "\"for type: {typ}\"", ".", "format", "(", "opstr", "=", "opstr", ",", "typ", "=", "type", "(", "self", ")", ".", "__name__", ")", ")", "if", "isinstance", "(", "other", ",", "Index", ")", ":", "if", "not", "other", ".", "_is_numeric_dtype", ":", "raise", "TypeError", "(", "\"cannot evaluate a numeric op \"", "\"{opstr} with type: {typ}\"", ".", "format", "(", "opstr", "=", "opstr", ",", "typ", "=", "type", "(", "other", ")", ")", ")", "elif", "isinstance", "(", "other", ",", "np", ".", "ndarray", ")", "and", "not", "other", ".", "ndim", ":", "other", "=", "other", ".", "item", "(", ")", "if", "isinstance", "(", "other", ",", "(", "Index", ",", "ABCSeries", ",", "np", ".", "ndarray", ")", ")", ":", "if", "len", "(", "self", ")", "!=", "len", "(", "other", ")", ":", "raise", "ValueError", "(", "\"cannot evaluate a numeric op with \"", "\"unequal lengths\"", ")", "other", "=", "com", ".", "values_from_object", "(", "other", ")", "if", "other", ".", "dtype", ".", "kind", "not", "in", "[", "'f'", ",", "'i'", ",", "'u'", "]", ":", "raise", "TypeError", "(", "\"cannot evaluate a numeric op \"", "\"with a non-numeric dtype\"", ")", "elif", "isinstance", "(", "other", ",", "(", "ABCDateOffset", ",", "np", ".", "timedelta64", ",", "timedelta", ")", ")", ":", "# higher up to handle", "pass", "elif", "isinstance", "(", "other", ",", "(", "datetime", ",", "np", ".", "datetime64", ")", ")", ":", "# higher up to handle", "pass", "else", ":", "if", "not", "(", "is_float", "(", "other", ")", "or", "is_integer", "(", "other", ")", ")", ":", "raise", "TypeError", "(", "\"can only perform ops with scalar values\"", ")", "return", "other" ]
Return valid other; evaluate or raise TypeError if we are not of the appropriate type. Notes ----- This is an internal method called by ops.
[ "Return", "valid", "other", ";", "evaluate", "or", "raise", "TypeError", "if", "we", "are", "not", "of", "the", "appropriate", "type", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5062-L5105
19,441
pandas-dev/pandas
pandas/core/indexes/base.py
Index._add_numeric_methods_binary
def _add_numeric_methods_binary(cls): """ Add in numeric methods. """ cls.__add__ = _make_arithmetic_op(operator.add, cls) cls.__radd__ = _make_arithmetic_op(ops.radd, cls) cls.__sub__ = _make_arithmetic_op(operator.sub, cls) cls.__rsub__ = _make_arithmetic_op(ops.rsub, cls) cls.__rpow__ = _make_arithmetic_op(ops.rpow, cls) cls.__pow__ = _make_arithmetic_op(operator.pow, cls) cls.__truediv__ = _make_arithmetic_op(operator.truediv, cls) cls.__rtruediv__ = _make_arithmetic_op(ops.rtruediv, cls) # TODO: rmod? rdivmod? cls.__mod__ = _make_arithmetic_op(operator.mod, cls) cls.__floordiv__ = _make_arithmetic_op(operator.floordiv, cls) cls.__rfloordiv__ = _make_arithmetic_op(ops.rfloordiv, cls) cls.__divmod__ = _make_arithmetic_op(divmod, cls) cls.__mul__ = _make_arithmetic_op(operator.mul, cls) cls.__rmul__ = _make_arithmetic_op(ops.rmul, cls)
python
def _add_numeric_methods_binary(cls): """ Add in numeric methods. """ cls.__add__ = _make_arithmetic_op(operator.add, cls) cls.__radd__ = _make_arithmetic_op(ops.radd, cls) cls.__sub__ = _make_arithmetic_op(operator.sub, cls) cls.__rsub__ = _make_arithmetic_op(ops.rsub, cls) cls.__rpow__ = _make_arithmetic_op(ops.rpow, cls) cls.__pow__ = _make_arithmetic_op(operator.pow, cls) cls.__truediv__ = _make_arithmetic_op(operator.truediv, cls) cls.__rtruediv__ = _make_arithmetic_op(ops.rtruediv, cls) # TODO: rmod? rdivmod? cls.__mod__ = _make_arithmetic_op(operator.mod, cls) cls.__floordiv__ = _make_arithmetic_op(operator.floordiv, cls) cls.__rfloordiv__ = _make_arithmetic_op(ops.rfloordiv, cls) cls.__divmod__ = _make_arithmetic_op(divmod, cls) cls.__mul__ = _make_arithmetic_op(operator.mul, cls) cls.__rmul__ = _make_arithmetic_op(ops.rmul, cls)
[ "def", "_add_numeric_methods_binary", "(", "cls", ")", ":", "cls", ".", "__add__", "=", "_make_arithmetic_op", "(", "operator", ".", "add", ",", "cls", ")", "cls", ".", "__radd__", "=", "_make_arithmetic_op", "(", "ops", ".", "radd", ",", "cls", ")", "cls", ".", "__sub__", "=", "_make_arithmetic_op", "(", "operator", ".", "sub", ",", "cls", ")", "cls", ".", "__rsub__", "=", "_make_arithmetic_op", "(", "ops", ".", "rsub", ",", "cls", ")", "cls", ".", "__rpow__", "=", "_make_arithmetic_op", "(", "ops", ".", "rpow", ",", "cls", ")", "cls", ".", "__pow__", "=", "_make_arithmetic_op", "(", "operator", ".", "pow", ",", "cls", ")", "cls", ".", "__truediv__", "=", "_make_arithmetic_op", "(", "operator", ".", "truediv", ",", "cls", ")", "cls", ".", "__rtruediv__", "=", "_make_arithmetic_op", "(", "ops", ".", "rtruediv", ",", "cls", ")", "# TODO: rmod? rdivmod?", "cls", ".", "__mod__", "=", "_make_arithmetic_op", "(", "operator", ".", "mod", ",", "cls", ")", "cls", ".", "__floordiv__", "=", "_make_arithmetic_op", "(", "operator", ".", "floordiv", ",", "cls", ")", "cls", ".", "__rfloordiv__", "=", "_make_arithmetic_op", "(", "ops", ".", "rfloordiv", ",", "cls", ")", "cls", ".", "__divmod__", "=", "_make_arithmetic_op", "(", "divmod", ",", "cls", ")", "cls", ".", "__mul__", "=", "_make_arithmetic_op", "(", "operator", ".", "mul", ",", "cls", ")", "cls", ".", "__rmul__", "=", "_make_arithmetic_op", "(", "ops", ".", "rmul", ",", "cls", ")" ]
Add in numeric methods.
[ "Add", "in", "numeric", "methods", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5108-L5128
19,442
pandas-dev/pandas
pandas/core/indexes/base.py
Index._add_numeric_methods_unary
def _add_numeric_methods_unary(cls): """ Add in numeric unary methods. """ def _make_evaluate_unary(op, opstr): def _evaluate_numeric_unary(self): self._validate_for_numeric_unaryop(op, opstr) attrs = self._get_attributes_dict() attrs = self._maybe_update_attributes(attrs) return Index(op(self.values), **attrs) _evaluate_numeric_unary.__name__ = opstr return _evaluate_numeric_unary cls.__neg__ = _make_evaluate_unary(operator.neg, '__neg__') cls.__pos__ = _make_evaluate_unary(operator.pos, '__pos__') cls.__abs__ = _make_evaluate_unary(np.abs, '__abs__') cls.__inv__ = _make_evaluate_unary(lambda x: -x, '__inv__')
python
def _add_numeric_methods_unary(cls): """ Add in numeric unary methods. """ def _make_evaluate_unary(op, opstr): def _evaluate_numeric_unary(self): self._validate_for_numeric_unaryop(op, opstr) attrs = self._get_attributes_dict() attrs = self._maybe_update_attributes(attrs) return Index(op(self.values), **attrs) _evaluate_numeric_unary.__name__ = opstr return _evaluate_numeric_unary cls.__neg__ = _make_evaluate_unary(operator.neg, '__neg__') cls.__pos__ = _make_evaluate_unary(operator.pos, '__pos__') cls.__abs__ = _make_evaluate_unary(np.abs, '__abs__') cls.__inv__ = _make_evaluate_unary(lambda x: -x, '__inv__')
[ "def", "_add_numeric_methods_unary", "(", "cls", ")", ":", "def", "_make_evaluate_unary", "(", "op", ",", "opstr", ")", ":", "def", "_evaluate_numeric_unary", "(", "self", ")", ":", "self", ".", "_validate_for_numeric_unaryop", "(", "op", ",", "opstr", ")", "attrs", "=", "self", ".", "_get_attributes_dict", "(", ")", "attrs", "=", "self", ".", "_maybe_update_attributes", "(", "attrs", ")", "return", "Index", "(", "op", "(", "self", ".", "values", ")", ",", "*", "*", "attrs", ")", "_evaluate_numeric_unary", ".", "__name__", "=", "opstr", "return", "_evaluate_numeric_unary", "cls", ".", "__neg__", "=", "_make_evaluate_unary", "(", "operator", ".", "neg", ",", "'__neg__'", ")", "cls", ".", "__pos__", "=", "_make_evaluate_unary", "(", "operator", ".", "pos", ",", "'__pos__'", ")", "cls", ".", "__abs__", "=", "_make_evaluate_unary", "(", "np", ".", "abs", ",", "'__abs__'", ")", "cls", ".", "__inv__", "=", "_make_evaluate_unary", "(", "lambda", "x", ":", "-", "x", ",", "'__inv__'", ")" ]
Add in numeric unary methods.
[ "Add", "in", "numeric", "unary", "methods", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5131-L5150
19,443
pandas-dev/pandas
pandas/core/indexes/base.py
Index._add_logical_methods
def _add_logical_methods(cls): """ Add in logical methods. """ _doc = """ %(desc)s Parameters ---------- *args These parameters will be passed to numpy.%(outname)s. **kwargs These parameters will be passed to numpy.%(outname)s. Returns ------- %(outname)s : bool or array_like (if axis is specified) A single element array_like may be converted to bool.""" _index_shared_docs['index_all'] = dedent(""" See Also -------- Index.any : Return whether any element in an Index is True. Series.any : Return whether any element in a Series is True. Series.all : Return whether all elements in a Series are True. Notes ----- Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero. Examples -------- **all** True, because nonzero integers are considered True. >>> pd.Index([1, 2, 3]).all() True False, because ``0`` is considered False. >>> pd.Index([0, 1, 2]).all() False **any** True, because ``1`` is considered True. >>> pd.Index([0, 0, 1]).any() True False, because ``0`` is considered False. >>> pd.Index([0, 0, 0]).any() False """) _index_shared_docs['index_any'] = dedent(""" See Also -------- Index.all : Return whether all elements are True. Series.all : Return whether all elements are True. Notes ----- Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero. Examples -------- >>> index = pd.Index([0, 1, 2]) >>> index.any() True >>> index = pd.Index([0, 0, 0]) >>> index.any() False """) def _make_logical_function(name, desc, f): @Substitution(outname=name, desc=desc) @Appender(_index_shared_docs['index_' + name]) @Appender(_doc) def logical_func(self, *args, **kwargs): result = f(self.values) if (isinstance(result, (np.ndarray, ABCSeries, Index)) and result.ndim == 0): # return NumPy type return result.dtype.type(result.item()) else: # pragma: no cover return result logical_func.__name__ = name return logical_func cls.all = _make_logical_function('all', 'Return whether all elements ' 'are True.', np.all) cls.any = _make_logical_function('any', 'Return whether any element is True.', np.any)
python
def _add_logical_methods(cls): """ Add in logical methods. """ _doc = """ %(desc)s Parameters ---------- *args These parameters will be passed to numpy.%(outname)s. **kwargs These parameters will be passed to numpy.%(outname)s. Returns ------- %(outname)s : bool or array_like (if axis is specified) A single element array_like may be converted to bool.""" _index_shared_docs['index_all'] = dedent(""" See Also -------- Index.any : Return whether any element in an Index is True. Series.any : Return whether any element in a Series is True. Series.all : Return whether all elements in a Series are True. Notes ----- Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero. Examples -------- **all** True, because nonzero integers are considered True. >>> pd.Index([1, 2, 3]).all() True False, because ``0`` is considered False. >>> pd.Index([0, 1, 2]).all() False **any** True, because ``1`` is considered True. >>> pd.Index([0, 0, 1]).any() True False, because ``0`` is considered False. >>> pd.Index([0, 0, 0]).any() False """) _index_shared_docs['index_any'] = dedent(""" See Also -------- Index.all : Return whether all elements are True. Series.all : Return whether all elements are True. Notes ----- Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero. Examples -------- >>> index = pd.Index([0, 1, 2]) >>> index.any() True >>> index = pd.Index([0, 0, 0]) >>> index.any() False """) def _make_logical_function(name, desc, f): @Substitution(outname=name, desc=desc) @Appender(_index_shared_docs['index_' + name]) @Appender(_doc) def logical_func(self, *args, **kwargs): result = f(self.values) if (isinstance(result, (np.ndarray, ABCSeries, Index)) and result.ndim == 0): # return NumPy type return result.dtype.type(result.item()) else: # pragma: no cover return result logical_func.__name__ = name return logical_func cls.all = _make_logical_function('all', 'Return whether all elements ' 'are True.', np.all) cls.any = _make_logical_function('any', 'Return whether any element is True.', np.any)
[ "def", "_add_logical_methods", "(", "cls", ")", ":", "_doc", "=", "\"\"\"\n %(desc)s\n\n Parameters\n ----------\n *args\n These parameters will be passed to numpy.%(outname)s.\n **kwargs\n These parameters will be passed to numpy.%(outname)s.\n\n Returns\n -------\n %(outname)s : bool or array_like (if axis is specified)\n A single element array_like may be converted to bool.\"\"\"", "_index_shared_docs", "[", "'index_all'", "]", "=", "dedent", "(", "\"\"\"\n\n See Also\n --------\n Index.any : Return whether any element in an Index is True.\n Series.any : Return whether any element in a Series is True.\n Series.all : Return whether all elements in a Series are True.\n\n Notes\n -----\n Not a Number (NaN), positive infinity and negative infinity\n evaluate to True because these are not equal to zero.\n\n Examples\n --------\n **all**\n\n True, because nonzero integers are considered True.\n\n >>> pd.Index([1, 2, 3]).all()\n True\n\n False, because ``0`` is considered False.\n\n >>> pd.Index([0, 1, 2]).all()\n False\n\n **any**\n\n True, because ``1`` is considered True.\n\n >>> pd.Index([0, 0, 1]).any()\n True\n\n False, because ``0`` is considered False.\n\n >>> pd.Index([0, 0, 0]).any()\n False\n \"\"\"", ")", "_index_shared_docs", "[", "'index_any'", "]", "=", "dedent", "(", "\"\"\"\n\n See Also\n --------\n Index.all : Return whether all elements are True.\n Series.all : Return whether all elements are True.\n\n Notes\n -----\n Not a Number (NaN), positive infinity and negative infinity\n evaluate to True because these are not equal to zero.\n\n Examples\n --------\n >>> index = pd.Index([0, 1, 2])\n >>> index.any()\n True\n\n >>> index = pd.Index([0, 0, 0])\n >>> index.any()\n False\n \"\"\"", ")", "def", "_make_logical_function", "(", "name", ",", "desc", ",", "f", ")", ":", "@", "Substitution", "(", "outname", "=", "name", ",", "desc", "=", "desc", ")", "@", "Appender", "(", "_index_shared_docs", "[", "'index_'", "+", "name", "]", ")", "@", "Appender", "(", "_doc", ")", "def", "logical_func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "f", "(", "self", ".", "values", ")", "if", "(", "isinstance", "(", "result", ",", "(", "np", ".", "ndarray", ",", "ABCSeries", ",", "Index", ")", ")", "and", "result", ".", "ndim", "==", "0", ")", ":", "# return NumPy type", "return", "result", ".", "dtype", ".", "type", "(", "result", ".", "item", "(", ")", ")", "else", ":", "# pragma: no cover", "return", "result", "logical_func", ".", "__name__", "=", "name", "return", "logical_func", "cls", ".", "all", "=", "_make_logical_function", "(", "'all'", ",", "'Return whether all elements '", "'are True.'", ",", "np", ".", "all", ")", "cls", ".", "any", "=", "_make_logical_function", "(", "'any'", ",", "'Return whether any element is True.'", ",", "np", ".", "any", ")" ]
Add in logical methods.
[ "Add", "in", "logical", "methods", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L5158-L5261
19,444
pandas-dev/pandas
pandas/core/groupby/grouper.py
Grouper._set_grouper
def _set_grouper(self, obj, sort=False): """ given an object and the specifications, setup the internal grouper for this particular specification Parameters ---------- obj : the subject object sort : bool, default False whether the resulting grouper should be sorted """ if self.key is not None and self.level is not None: raise ValueError( "The Grouper cannot specify both a key and a level!") # Keep self.grouper value before overriding if self._grouper is None: self._grouper = self.grouper # the key must be a valid info item if self.key is not None: key = self.key # The 'on' is already defined if (getattr(self.grouper, 'name', None) == key and isinstance(obj, ABCSeries)): ax = self._grouper.take(obj.index) else: if key not in obj._info_axis: raise KeyError( "The grouper name {0} is not found".format(key)) ax = Index(obj[key], name=key) else: ax = obj._get_axis(self.axis) if self.level is not None: level = self.level # if a level is given it must be a mi level or # equivalent to the axis name if isinstance(ax, MultiIndex): level = ax._get_level_number(level) ax = Index(ax._get_level_values(level), name=ax.names[level]) else: if level not in (0, ax.name): raise ValueError( "The level {0} is not valid".format(level)) # possibly sort if (self.sort or sort) and not ax.is_monotonic: # use stable sort to support first, last, nth indexer = self.indexer = ax.argsort(kind='mergesort') ax = ax.take(indexer) obj = obj._take(indexer, axis=self.axis, is_copy=False) self.obj = obj self.grouper = ax return self.grouper
python
def _set_grouper(self, obj, sort=False): """ given an object and the specifications, setup the internal grouper for this particular specification Parameters ---------- obj : the subject object sort : bool, default False whether the resulting grouper should be sorted """ if self.key is not None and self.level is not None: raise ValueError( "The Grouper cannot specify both a key and a level!") # Keep self.grouper value before overriding if self._grouper is None: self._grouper = self.grouper # the key must be a valid info item if self.key is not None: key = self.key # The 'on' is already defined if (getattr(self.grouper, 'name', None) == key and isinstance(obj, ABCSeries)): ax = self._grouper.take(obj.index) else: if key not in obj._info_axis: raise KeyError( "The grouper name {0} is not found".format(key)) ax = Index(obj[key], name=key) else: ax = obj._get_axis(self.axis) if self.level is not None: level = self.level # if a level is given it must be a mi level or # equivalent to the axis name if isinstance(ax, MultiIndex): level = ax._get_level_number(level) ax = Index(ax._get_level_values(level), name=ax.names[level]) else: if level not in (0, ax.name): raise ValueError( "The level {0} is not valid".format(level)) # possibly sort if (self.sort or sort) and not ax.is_monotonic: # use stable sort to support first, last, nth indexer = self.indexer = ax.argsort(kind='mergesort') ax = ax.take(indexer) obj = obj._take(indexer, axis=self.axis, is_copy=False) self.obj = obj self.grouper = ax return self.grouper
[ "def", "_set_grouper", "(", "self", ",", "obj", ",", "sort", "=", "False", ")", ":", "if", "self", ".", "key", "is", "not", "None", "and", "self", ".", "level", "is", "not", "None", ":", "raise", "ValueError", "(", "\"The Grouper cannot specify both a key and a level!\"", ")", "# Keep self.grouper value before overriding", "if", "self", ".", "_grouper", "is", "None", ":", "self", ".", "_grouper", "=", "self", ".", "grouper", "# the key must be a valid info item", "if", "self", ".", "key", "is", "not", "None", ":", "key", "=", "self", ".", "key", "# The 'on' is already defined", "if", "(", "getattr", "(", "self", ".", "grouper", ",", "'name'", ",", "None", ")", "==", "key", "and", "isinstance", "(", "obj", ",", "ABCSeries", ")", ")", ":", "ax", "=", "self", ".", "_grouper", ".", "take", "(", "obj", ".", "index", ")", "else", ":", "if", "key", "not", "in", "obj", ".", "_info_axis", ":", "raise", "KeyError", "(", "\"The grouper name {0} is not found\"", ".", "format", "(", "key", ")", ")", "ax", "=", "Index", "(", "obj", "[", "key", "]", ",", "name", "=", "key", ")", "else", ":", "ax", "=", "obj", ".", "_get_axis", "(", "self", ".", "axis", ")", "if", "self", ".", "level", "is", "not", "None", ":", "level", "=", "self", ".", "level", "# if a level is given it must be a mi level or", "# equivalent to the axis name", "if", "isinstance", "(", "ax", ",", "MultiIndex", ")", ":", "level", "=", "ax", ".", "_get_level_number", "(", "level", ")", "ax", "=", "Index", "(", "ax", ".", "_get_level_values", "(", "level", ")", ",", "name", "=", "ax", ".", "names", "[", "level", "]", ")", "else", ":", "if", "level", "not", "in", "(", "0", ",", "ax", ".", "name", ")", ":", "raise", "ValueError", "(", "\"The level {0} is not valid\"", ".", "format", "(", "level", ")", ")", "# possibly sort", "if", "(", "self", ".", "sort", "or", "sort", ")", "and", "not", "ax", ".", "is_monotonic", ":", "# use stable sort to support first, last, nth", "indexer", "=", "self", ".", "indexer", "=", "ax", ".", "argsort", "(", "kind", "=", "'mergesort'", ")", "ax", "=", "ax", ".", "take", "(", "indexer", ")", "obj", "=", "obj", ".", "_take", "(", "indexer", ",", "axis", "=", "self", ".", "axis", ",", "is_copy", "=", "False", ")", "self", ".", "obj", "=", "obj", "self", ".", "grouper", "=", "ax", "return", "self", ".", "grouper" ]
given an object and the specifications, setup the internal grouper for this particular specification Parameters ---------- obj : the subject object sort : bool, default False whether the resulting grouper should be sorted
[ "given", "an", "object", "and", "the", "specifications", "setup", "the", "internal", "grouper", "for", "this", "particular", "specification" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/grouper.py#L133-L192
19,445
pandas-dev/pandas
pandas/core/missing.py
_interpolate_scipy_wrapper
def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None, bounds_error=False, order=None, **kwargs): """ Passed off to scipy.interpolate.interp1d. method is scipy's kind. Returns an array interpolated at new_x. Add any new methods to the list in _clean_interp_method. """ try: from scipy import interpolate # TODO: Why is DatetimeIndex being imported here? from pandas import DatetimeIndex # noqa except ImportError: raise ImportError('{method} interpolation requires SciPy' .format(method=method)) new_x = np.asarray(new_x) # ignores some kwargs that could be passed along. alt_methods = { 'barycentric': interpolate.barycentric_interpolate, 'krogh': interpolate.krogh_interpolate, 'from_derivatives': _from_derivatives, 'piecewise_polynomial': _from_derivatives, } if getattr(x, 'is_all_dates', False): # GH 5975, scipy.interp1d can't hande datetime64s x, new_x = x._values.astype('i8'), new_x.astype('i8') if method == 'pchip': try: alt_methods['pchip'] = interpolate.pchip_interpolate except AttributeError: raise ImportError("Your version of Scipy does not support " "PCHIP interpolation.") elif method == 'akima': try: from scipy.interpolate import Akima1DInterpolator # noqa alt_methods['akima'] = _akima_interpolate except ImportError: raise ImportError("Your version of Scipy does not support " "Akima interpolation.") interp1d_methods = ['nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'polynomial'] if method in interp1d_methods: if method == 'polynomial': method = order terp = interpolate.interp1d(x, y, kind=method, fill_value=fill_value, bounds_error=bounds_error) new_y = terp(new_x) elif method == 'spline': # GH #10633, #24014 if isna(order) or (order <= 0): raise ValueError("order needs to be specified and greater than 0; " "got order: {}".format(order)) terp = interpolate.UnivariateSpline(x, y, k=order, **kwargs) new_y = terp(new_x) else: # GH 7295: need to be able to write for some reason # in some circumstances: check all three if not x.flags.writeable: x = x.copy() if not y.flags.writeable: y = y.copy() if not new_x.flags.writeable: new_x = new_x.copy() method = alt_methods[method] new_y = method(x, y, new_x, **kwargs) return new_y
python
def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None, bounds_error=False, order=None, **kwargs): """ Passed off to scipy.interpolate.interp1d. method is scipy's kind. Returns an array interpolated at new_x. Add any new methods to the list in _clean_interp_method. """ try: from scipy import interpolate # TODO: Why is DatetimeIndex being imported here? from pandas import DatetimeIndex # noqa except ImportError: raise ImportError('{method} interpolation requires SciPy' .format(method=method)) new_x = np.asarray(new_x) # ignores some kwargs that could be passed along. alt_methods = { 'barycentric': interpolate.barycentric_interpolate, 'krogh': interpolate.krogh_interpolate, 'from_derivatives': _from_derivatives, 'piecewise_polynomial': _from_derivatives, } if getattr(x, 'is_all_dates', False): # GH 5975, scipy.interp1d can't hande datetime64s x, new_x = x._values.astype('i8'), new_x.astype('i8') if method == 'pchip': try: alt_methods['pchip'] = interpolate.pchip_interpolate except AttributeError: raise ImportError("Your version of Scipy does not support " "PCHIP interpolation.") elif method == 'akima': try: from scipy.interpolate import Akima1DInterpolator # noqa alt_methods['akima'] = _akima_interpolate except ImportError: raise ImportError("Your version of Scipy does not support " "Akima interpolation.") interp1d_methods = ['nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'polynomial'] if method in interp1d_methods: if method == 'polynomial': method = order terp = interpolate.interp1d(x, y, kind=method, fill_value=fill_value, bounds_error=bounds_error) new_y = terp(new_x) elif method == 'spline': # GH #10633, #24014 if isna(order) or (order <= 0): raise ValueError("order needs to be specified and greater than 0; " "got order: {}".format(order)) terp = interpolate.UnivariateSpline(x, y, k=order, **kwargs) new_y = terp(new_x) else: # GH 7295: need to be able to write for some reason # in some circumstances: check all three if not x.flags.writeable: x = x.copy() if not y.flags.writeable: y = y.copy() if not new_x.flags.writeable: new_x = new_x.copy() method = alt_methods[method] new_y = method(x, y, new_x, **kwargs) return new_y
[ "def", "_interpolate_scipy_wrapper", "(", "x", ",", "y", ",", "new_x", ",", "method", ",", "fill_value", "=", "None", ",", "bounds_error", "=", "False", ",", "order", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "from", "scipy", "import", "interpolate", "# TODO: Why is DatetimeIndex being imported here?", "from", "pandas", "import", "DatetimeIndex", "# noqa", "except", "ImportError", ":", "raise", "ImportError", "(", "'{method} interpolation requires SciPy'", ".", "format", "(", "method", "=", "method", ")", ")", "new_x", "=", "np", ".", "asarray", "(", "new_x", ")", "# ignores some kwargs that could be passed along.", "alt_methods", "=", "{", "'barycentric'", ":", "interpolate", ".", "barycentric_interpolate", ",", "'krogh'", ":", "interpolate", ".", "krogh_interpolate", ",", "'from_derivatives'", ":", "_from_derivatives", ",", "'piecewise_polynomial'", ":", "_from_derivatives", ",", "}", "if", "getattr", "(", "x", ",", "'is_all_dates'", ",", "False", ")", ":", "# GH 5975, scipy.interp1d can't hande datetime64s", "x", ",", "new_x", "=", "x", ".", "_values", ".", "astype", "(", "'i8'", ")", ",", "new_x", ".", "astype", "(", "'i8'", ")", "if", "method", "==", "'pchip'", ":", "try", ":", "alt_methods", "[", "'pchip'", "]", "=", "interpolate", ".", "pchip_interpolate", "except", "AttributeError", ":", "raise", "ImportError", "(", "\"Your version of Scipy does not support \"", "\"PCHIP interpolation.\"", ")", "elif", "method", "==", "'akima'", ":", "try", ":", "from", "scipy", ".", "interpolate", "import", "Akima1DInterpolator", "# noqa", "alt_methods", "[", "'akima'", "]", "=", "_akima_interpolate", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Your version of Scipy does not support \"", "\"Akima interpolation.\"", ")", "interp1d_methods", "=", "[", "'nearest'", ",", "'zero'", ",", "'slinear'", ",", "'quadratic'", ",", "'cubic'", ",", "'polynomial'", "]", "if", "method", "in", "interp1d_methods", ":", "if", "method", "==", "'polynomial'", ":", "method", "=", "order", "terp", "=", "interpolate", ".", "interp1d", "(", "x", ",", "y", ",", "kind", "=", "method", ",", "fill_value", "=", "fill_value", ",", "bounds_error", "=", "bounds_error", ")", "new_y", "=", "terp", "(", "new_x", ")", "elif", "method", "==", "'spline'", ":", "# GH #10633, #24014", "if", "isna", "(", "order", ")", "or", "(", "order", "<=", "0", ")", ":", "raise", "ValueError", "(", "\"order needs to be specified and greater than 0; \"", "\"got order: {}\"", ".", "format", "(", "order", ")", ")", "terp", "=", "interpolate", ".", "UnivariateSpline", "(", "x", ",", "y", ",", "k", "=", "order", ",", "*", "*", "kwargs", ")", "new_y", "=", "terp", "(", "new_x", ")", "else", ":", "# GH 7295: need to be able to write for some reason", "# in some circumstances: check all three", "if", "not", "x", ".", "flags", ".", "writeable", ":", "x", "=", "x", ".", "copy", "(", ")", "if", "not", "y", ".", "flags", ".", "writeable", ":", "y", "=", "y", ".", "copy", "(", ")", "if", "not", "new_x", ".", "flags", ".", "writeable", ":", "new_x", "=", "new_x", ".", "copy", "(", ")", "method", "=", "alt_methods", "[", "method", "]", "new_y", "=", "method", "(", "x", ",", "y", ",", "new_x", ",", "*", "*", "kwargs", ")", "return", "new_y" ]
Passed off to scipy.interpolate.interp1d. method is scipy's kind. Returns an array interpolated at new_x. Add any new methods to the list in _clean_interp_method.
[ "Passed", "off", "to", "scipy", ".", "interpolate", ".", "interp1d", ".", "method", "is", "scipy", "s", "kind", ".", "Returns", "an", "array", "interpolated", "at", "new_x", ".", "Add", "any", "new", "methods", "to", "the", "list", "in", "_clean_interp_method", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L242-L311
19,446
pandas-dev/pandas
pandas/core/missing.py
_from_derivatives
def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False): """ Convenience function for interpolate.BPoly.from_derivatives. Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : array_like sorted 1D array of x-coordinates yi : array_like or list of array-likes yi[i][j] is the j-th derivative known at xi[i] order: None or int or array_like of ints. Default: None. Specifies the degree of local polynomials. If not None, some derivatives are ignored. der : int or list How many derivatives to extract; None for all potentially nonzero derivatives (that is a number equal to the number of points), or a list of derivatives to extract. This numberincludes the function value as 0th derivative. extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. See Also -------- scipy.interpolate.BPoly.from_derivatives Returns ------- y : scalar or array_like The result, of length R or length M or M by R. """ from scipy import interpolate # return the method for compat with scipy version & backwards compat method = interpolate.BPoly.from_derivatives m = method(xi, yi.reshape(-1, 1), orders=order, extrapolate=extrapolate) return m(x)
python
def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False): """ Convenience function for interpolate.BPoly.from_derivatives. Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : array_like sorted 1D array of x-coordinates yi : array_like or list of array-likes yi[i][j] is the j-th derivative known at xi[i] order: None or int or array_like of ints. Default: None. Specifies the degree of local polynomials. If not None, some derivatives are ignored. der : int or list How many derivatives to extract; None for all potentially nonzero derivatives (that is a number equal to the number of points), or a list of derivatives to extract. This numberincludes the function value as 0th derivative. extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. See Also -------- scipy.interpolate.BPoly.from_derivatives Returns ------- y : scalar or array_like The result, of length R or length M or M by R. """ from scipy import interpolate # return the method for compat with scipy version & backwards compat method = interpolate.BPoly.from_derivatives m = method(xi, yi.reshape(-1, 1), orders=order, extrapolate=extrapolate) return m(x)
[ "def", "_from_derivatives", "(", "xi", ",", "yi", ",", "x", ",", "order", "=", "None", ",", "der", "=", "0", ",", "extrapolate", "=", "False", ")", ":", "from", "scipy", "import", "interpolate", "# return the method for compat with scipy version & backwards compat", "method", "=", "interpolate", ".", "BPoly", ".", "from_derivatives", "m", "=", "method", "(", "xi", ",", "yi", ".", "reshape", "(", "-", "1", ",", "1", ")", ",", "orders", "=", "order", ",", "extrapolate", "=", "extrapolate", ")", "return", "m", "(", "x", ")" ]
Convenience function for interpolate.BPoly.from_derivatives. Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : array_like sorted 1D array of x-coordinates yi : array_like or list of array-likes yi[i][j] is the j-th derivative known at xi[i] order: None or int or array_like of ints. Default: None. Specifies the degree of local polynomials. If not None, some derivatives are ignored. der : int or list How many derivatives to extract; None for all potentially nonzero derivatives (that is a number equal to the number of points), or a list of derivatives to extract. This numberincludes the function value as 0th derivative. extrapolate : bool, optional Whether to extrapolate to ouf-of-bounds points based on first and last intervals, or to return NaNs. Default: True. See Also -------- scipy.interpolate.BPoly.from_derivatives Returns ------- y : scalar or array_like The result, of length R or length M or M by R.
[ "Convenience", "function", "for", "interpolate", ".", "BPoly", ".", "from_derivatives", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L314-L355
19,447
pandas-dev/pandas
pandas/core/missing.py
interpolate_2d
def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None, dtype=None): """ Perform an actual interpolation of values, values will be make 2-d if needed fills inplace, returns the result. """ transf = (lambda x: x) if axis == 0 else (lambda x: x.T) # reshape a 1 dim if needed ndim = values.ndim if values.ndim == 1: if axis != 0: # pragma: no cover raise AssertionError("cannot interpolate on a ndim == 1 with " "axis != 0") values = values.reshape(tuple((1,) + values.shape)) if fill_value is None: mask = None else: # todo create faster fill func without masking mask = mask_missing(transf(values), fill_value) method = clean_fill_method(method) if method == 'pad': values = transf(pad_2d( transf(values), limit=limit, mask=mask, dtype=dtype)) else: values = transf(backfill_2d( transf(values), limit=limit, mask=mask, dtype=dtype)) # reshape back if ndim == 1: values = values[0] return values
python
def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None, dtype=None): """ Perform an actual interpolation of values, values will be make 2-d if needed fills inplace, returns the result. """ transf = (lambda x: x) if axis == 0 else (lambda x: x.T) # reshape a 1 dim if needed ndim = values.ndim if values.ndim == 1: if axis != 0: # pragma: no cover raise AssertionError("cannot interpolate on a ndim == 1 with " "axis != 0") values = values.reshape(tuple((1,) + values.shape)) if fill_value is None: mask = None else: # todo create faster fill func without masking mask = mask_missing(transf(values), fill_value) method = clean_fill_method(method) if method == 'pad': values = transf(pad_2d( transf(values), limit=limit, mask=mask, dtype=dtype)) else: values = transf(backfill_2d( transf(values), limit=limit, mask=mask, dtype=dtype)) # reshape back if ndim == 1: values = values[0] return values
[ "def", "interpolate_2d", "(", "values", ",", "method", "=", "'pad'", ",", "axis", "=", "0", ",", "limit", "=", "None", ",", "fill_value", "=", "None", ",", "dtype", "=", "None", ")", ":", "transf", "=", "(", "lambda", "x", ":", "x", ")", "if", "axis", "==", "0", "else", "(", "lambda", "x", ":", "x", ".", "T", ")", "# reshape a 1 dim if needed", "ndim", "=", "values", ".", "ndim", "if", "values", ".", "ndim", "==", "1", ":", "if", "axis", "!=", "0", ":", "# pragma: no cover", "raise", "AssertionError", "(", "\"cannot interpolate on a ndim == 1 with \"", "\"axis != 0\"", ")", "values", "=", "values", ".", "reshape", "(", "tuple", "(", "(", "1", ",", ")", "+", "values", ".", "shape", ")", ")", "if", "fill_value", "is", "None", ":", "mask", "=", "None", "else", ":", "# todo create faster fill func without masking", "mask", "=", "mask_missing", "(", "transf", "(", "values", ")", ",", "fill_value", ")", "method", "=", "clean_fill_method", "(", "method", ")", "if", "method", "==", "'pad'", ":", "values", "=", "transf", "(", "pad_2d", "(", "transf", "(", "values", ")", ",", "limit", "=", "limit", ",", "mask", "=", "mask", ",", "dtype", "=", "dtype", ")", ")", "else", ":", "values", "=", "transf", "(", "backfill_2d", "(", "transf", "(", "values", ")", ",", "limit", "=", "limit", ",", "mask", "=", "mask", ",", "dtype", "=", "dtype", ")", ")", "# reshape back", "if", "ndim", "==", "1", ":", "values", "=", "values", "[", "0", "]", "return", "values" ]
Perform an actual interpolation of values, values will be make 2-d if needed fills inplace, returns the result.
[ "Perform", "an", "actual", "interpolation", "of", "values", "values", "will", "be", "make", "2", "-", "d", "if", "needed", "fills", "inplace", "returns", "the", "result", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L408-L442
19,448
pandas-dev/pandas
pandas/core/missing.py
_cast_values_for_fillna
def _cast_values_for_fillna(values, dtype): """ Cast values to a dtype that algos.pad and algos.backfill can handle. """ # TODO: for int-dtypes we make a copy, but for everything else this # alters the values in-place. Is this intentional? if (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or is_timedelta64_dtype(dtype)): values = values.view(np.int64) elif is_integer_dtype(values): # NB: this check needs to come after the datetime64 check above values = ensure_float64(values) return values
python
def _cast_values_for_fillna(values, dtype): """ Cast values to a dtype that algos.pad and algos.backfill can handle. """ # TODO: for int-dtypes we make a copy, but for everything else this # alters the values in-place. Is this intentional? if (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or is_timedelta64_dtype(dtype)): values = values.view(np.int64) elif is_integer_dtype(values): # NB: this check needs to come after the datetime64 check above values = ensure_float64(values) return values
[ "def", "_cast_values_for_fillna", "(", "values", ",", "dtype", ")", ":", "# TODO: for int-dtypes we make a copy, but for everything else this", "# alters the values in-place. Is this intentional?", "if", "(", "is_datetime64_dtype", "(", "dtype", ")", "or", "is_datetime64tz_dtype", "(", "dtype", ")", "or", "is_timedelta64_dtype", "(", "dtype", ")", ")", ":", "values", "=", "values", ".", "view", "(", "np", ".", "int64", ")", "elif", "is_integer_dtype", "(", "values", ")", ":", "# NB: this check needs to come after the datetime64 check above", "values", "=", "ensure_float64", "(", "values", ")", "return", "values" ]
Cast values to a dtype that algos.pad and algos.backfill can handle.
[ "Cast", "values", "to", "a", "dtype", "that", "algos", ".", "pad", "and", "algos", ".", "backfill", "can", "handle", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L445-L460
19,449
pandas-dev/pandas
pandas/core/missing.py
fill_zeros
def fill_zeros(result, x, y, name, fill): """ If this is a reversed op, then flip x,y If we have an integer value (or array in y) and we have 0's, fill them with the fill, return the result. Mask the nan's from x. """ if fill is None or is_float_dtype(result): return result if name.startswith(('r', '__r')): x, y = y, x is_variable_type = (hasattr(y, 'dtype') or hasattr(y, 'type')) is_scalar_type = is_scalar(y) if not is_variable_type and not is_scalar_type: return result if is_scalar_type: y = np.array(y) if is_integer_dtype(y): if (y == 0).any(): # GH 7325, mask and nans must be broadcastable (also: PR 9308) # Raveling and then reshaping makes np.putmask faster mask = ((y == 0) & ~np.isnan(result)).ravel() shape = result.shape result = result.astype('float64', copy=False).ravel() np.putmask(result, mask, fill) # if we have a fill of inf, then sign it correctly # (GH 6178 and PR 9308) if np.isinf(fill): signs = y if name.startswith(('r', '__r')) else x signs = np.sign(signs.astype('float', copy=False)) negative_inf_mask = (signs.ravel() < 0) & mask np.putmask(result, negative_inf_mask, -fill) if "floordiv" in name: # (PR 9308) nan_mask = ((y == 0) & (x == 0)).ravel() np.putmask(result, nan_mask, np.nan) result = result.reshape(shape) return result
python
def fill_zeros(result, x, y, name, fill): """ If this is a reversed op, then flip x,y If we have an integer value (or array in y) and we have 0's, fill them with the fill, return the result. Mask the nan's from x. """ if fill is None or is_float_dtype(result): return result if name.startswith(('r', '__r')): x, y = y, x is_variable_type = (hasattr(y, 'dtype') or hasattr(y, 'type')) is_scalar_type = is_scalar(y) if not is_variable_type and not is_scalar_type: return result if is_scalar_type: y = np.array(y) if is_integer_dtype(y): if (y == 0).any(): # GH 7325, mask and nans must be broadcastable (also: PR 9308) # Raveling and then reshaping makes np.putmask faster mask = ((y == 0) & ~np.isnan(result)).ravel() shape = result.shape result = result.astype('float64', copy=False).ravel() np.putmask(result, mask, fill) # if we have a fill of inf, then sign it correctly # (GH 6178 and PR 9308) if np.isinf(fill): signs = y if name.startswith(('r', '__r')) else x signs = np.sign(signs.astype('float', copy=False)) negative_inf_mask = (signs.ravel() < 0) & mask np.putmask(result, negative_inf_mask, -fill) if "floordiv" in name: # (PR 9308) nan_mask = ((y == 0) & (x == 0)).ravel() np.putmask(result, nan_mask, np.nan) result = result.reshape(shape) return result
[ "def", "fill_zeros", "(", "result", ",", "x", ",", "y", ",", "name", ",", "fill", ")", ":", "if", "fill", "is", "None", "or", "is_float_dtype", "(", "result", ")", ":", "return", "result", "if", "name", ".", "startswith", "(", "(", "'r'", ",", "'__r'", ")", ")", ":", "x", ",", "y", "=", "y", ",", "x", "is_variable_type", "=", "(", "hasattr", "(", "y", ",", "'dtype'", ")", "or", "hasattr", "(", "y", ",", "'type'", ")", ")", "is_scalar_type", "=", "is_scalar", "(", "y", ")", "if", "not", "is_variable_type", "and", "not", "is_scalar_type", ":", "return", "result", "if", "is_scalar_type", ":", "y", "=", "np", ".", "array", "(", "y", ")", "if", "is_integer_dtype", "(", "y", ")", ":", "if", "(", "y", "==", "0", ")", ".", "any", "(", ")", ":", "# GH 7325, mask and nans must be broadcastable (also: PR 9308)", "# Raveling and then reshaping makes np.putmask faster", "mask", "=", "(", "(", "y", "==", "0", ")", "&", "~", "np", ".", "isnan", "(", "result", ")", ")", ".", "ravel", "(", ")", "shape", "=", "result", ".", "shape", "result", "=", "result", ".", "astype", "(", "'float64'", ",", "copy", "=", "False", ")", ".", "ravel", "(", ")", "np", ".", "putmask", "(", "result", ",", "mask", ",", "fill", ")", "# if we have a fill of inf, then sign it correctly", "# (GH 6178 and PR 9308)", "if", "np", ".", "isinf", "(", "fill", ")", ":", "signs", "=", "y", "if", "name", ".", "startswith", "(", "(", "'r'", ",", "'__r'", ")", ")", "else", "x", "signs", "=", "np", ".", "sign", "(", "signs", ".", "astype", "(", "'float'", ",", "copy", "=", "False", ")", ")", "negative_inf_mask", "=", "(", "signs", ".", "ravel", "(", ")", "<", "0", ")", "&", "mask", "np", ".", "putmask", "(", "result", ",", "negative_inf_mask", ",", "-", "fill", ")", "if", "\"floordiv\"", "in", "name", ":", "# (PR 9308)", "nan_mask", "=", "(", "(", "y", "==", "0", ")", "&", "(", "x", "==", "0", ")", ")", ".", "ravel", "(", ")", "np", ".", "putmask", "(", "result", ",", "nan_mask", ",", "np", ".", "nan", ")", "result", "=", "result", ".", "reshape", "(", "shape", ")", "return", "result" ]
If this is a reversed op, then flip x,y If we have an integer value (or array in y) and we have 0's, fill them with the fill, return the result. Mask the nan's from x.
[ "If", "this", "is", "a", "reversed", "op", "then", "flip", "x", "y" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L524-L576
19,450
pandas-dev/pandas
pandas/core/missing.py
dispatch_missing
def dispatch_missing(op, left, right, result): """ Fill nulls caused by division by zero, casting to a diffferent dtype if necessary. Parameters ---------- op : function (operator.add, operator.div, ...) left : object (Index for non-reversed ops) right : object (Index fof reversed ops) result : ndarray Returns ------- result : ndarray """ opstr = '__{opname}__'.format(opname=op.__name__).replace('____', '__') if op in [operator.truediv, operator.floordiv, getattr(operator, 'div', None)]: result = mask_zero_div_zero(left, right, result) elif op is operator.mod: result = fill_zeros(result, left, right, opstr, np.nan) elif op is divmod: res0 = mask_zero_div_zero(left, right, result[0]) res1 = fill_zeros(result[1], left, right, opstr, np.nan) result = (res0, res1) return result
python
def dispatch_missing(op, left, right, result): """ Fill nulls caused by division by zero, casting to a diffferent dtype if necessary. Parameters ---------- op : function (operator.add, operator.div, ...) left : object (Index for non-reversed ops) right : object (Index fof reversed ops) result : ndarray Returns ------- result : ndarray """ opstr = '__{opname}__'.format(opname=op.__name__).replace('____', '__') if op in [operator.truediv, operator.floordiv, getattr(operator, 'div', None)]: result = mask_zero_div_zero(left, right, result) elif op is operator.mod: result = fill_zeros(result, left, right, opstr, np.nan) elif op is divmod: res0 = mask_zero_div_zero(left, right, result[0]) res1 = fill_zeros(result[1], left, right, opstr, np.nan) result = (res0, res1) return result
[ "def", "dispatch_missing", "(", "op", ",", "left", ",", "right", ",", "result", ")", ":", "opstr", "=", "'__{opname}__'", ".", "format", "(", "opname", "=", "op", ".", "__name__", ")", ".", "replace", "(", "'____'", ",", "'__'", ")", "if", "op", "in", "[", "operator", ".", "truediv", ",", "operator", ".", "floordiv", ",", "getattr", "(", "operator", ",", "'div'", ",", "None", ")", "]", ":", "result", "=", "mask_zero_div_zero", "(", "left", ",", "right", ",", "result", ")", "elif", "op", "is", "operator", ".", "mod", ":", "result", "=", "fill_zeros", "(", "result", ",", "left", ",", "right", ",", "opstr", ",", "np", ".", "nan", ")", "elif", "op", "is", "divmod", ":", "res0", "=", "mask_zero_div_zero", "(", "left", ",", "right", ",", "result", "[", "0", "]", ")", "res1", "=", "fill_zeros", "(", "result", "[", "1", "]", ",", "left", ",", "right", ",", "opstr", ",", "np", ".", "nan", ")", "result", "=", "(", "res0", ",", "res1", ")", "return", "result" ]
Fill nulls caused by division by zero, casting to a diffferent dtype if necessary. Parameters ---------- op : function (operator.add, operator.div, ...) left : object (Index for non-reversed ops) right : object (Index fof reversed ops) result : ndarray Returns ------- result : ndarray
[ "Fill", "nulls", "caused", "by", "division", "by", "zero", "casting", "to", "a", "diffferent", "dtype", "if", "necessary", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L631-L657
19,451
pandas-dev/pandas
pandas/core/missing.py
_interp_limit
def _interp_limit(invalid, fw_limit, bw_limit): """ Get indexers of values that won't be filled because they exceed the limits. Parameters ---------- invalid : boolean ndarray fw_limit : int or None forward limit to index bw_limit : int or None backward limit to index Returns ------- set of indexers Notes ----- This is equivalent to the more readable, but slower .. code-block:: python def _interp_limit(invalid, fw_limit, bw_limit): for x in np.where(invalid)[0]: if invalid[max(0, x - fw_limit):x + bw_limit + 1].all(): yield x """ # handle forward first; the backward direction is the same except # 1. operate on the reversed array # 2. subtract the returned indices from N - 1 N = len(invalid) f_idx = set() b_idx = set() def inner(invalid, limit): limit = min(limit, N) windowed = _rolling_window(invalid, limit + 1).all(1) idx = (set(np.where(windowed)[0] + limit) | set(np.where((~invalid[:limit + 1]).cumsum() == 0)[0])) return idx if fw_limit is not None: if fw_limit == 0: f_idx = set(np.where(invalid)[0]) else: f_idx = inner(invalid, fw_limit) if bw_limit is not None: if bw_limit == 0: # then we don't even need to care about backwards # just use forwards return f_idx else: b_idx = list(inner(invalid[::-1], bw_limit)) b_idx = set(N - 1 - np.asarray(b_idx)) if fw_limit == 0: return b_idx return f_idx & b_idx
python
def _interp_limit(invalid, fw_limit, bw_limit): """ Get indexers of values that won't be filled because they exceed the limits. Parameters ---------- invalid : boolean ndarray fw_limit : int or None forward limit to index bw_limit : int or None backward limit to index Returns ------- set of indexers Notes ----- This is equivalent to the more readable, but slower .. code-block:: python def _interp_limit(invalid, fw_limit, bw_limit): for x in np.where(invalid)[0]: if invalid[max(0, x - fw_limit):x + bw_limit + 1].all(): yield x """ # handle forward first; the backward direction is the same except # 1. operate on the reversed array # 2. subtract the returned indices from N - 1 N = len(invalid) f_idx = set() b_idx = set() def inner(invalid, limit): limit = min(limit, N) windowed = _rolling_window(invalid, limit + 1).all(1) idx = (set(np.where(windowed)[0] + limit) | set(np.where((~invalid[:limit + 1]).cumsum() == 0)[0])) return idx if fw_limit is not None: if fw_limit == 0: f_idx = set(np.where(invalid)[0]) else: f_idx = inner(invalid, fw_limit) if bw_limit is not None: if bw_limit == 0: # then we don't even need to care about backwards # just use forwards return f_idx else: b_idx = list(inner(invalid[::-1], bw_limit)) b_idx = set(N - 1 - np.asarray(b_idx)) if fw_limit == 0: return b_idx return f_idx & b_idx
[ "def", "_interp_limit", "(", "invalid", ",", "fw_limit", ",", "bw_limit", ")", ":", "# handle forward first; the backward direction is the same except", "# 1. operate on the reversed array", "# 2. subtract the returned indices from N - 1", "N", "=", "len", "(", "invalid", ")", "f_idx", "=", "set", "(", ")", "b_idx", "=", "set", "(", ")", "def", "inner", "(", "invalid", ",", "limit", ")", ":", "limit", "=", "min", "(", "limit", ",", "N", ")", "windowed", "=", "_rolling_window", "(", "invalid", ",", "limit", "+", "1", ")", ".", "all", "(", "1", ")", "idx", "=", "(", "set", "(", "np", ".", "where", "(", "windowed", ")", "[", "0", "]", "+", "limit", ")", "|", "set", "(", "np", ".", "where", "(", "(", "~", "invalid", "[", ":", "limit", "+", "1", "]", ")", ".", "cumsum", "(", ")", "==", "0", ")", "[", "0", "]", ")", ")", "return", "idx", "if", "fw_limit", "is", "not", "None", ":", "if", "fw_limit", "==", "0", ":", "f_idx", "=", "set", "(", "np", ".", "where", "(", "invalid", ")", "[", "0", "]", ")", "else", ":", "f_idx", "=", "inner", "(", "invalid", ",", "fw_limit", ")", "if", "bw_limit", "is", "not", "None", ":", "if", "bw_limit", "==", "0", ":", "# then we don't even need to care about backwards", "# just use forwards", "return", "f_idx", "else", ":", "b_idx", "=", "list", "(", "inner", "(", "invalid", "[", ":", ":", "-", "1", "]", ",", "bw_limit", ")", ")", "b_idx", "=", "set", "(", "N", "-", "1", "-", "np", ".", "asarray", "(", "b_idx", ")", ")", "if", "fw_limit", "==", "0", ":", "return", "b_idx", "return", "f_idx", "&", "b_idx" ]
Get indexers of values that won't be filled because they exceed the limits. Parameters ---------- invalid : boolean ndarray fw_limit : int or None forward limit to index bw_limit : int or None backward limit to index Returns ------- set of indexers Notes ----- This is equivalent to the more readable, but slower .. code-block:: python def _interp_limit(invalid, fw_limit, bw_limit): for x in np.where(invalid)[0]: if invalid[max(0, x - fw_limit):x + bw_limit + 1].all(): yield x
[ "Get", "indexers", "of", "values", "that", "won", "t", "be", "filled", "because", "they", "exceed", "the", "limits", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L660-L721
19,452
pandas-dev/pandas
pandas/io/formats/console.py
in_interactive_session
def in_interactive_session(): """ check if we're running in an interactive shell returns True if running under python/ipython interactive shell """ from pandas import get_option def check_main(): try: import __main__ as main except ModuleNotFoundError: return get_option('mode.sim_interactive') return (not hasattr(main, '__file__') or get_option('mode.sim_interactive')) try: return __IPYTHON__ or check_main() # noqa except NameError: return check_main()
python
def in_interactive_session(): """ check if we're running in an interactive shell returns True if running under python/ipython interactive shell """ from pandas import get_option def check_main(): try: import __main__ as main except ModuleNotFoundError: return get_option('mode.sim_interactive') return (not hasattr(main, '__file__') or get_option('mode.sim_interactive')) try: return __IPYTHON__ or check_main() # noqa except NameError: return check_main()
[ "def", "in_interactive_session", "(", ")", ":", "from", "pandas", "import", "get_option", "def", "check_main", "(", ")", ":", "try", ":", "import", "__main__", "as", "main", "except", "ModuleNotFoundError", ":", "return", "get_option", "(", "'mode.sim_interactive'", ")", "return", "(", "not", "hasattr", "(", "main", ",", "'__file__'", ")", "or", "get_option", "(", "'mode.sim_interactive'", ")", ")", "try", ":", "return", "__IPYTHON__", "or", "check_main", "(", ")", "# noqa", "except", "NameError", ":", "return", "check_main", "(", ")" ]
check if we're running in an interactive shell returns True if running under python/ipython interactive shell
[ "check", "if", "we", "re", "running", "in", "an", "interactive", "shell" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/formats/console.py#L51-L69
19,453
pandas-dev/pandas
pandas/core/groupby/categorical.py
recode_for_groupby
def recode_for_groupby(c, sort, observed): """ Code the categories to ensure we can groupby for categoricals. If observed=True, we return a new Categorical with the observed categories only. If sort=False, return a copy of self, coded with categories as returned by .unique(), followed by any categories not appearing in the data. If sort=True, return self. This method is needed solely to ensure the categorical index of the GroupBy result has categories in the order of appearance in the data (GH-8868). Parameters ---------- c : Categorical sort : boolean The value of the sort parameter groupby was called with. observed : boolean Account only for the observed values Returns ------- New Categorical If sort=False, the new categories are set to the order of appearance in codes (unless ordered=True, in which case the original order is preserved), followed by any unrepresented categories in the original order. Categorical or None If we are observed, return the original categorical, otherwise None """ # we only care about observed values if observed: unique_codes = unique1d(c.codes) take_codes = unique_codes[unique_codes != -1] if c.ordered: take_codes = np.sort(take_codes) # we recode according to the uniques categories = c.categories.take(take_codes) codes = _recode_for_categories(c.codes, c.categories, categories) # return a new categorical that maps our new codes # and categories dtype = CategoricalDtype(categories, ordered=c.ordered) return Categorical(codes, dtype=dtype, fastpath=True), c # Already sorted according to c.categories; all is fine if sort: return c, None # sort=False should order groups in as-encountered order (GH-8868) cat = c.unique() # But for groupby to work, all categories should be present, # including those missing from the data (GH-13179), which .unique() # above dropped cat = cat.add_categories( c.categories[~c.categories.isin(cat.categories)]) return c.reorder_categories(cat.categories), None
python
def recode_for_groupby(c, sort, observed): """ Code the categories to ensure we can groupby for categoricals. If observed=True, we return a new Categorical with the observed categories only. If sort=False, return a copy of self, coded with categories as returned by .unique(), followed by any categories not appearing in the data. If sort=True, return self. This method is needed solely to ensure the categorical index of the GroupBy result has categories in the order of appearance in the data (GH-8868). Parameters ---------- c : Categorical sort : boolean The value of the sort parameter groupby was called with. observed : boolean Account only for the observed values Returns ------- New Categorical If sort=False, the new categories are set to the order of appearance in codes (unless ordered=True, in which case the original order is preserved), followed by any unrepresented categories in the original order. Categorical or None If we are observed, return the original categorical, otherwise None """ # we only care about observed values if observed: unique_codes = unique1d(c.codes) take_codes = unique_codes[unique_codes != -1] if c.ordered: take_codes = np.sort(take_codes) # we recode according to the uniques categories = c.categories.take(take_codes) codes = _recode_for_categories(c.codes, c.categories, categories) # return a new categorical that maps our new codes # and categories dtype = CategoricalDtype(categories, ordered=c.ordered) return Categorical(codes, dtype=dtype, fastpath=True), c # Already sorted according to c.categories; all is fine if sort: return c, None # sort=False should order groups in as-encountered order (GH-8868) cat = c.unique() # But for groupby to work, all categories should be present, # including those missing from the data (GH-13179), which .unique() # above dropped cat = cat.add_categories( c.categories[~c.categories.isin(cat.categories)]) return c.reorder_categories(cat.categories), None
[ "def", "recode_for_groupby", "(", "c", ",", "sort", ",", "observed", ")", ":", "# we only care about observed values", "if", "observed", ":", "unique_codes", "=", "unique1d", "(", "c", ".", "codes", ")", "take_codes", "=", "unique_codes", "[", "unique_codes", "!=", "-", "1", "]", "if", "c", ".", "ordered", ":", "take_codes", "=", "np", ".", "sort", "(", "take_codes", ")", "# we recode according to the uniques", "categories", "=", "c", ".", "categories", ".", "take", "(", "take_codes", ")", "codes", "=", "_recode_for_categories", "(", "c", ".", "codes", ",", "c", ".", "categories", ",", "categories", ")", "# return a new categorical that maps our new codes", "# and categories", "dtype", "=", "CategoricalDtype", "(", "categories", ",", "ordered", "=", "c", ".", "ordered", ")", "return", "Categorical", "(", "codes", ",", "dtype", "=", "dtype", ",", "fastpath", "=", "True", ")", ",", "c", "# Already sorted according to c.categories; all is fine", "if", "sort", ":", "return", "c", ",", "None", "# sort=False should order groups in as-encountered order (GH-8868)", "cat", "=", "c", ".", "unique", "(", ")", "# But for groupby to work, all categories should be present,", "# including those missing from the data (GH-13179), which .unique()", "# above dropped", "cat", "=", "cat", ".", "add_categories", "(", "c", ".", "categories", "[", "~", "c", ".", "categories", ".", "isin", "(", "cat", ".", "categories", ")", "]", ")", "return", "c", ".", "reorder_categories", "(", "cat", ".", "categories", ")", ",", "None" ]
Code the categories to ensure we can groupby for categoricals. If observed=True, we return a new Categorical with the observed categories only. If sort=False, return a copy of self, coded with categories as returned by .unique(), followed by any categories not appearing in the data. If sort=True, return self. This method is needed solely to ensure the categorical index of the GroupBy result has categories in the order of appearance in the data (GH-8868). Parameters ---------- c : Categorical sort : boolean The value of the sort parameter groupby was called with. observed : boolean Account only for the observed values Returns ------- New Categorical If sort=False, the new categories are set to the order of appearance in codes (unless ordered=True, in which case the original order is preserved), followed by any unrepresented categories in the original order. Categorical or None If we are observed, return the original categorical, otherwise None
[ "Code", "the", "categories", "to", "ensure", "we", "can", "groupby", "for", "categoricals", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/categorical.py#L8-L74
19,454
pandas-dev/pandas
pandas/io/parquet.py
get_engine
def get_engine(engine): """ return our implementation """ if engine == 'auto': engine = get_option('io.parquet.engine') if engine == 'auto': # try engines in this order try: return PyArrowImpl() except ImportError: pass try: return FastParquetImpl() except ImportError: pass raise ImportError("Unable to find a usable engine; " "tried using: 'pyarrow', 'fastparquet'.\n" "pyarrow or fastparquet is required for parquet " "support") if engine not in ['pyarrow', 'fastparquet']: raise ValueError("engine must be one of 'pyarrow', 'fastparquet'") if engine == 'pyarrow': return PyArrowImpl() elif engine == 'fastparquet': return FastParquetImpl()
python
def get_engine(engine): """ return our implementation """ if engine == 'auto': engine = get_option('io.parquet.engine') if engine == 'auto': # try engines in this order try: return PyArrowImpl() except ImportError: pass try: return FastParquetImpl() except ImportError: pass raise ImportError("Unable to find a usable engine; " "tried using: 'pyarrow', 'fastparquet'.\n" "pyarrow or fastparquet is required for parquet " "support") if engine not in ['pyarrow', 'fastparquet']: raise ValueError("engine must be one of 'pyarrow', 'fastparquet'") if engine == 'pyarrow': return PyArrowImpl() elif engine == 'fastparquet': return FastParquetImpl()
[ "def", "get_engine", "(", "engine", ")", ":", "if", "engine", "==", "'auto'", ":", "engine", "=", "get_option", "(", "'io.parquet.engine'", ")", "if", "engine", "==", "'auto'", ":", "# try engines in this order", "try", ":", "return", "PyArrowImpl", "(", ")", "except", "ImportError", ":", "pass", "try", ":", "return", "FastParquetImpl", "(", ")", "except", "ImportError", ":", "pass", "raise", "ImportError", "(", "\"Unable to find a usable engine; \"", "\"tried using: 'pyarrow', 'fastparquet'.\\n\"", "\"pyarrow or fastparquet is required for parquet \"", "\"support\"", ")", "if", "engine", "not", "in", "[", "'pyarrow'", ",", "'fastparquet'", "]", ":", "raise", "ValueError", "(", "\"engine must be one of 'pyarrow', 'fastparquet'\"", ")", "if", "engine", "==", "'pyarrow'", ":", "return", "PyArrowImpl", "(", ")", "elif", "engine", "==", "'fastparquet'", ":", "return", "FastParquetImpl", "(", ")" ]
return our implementation
[ "return", "our", "implementation" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/parquet.py#L13-L42
19,455
pandas-dev/pandas
pandas/io/parquet.py
to_parquet
def to_parquet(df, path, engine='auto', compression='snappy', index=None, partition_cols=None, **kwargs): """ Write a DataFrame to the parquet format. Parameters ---------- path : str File path or Root Directory path. Will be used as Root Directory path while writing a partitioned dataset. .. versionchanged:: 0.24.0 engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto' Parquet library to use. If 'auto', then the option ``io.parquet.engine`` is used. The default ``io.parquet.engine`` behavior is to try 'pyarrow', falling back to 'fastparquet' if 'pyarrow' is unavailable. compression : {'snappy', 'gzip', 'brotli', None}, default 'snappy' Name of the compression to use. Use ``None`` for no compression. index : bool, default None If ``True``, include the dataframe's index(es) in the file output. If ``False``, they will not be written to the file. If ``None``, the engine's default behavior will be used. .. versionadded 0.24.0 partition_cols : list, optional, default None Column names by which to partition the dataset Columns are partitioned in the order they are given .. versionadded:: 0.24.0 kwargs Additional keyword arguments passed to the engine """ impl = get_engine(engine) return impl.write(df, path, compression=compression, index=index, partition_cols=partition_cols, **kwargs)
python
def to_parquet(df, path, engine='auto', compression='snappy', index=None, partition_cols=None, **kwargs): """ Write a DataFrame to the parquet format. Parameters ---------- path : str File path or Root Directory path. Will be used as Root Directory path while writing a partitioned dataset. .. versionchanged:: 0.24.0 engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto' Parquet library to use. If 'auto', then the option ``io.parquet.engine`` is used. The default ``io.parquet.engine`` behavior is to try 'pyarrow', falling back to 'fastparquet' if 'pyarrow' is unavailable. compression : {'snappy', 'gzip', 'brotli', None}, default 'snappy' Name of the compression to use. Use ``None`` for no compression. index : bool, default None If ``True``, include the dataframe's index(es) in the file output. If ``False``, they will not be written to the file. If ``None``, the engine's default behavior will be used. .. versionadded 0.24.0 partition_cols : list, optional, default None Column names by which to partition the dataset Columns are partitioned in the order they are given .. versionadded:: 0.24.0 kwargs Additional keyword arguments passed to the engine """ impl = get_engine(engine) return impl.write(df, path, compression=compression, index=index, partition_cols=partition_cols, **kwargs)
[ "def", "to_parquet", "(", "df", ",", "path", ",", "engine", "=", "'auto'", ",", "compression", "=", "'snappy'", ",", "index", "=", "None", ",", "partition_cols", "=", "None", ",", "*", "*", "kwargs", ")", ":", "impl", "=", "get_engine", "(", "engine", ")", "return", "impl", ".", "write", "(", "df", ",", "path", ",", "compression", "=", "compression", ",", "index", "=", "index", ",", "partition_cols", "=", "partition_cols", ",", "*", "*", "kwargs", ")" ]
Write a DataFrame to the parquet format. Parameters ---------- path : str File path or Root Directory path. Will be used as Root Directory path while writing a partitioned dataset. .. versionchanged:: 0.24.0 engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto' Parquet library to use. If 'auto', then the option ``io.parquet.engine`` is used. The default ``io.parquet.engine`` behavior is to try 'pyarrow', falling back to 'fastparquet' if 'pyarrow' is unavailable. compression : {'snappy', 'gzip', 'brotli', None}, default 'snappy' Name of the compression to use. Use ``None`` for no compression. index : bool, default None If ``True``, include the dataframe's index(es) in the file output. If ``False``, they will not be written to the file. If ``None``, the engine's default behavior will be used. .. versionadded 0.24.0 partition_cols : list, optional, default None Column names by which to partition the dataset Columns are partitioned in the order they are given .. versionadded:: 0.24.0 kwargs Additional keyword arguments passed to the engine
[ "Write", "a", "DataFrame", "to", "the", "parquet", "format", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/parquet.py#L213-L251
19,456
pandas-dev/pandas
pandas/core/groupby/ops.py
generate_bins_generic
def generate_bins_generic(values, binner, closed): """ Generate bin edge offsets and bin labels for one array using another array which has bin edge values. Both arrays must be sorted. Parameters ---------- values : array of values binner : a comparable array of values representing bins into which to bin the first array. Note, 'values' end-points must fall within 'binner' end-points. closed : which end of bin is closed; left (default), right Returns ------- bins : array of offsets (into 'values' argument) of bins. Zero and last edge are excluded in result, so for instance the first bin is values[0:bin[0]] and the last is values[bin[-1]:] """ lenidx = len(values) lenbin = len(binner) if lenidx <= 0 or lenbin <= 0: raise ValueError("Invalid length for values or for binner") # check binner fits data if values[0] < binner[0]: raise ValueError("Values falls before first bin") if values[lenidx - 1] > binner[lenbin - 1]: raise ValueError("Values falls after last bin") bins = np.empty(lenbin - 1, dtype=np.int64) j = 0 # index into values bc = 0 # bin count # linear scan, presume nothing about values/binner except that it fits ok for i in range(0, lenbin - 1): r_bin = binner[i + 1] # count values in current bin, advance to next bin while j < lenidx and (values[j] < r_bin or (closed == 'right' and values[j] == r_bin)): j += 1 bins[bc] = j bc += 1 return bins
python
def generate_bins_generic(values, binner, closed): """ Generate bin edge offsets and bin labels for one array using another array which has bin edge values. Both arrays must be sorted. Parameters ---------- values : array of values binner : a comparable array of values representing bins into which to bin the first array. Note, 'values' end-points must fall within 'binner' end-points. closed : which end of bin is closed; left (default), right Returns ------- bins : array of offsets (into 'values' argument) of bins. Zero and last edge are excluded in result, so for instance the first bin is values[0:bin[0]] and the last is values[bin[-1]:] """ lenidx = len(values) lenbin = len(binner) if lenidx <= 0 or lenbin <= 0: raise ValueError("Invalid length for values or for binner") # check binner fits data if values[0] < binner[0]: raise ValueError("Values falls before first bin") if values[lenidx - 1] > binner[lenbin - 1]: raise ValueError("Values falls after last bin") bins = np.empty(lenbin - 1, dtype=np.int64) j = 0 # index into values bc = 0 # bin count # linear scan, presume nothing about values/binner except that it fits ok for i in range(0, lenbin - 1): r_bin = binner[i + 1] # count values in current bin, advance to next bin while j < lenidx and (values[j] < r_bin or (closed == 'right' and values[j] == r_bin)): j += 1 bins[bc] = j bc += 1 return bins
[ "def", "generate_bins_generic", "(", "values", ",", "binner", ",", "closed", ")", ":", "lenidx", "=", "len", "(", "values", ")", "lenbin", "=", "len", "(", "binner", ")", "if", "lenidx", "<=", "0", "or", "lenbin", "<=", "0", ":", "raise", "ValueError", "(", "\"Invalid length for values or for binner\"", ")", "# check binner fits data", "if", "values", "[", "0", "]", "<", "binner", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Values falls before first bin\"", ")", "if", "values", "[", "lenidx", "-", "1", "]", ">", "binner", "[", "lenbin", "-", "1", "]", ":", "raise", "ValueError", "(", "\"Values falls after last bin\"", ")", "bins", "=", "np", ".", "empty", "(", "lenbin", "-", "1", ",", "dtype", "=", "np", ".", "int64", ")", "j", "=", "0", "# index into values", "bc", "=", "0", "# bin count", "# linear scan, presume nothing about values/binner except that it fits ok", "for", "i", "in", "range", "(", "0", ",", "lenbin", "-", "1", ")", ":", "r_bin", "=", "binner", "[", "i", "+", "1", "]", "# count values in current bin, advance to next bin", "while", "j", "<", "lenidx", "and", "(", "values", "[", "j", "]", "<", "r_bin", "or", "(", "closed", "==", "'right'", "and", "values", "[", "j", "]", "==", "r_bin", ")", ")", ":", "j", "+=", "1", "bins", "[", "bc", "]", "=", "j", "bc", "+=", "1", "return", "bins" ]
Generate bin edge offsets and bin labels for one array using another array which has bin edge values. Both arrays must be sorted. Parameters ---------- values : array of values binner : a comparable array of values representing bins into which to bin the first array. Note, 'values' end-points must fall within 'binner' end-points. closed : which end of bin is closed; left (default), right Returns ------- bins : array of offsets (into 'values' argument) of bins. Zero and last edge are excluded in result, so for instance the first bin is values[0:bin[0]] and the last is values[bin[-1]:]
[ "Generate", "bin", "edge", "offsets", "and", "bin", "labels", "for", "one", "array", "using", "another", "array", "which", "has", "bin", "edge", "values", ".", "Both", "arrays", "must", "be", "sorted", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/ops.py#L40-L89
19,457
pandas-dev/pandas
pandas/core/groupby/ops.py
BaseGrouper.size
def size(self): """ Compute group sizes """ ids, _, ngroup = self.group_info ids = ensure_platform_int(ids) if ngroup: out = np.bincount(ids[ids != -1], minlength=ngroup) else: out = [] return Series(out, index=self.result_index, dtype='int64')
python
def size(self): """ Compute group sizes """ ids, _, ngroup = self.group_info ids = ensure_platform_int(ids) if ngroup: out = np.bincount(ids[ids != -1], minlength=ngroup) else: out = [] return Series(out, index=self.result_index, dtype='int64')
[ "def", "size", "(", "self", ")", ":", "ids", ",", "_", ",", "ngroup", "=", "self", ".", "group_info", "ids", "=", "ensure_platform_int", "(", "ids", ")", "if", "ngroup", ":", "out", "=", "np", ".", "bincount", "(", "ids", "[", "ids", "!=", "-", "1", "]", ",", "minlength", "=", "ngroup", ")", "else", ":", "out", "=", "[", "]", "return", "Series", "(", "out", ",", "index", "=", "self", ".", "result_index", ",", "dtype", "=", "'int64'", ")" ]
Compute group sizes
[ "Compute", "group", "sizes" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/ops.py#L241-L254
19,458
pandas-dev/pandas
pandas/core/reshape/melt.py
lreshape
def lreshape(data, groups, dropna=True, label=None): """ Reshape long-format data to wide. Generalized inverse of DataFrame.pivot Parameters ---------- data : DataFrame groups : dict {new_name : list_of_columns} dropna : boolean, default True Examples -------- >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526], ... 'team': ['Red Sox', 'Yankees'], ... 'year1': [2007, 2007], 'year2': [2008, 2008]}) >>> data hr1 hr2 team year1 year2 0 514 545 Red Sox 2007 2008 1 573 526 Yankees 2007 2008 >>> pd.lreshape(data, {'year': ['year1', 'year2'], 'hr': ['hr1', 'hr2']}) team year hr 0 Red Sox 2007 514 1 Yankees 2007 573 2 Red Sox 2008 545 3 Yankees 2008 526 Returns ------- reshaped : DataFrame """ if isinstance(groups, dict): keys = list(groups.keys()) values = list(groups.values()) else: keys, values = zip(*groups) all_cols = list(set.union(*[set(x) for x in values])) id_cols = list(data.columns.difference(all_cols)) K = len(values[0]) for seq in values: if len(seq) != K: raise ValueError('All column lists must be same length') mdata = {} pivot_cols = [] for target, names in zip(keys, values): to_concat = [data[col].values for col in names] import pandas.core.dtypes.concat as _concat mdata[target] = _concat._concat_compat(to_concat) pivot_cols.append(target) for col in id_cols: mdata[col] = np.tile(data[col].values, K) if dropna: mask = np.ones(len(mdata[pivot_cols[0]]), dtype=bool) for c in pivot_cols: mask &= notna(mdata[c]) if not mask.all(): mdata = {k: v[mask] for k, v in mdata.items()} return data._constructor(mdata, columns=id_cols + pivot_cols)
python
def lreshape(data, groups, dropna=True, label=None): """ Reshape long-format data to wide. Generalized inverse of DataFrame.pivot Parameters ---------- data : DataFrame groups : dict {new_name : list_of_columns} dropna : boolean, default True Examples -------- >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526], ... 'team': ['Red Sox', 'Yankees'], ... 'year1': [2007, 2007], 'year2': [2008, 2008]}) >>> data hr1 hr2 team year1 year2 0 514 545 Red Sox 2007 2008 1 573 526 Yankees 2007 2008 >>> pd.lreshape(data, {'year': ['year1', 'year2'], 'hr': ['hr1', 'hr2']}) team year hr 0 Red Sox 2007 514 1 Yankees 2007 573 2 Red Sox 2008 545 3 Yankees 2008 526 Returns ------- reshaped : DataFrame """ if isinstance(groups, dict): keys = list(groups.keys()) values = list(groups.values()) else: keys, values = zip(*groups) all_cols = list(set.union(*[set(x) for x in values])) id_cols = list(data.columns.difference(all_cols)) K = len(values[0]) for seq in values: if len(seq) != K: raise ValueError('All column lists must be same length') mdata = {} pivot_cols = [] for target, names in zip(keys, values): to_concat = [data[col].values for col in names] import pandas.core.dtypes.concat as _concat mdata[target] = _concat._concat_compat(to_concat) pivot_cols.append(target) for col in id_cols: mdata[col] = np.tile(data[col].values, K) if dropna: mask = np.ones(len(mdata[pivot_cols[0]]), dtype=bool) for c in pivot_cols: mask &= notna(mdata[c]) if not mask.all(): mdata = {k: v[mask] for k, v in mdata.items()} return data._constructor(mdata, columns=id_cols + pivot_cols)
[ "def", "lreshape", "(", "data", ",", "groups", ",", "dropna", "=", "True", ",", "label", "=", "None", ")", ":", "if", "isinstance", "(", "groups", ",", "dict", ")", ":", "keys", "=", "list", "(", "groups", ".", "keys", "(", ")", ")", "values", "=", "list", "(", "groups", ".", "values", "(", ")", ")", "else", ":", "keys", ",", "values", "=", "zip", "(", "*", "groups", ")", "all_cols", "=", "list", "(", "set", ".", "union", "(", "*", "[", "set", "(", "x", ")", "for", "x", "in", "values", "]", ")", ")", "id_cols", "=", "list", "(", "data", ".", "columns", ".", "difference", "(", "all_cols", ")", ")", "K", "=", "len", "(", "values", "[", "0", "]", ")", "for", "seq", "in", "values", ":", "if", "len", "(", "seq", ")", "!=", "K", ":", "raise", "ValueError", "(", "'All column lists must be same length'", ")", "mdata", "=", "{", "}", "pivot_cols", "=", "[", "]", "for", "target", ",", "names", "in", "zip", "(", "keys", ",", "values", ")", ":", "to_concat", "=", "[", "data", "[", "col", "]", ".", "values", "for", "col", "in", "names", "]", "import", "pandas", ".", "core", ".", "dtypes", ".", "concat", "as", "_concat", "mdata", "[", "target", "]", "=", "_concat", ".", "_concat_compat", "(", "to_concat", ")", "pivot_cols", ".", "append", "(", "target", ")", "for", "col", "in", "id_cols", ":", "mdata", "[", "col", "]", "=", "np", ".", "tile", "(", "data", "[", "col", "]", ".", "values", ",", "K", ")", "if", "dropna", ":", "mask", "=", "np", ".", "ones", "(", "len", "(", "mdata", "[", "pivot_cols", "[", "0", "]", "]", ")", ",", "dtype", "=", "bool", ")", "for", "c", "in", "pivot_cols", ":", "mask", "&=", "notna", "(", "mdata", "[", "c", "]", ")", "if", "not", "mask", ".", "all", "(", ")", ":", "mdata", "=", "{", "k", ":", "v", "[", "mask", "]", "for", "k", ",", "v", "in", "mdata", ".", "items", "(", ")", "}", "return", "data", ".", "_constructor", "(", "mdata", ",", "columns", "=", "id_cols", "+", "pivot_cols", ")" ]
Reshape long-format data to wide. Generalized inverse of DataFrame.pivot Parameters ---------- data : DataFrame groups : dict {new_name : list_of_columns} dropna : boolean, default True Examples -------- >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526], ... 'team': ['Red Sox', 'Yankees'], ... 'year1': [2007, 2007], 'year2': [2008, 2008]}) >>> data hr1 hr2 team year1 year2 0 514 545 Red Sox 2007 2008 1 573 526 Yankees 2007 2008 >>> pd.lreshape(data, {'year': ['year1', 'year2'], 'hr': ['hr1', 'hr2']}) team year hr 0 Red Sox 2007 514 1 Yankees 2007 573 2 Red Sox 2008 545 3 Yankees 2008 526 Returns ------- reshaped : DataFrame
[ "Reshape", "long", "-", "format", "data", "to", "wide", ".", "Generalized", "inverse", "of", "DataFrame", ".", "pivot" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/reshape/melt.py#L108-L175
19,459
pandas-dev/pandas
pandas/core/reshape/melt.py
wide_to_long
def wide_to_long(df, stubnames, i, j, sep="", suffix=r'\d+'): r""" Wide panel to long format. Less flexible but more user-friendly than melt. With stubnames ['A', 'B'], this function expects to find one or more group of columns with format A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,... You specify what you want to call this suffix in the resulting long format with `j` (for example `j='year'`) Each row of these wide variables are assumed to be uniquely identified by `i` (can be a single column name or a list of column names) All remaining variables in the data frame are left intact. Parameters ---------- df : DataFrame The wide-format DataFrame stubnames : str or list-like The stub name(s). The wide format variables are assumed to start with the stub names. i : str or list-like Column(s) to use as id variable(s) j : str The name of the sub-observation variable. What you wish to name your suffix in the long format. sep : str, default "" A character indicating the separation of the variable names in the wide format, to be stripped from the names in the long format. For example, if your column names are A-suffix1, A-suffix2, you can strip the hyphen by specifying `sep='-'` .. versionadded:: 0.20.0 suffix : str, default '\\d+' A regular expression capturing the wanted suffixes. '\\d+' captures numeric suffixes. Suffixes with no numbers could be specified with the negated character class '\\D+'. You can also further disambiguate suffixes, for example, if your wide variables are of the form A-one, B-two,.., and you have an unrelated column A-rating, you can ignore the last one by specifying `suffix='(!?one|two)'` .. versionadded:: 0.20.0 .. versionchanged:: 0.23.0 When all suffixes are numeric, they are cast to int64/float64. Returns ------- DataFrame A DataFrame that contains each stub name as a variable, with new index (i, j). Notes ----- All extra variables are left untouched. This simply uses `pandas.melt` under the hood, but is hard-coded to "do the right thing" in a typical case. Examples -------- >>> np.random.seed(123) >>> df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, ... "A1980" : {0 : "d", 1 : "e", 2 : "f"}, ... "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7}, ... "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1}, ... "X" : dict(zip(range(3), np.random.randn(3))) ... }) >>> df["id"] = df.index >>> df A1970 A1980 B1970 B1980 X id 0 a d 2.5 3.2 -1.085631 0 1 b e 1.2 1.3 0.997345 1 2 c f 0.7 0.1 0.282978 2 >>> pd.wide_to_long(df, ["A", "B"], i="id", j="year") ... # doctest: +NORMALIZE_WHITESPACE X A B id year 0 1970 -1.085631 a 2.5 1 1970 0.997345 b 1.2 2 1970 0.282978 c 0.7 0 1980 -1.085631 d 3.2 1 1980 0.997345 e 1.3 2 1980 0.282978 f 0.1 With multiple id columns >>> df = pd.DataFrame({ ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], ... 'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], ... 'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] ... }) >>> df birth famid ht1 ht2 0 1 1 2.8 3.4 1 2 1 2.9 3.8 2 3 1 2.2 2.9 3 1 2 2.0 3.2 4 2 2 1.8 2.8 5 3 2 1.9 2.4 6 1 3 2.2 3.3 7 2 3 2.3 3.4 8 3 3 2.1 2.9 >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age') >>> l ... # doctest: +NORMALIZE_WHITESPACE ht famid birth age 1 1 1 2.8 2 3.4 2 1 2.9 2 3.8 3 1 2.2 2 2.9 2 1 1 2.0 2 3.2 2 1 1.8 2 2.8 3 1 1.9 2 2.4 3 1 1 2.2 2 3.3 2 1 2.3 2 3.4 3 1 2.1 2 2.9 Going from long back to wide just takes some creative use of `unstack` >>> w = l.unstack() >>> w.columns = w.columns.map('{0[0]}{0[1]}'.format) >>> w.reset_index() famid birth ht1 ht2 0 1 1 2.8 3.4 1 1 2 2.9 3.8 2 1 3 2.2 2.9 3 2 1 2.0 3.2 4 2 2 1.8 2.8 5 2 3 1.9 2.4 6 3 1 2.2 3.3 7 3 2 2.3 3.4 8 3 3 2.1 2.9 Less wieldy column names are also handled >>> np.random.seed(0) >>> df = pd.DataFrame({'A(quarterly)-2010': np.random.rand(3), ... 'A(quarterly)-2011': np.random.rand(3), ... 'B(quarterly)-2010': np.random.rand(3), ... 'B(quarterly)-2011': np.random.rand(3), ... 'X' : np.random.randint(3, size=3)}) >>> df['id'] = df.index >>> df # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS A(quarterly)-2010 A(quarterly)-2011 B(quarterly)-2010 ... 0 0.548814 0.544883 0.437587 ... 1 0.715189 0.423655 0.891773 ... 2 0.602763 0.645894 0.963663 ... X id 0 0 0 1 1 1 2 1 2 >>> pd.wide_to_long(df, ['A(quarterly)', 'B(quarterly)'], i='id', ... j='year', sep='-') ... # doctest: +NORMALIZE_WHITESPACE X A(quarterly) B(quarterly) id year 0 2010 0 0.548814 0.437587 1 2010 1 0.715189 0.891773 2 2010 1 0.602763 0.963663 0 2011 0 0.544883 0.383442 1 2011 1 0.423655 0.791725 2 2011 1 0.645894 0.528895 If we have many columns, we could also use a regex to find our stubnames and pass that list on to wide_to_long >>> stubnames = sorted( ... set([match[0] for match in df.columns.str.findall( ... r'[A-B]\(.*\)').values if match != [] ]) ... ) >>> list(stubnames) ['A(quarterly)', 'B(quarterly)'] All of the above examples have integers as suffixes. It is possible to have non-integers as suffixes. >>> df = pd.DataFrame({ ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], ... 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], ... 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] ... }) >>> df birth famid ht_one ht_two 0 1 1 2.8 3.4 1 2 1 2.9 3.8 2 3 1 2.2 2.9 3 1 2 2.0 3.2 4 2 2 1.8 2.8 5 3 2 1.9 2.4 6 1 3 2.2 3.3 7 2 3 2.3 3.4 8 3 3 2.1 2.9 >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age', sep='_', suffix='\w') >>> l ... # doctest: +NORMALIZE_WHITESPACE ht famid birth age 1 1 one 2.8 two 3.4 2 one 2.9 two 3.8 3 one 2.2 two 2.9 2 1 one 2.0 two 3.2 2 one 1.8 two 2.8 3 one 1.9 two 2.4 3 1 one 2.2 two 3.3 2 one 2.3 two 3.4 3 one 2.1 two 2.9 """ def get_var_names(df, stub, sep, suffix): regex = r'^{stub}{sep}{suffix}$'.format( stub=re.escape(stub), sep=re.escape(sep), suffix=suffix) pattern = re.compile(regex) return [col for col in df.columns if pattern.match(col)] def melt_stub(df, stub, i, j, value_vars, sep): newdf = melt(df, id_vars=i, value_vars=value_vars, value_name=stub.rstrip(sep), var_name=j) newdf[j] = Categorical(newdf[j]) newdf[j] = newdf[j].str.replace(re.escape(stub + sep), "") # GH17627 Cast numerics suffixes to int/float newdf[j] = to_numeric(newdf[j], errors='ignore') return newdf.set_index(i + [j]) if not is_list_like(stubnames): stubnames = [stubnames] else: stubnames = list(stubnames) if any(col in stubnames for col in df.columns): raise ValueError("stubname can't be identical to a column name") if not is_list_like(i): i = [i] else: i = list(i) if df[i].duplicated().any(): raise ValueError("the id variables need to uniquely identify each row") value_vars = [get_var_names(df, stub, sep, suffix) for stub in stubnames] value_vars_flattened = [e for sublist in value_vars for e in sublist] id_vars = list(set(df.columns.tolist()).difference(value_vars_flattened)) melted = [melt_stub(df, s, i, j, v, sep) for s, v in zip(stubnames, value_vars)] melted = melted[0].join(melted[1:], how='outer') if len(i) == 1: new = df[id_vars].set_index(i).join(melted) return new new = df[id_vars].merge(melted.reset_index(), on=i).set_index(i + [j]) return new
python
def wide_to_long(df, stubnames, i, j, sep="", suffix=r'\d+'): r""" Wide panel to long format. Less flexible but more user-friendly than melt. With stubnames ['A', 'B'], this function expects to find one or more group of columns with format A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,... You specify what you want to call this suffix in the resulting long format with `j` (for example `j='year'`) Each row of these wide variables are assumed to be uniquely identified by `i` (can be a single column name or a list of column names) All remaining variables in the data frame are left intact. Parameters ---------- df : DataFrame The wide-format DataFrame stubnames : str or list-like The stub name(s). The wide format variables are assumed to start with the stub names. i : str or list-like Column(s) to use as id variable(s) j : str The name of the sub-observation variable. What you wish to name your suffix in the long format. sep : str, default "" A character indicating the separation of the variable names in the wide format, to be stripped from the names in the long format. For example, if your column names are A-suffix1, A-suffix2, you can strip the hyphen by specifying `sep='-'` .. versionadded:: 0.20.0 suffix : str, default '\\d+' A regular expression capturing the wanted suffixes. '\\d+' captures numeric suffixes. Suffixes with no numbers could be specified with the negated character class '\\D+'. You can also further disambiguate suffixes, for example, if your wide variables are of the form A-one, B-two,.., and you have an unrelated column A-rating, you can ignore the last one by specifying `suffix='(!?one|two)'` .. versionadded:: 0.20.0 .. versionchanged:: 0.23.0 When all suffixes are numeric, they are cast to int64/float64. Returns ------- DataFrame A DataFrame that contains each stub name as a variable, with new index (i, j). Notes ----- All extra variables are left untouched. This simply uses `pandas.melt` under the hood, but is hard-coded to "do the right thing" in a typical case. Examples -------- >>> np.random.seed(123) >>> df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, ... "A1980" : {0 : "d", 1 : "e", 2 : "f"}, ... "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7}, ... "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1}, ... "X" : dict(zip(range(3), np.random.randn(3))) ... }) >>> df["id"] = df.index >>> df A1970 A1980 B1970 B1980 X id 0 a d 2.5 3.2 -1.085631 0 1 b e 1.2 1.3 0.997345 1 2 c f 0.7 0.1 0.282978 2 >>> pd.wide_to_long(df, ["A", "B"], i="id", j="year") ... # doctest: +NORMALIZE_WHITESPACE X A B id year 0 1970 -1.085631 a 2.5 1 1970 0.997345 b 1.2 2 1970 0.282978 c 0.7 0 1980 -1.085631 d 3.2 1 1980 0.997345 e 1.3 2 1980 0.282978 f 0.1 With multiple id columns >>> df = pd.DataFrame({ ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], ... 'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], ... 'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] ... }) >>> df birth famid ht1 ht2 0 1 1 2.8 3.4 1 2 1 2.9 3.8 2 3 1 2.2 2.9 3 1 2 2.0 3.2 4 2 2 1.8 2.8 5 3 2 1.9 2.4 6 1 3 2.2 3.3 7 2 3 2.3 3.4 8 3 3 2.1 2.9 >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age') >>> l ... # doctest: +NORMALIZE_WHITESPACE ht famid birth age 1 1 1 2.8 2 3.4 2 1 2.9 2 3.8 3 1 2.2 2 2.9 2 1 1 2.0 2 3.2 2 1 1.8 2 2.8 3 1 1.9 2 2.4 3 1 1 2.2 2 3.3 2 1 2.3 2 3.4 3 1 2.1 2 2.9 Going from long back to wide just takes some creative use of `unstack` >>> w = l.unstack() >>> w.columns = w.columns.map('{0[0]}{0[1]}'.format) >>> w.reset_index() famid birth ht1 ht2 0 1 1 2.8 3.4 1 1 2 2.9 3.8 2 1 3 2.2 2.9 3 2 1 2.0 3.2 4 2 2 1.8 2.8 5 2 3 1.9 2.4 6 3 1 2.2 3.3 7 3 2 2.3 3.4 8 3 3 2.1 2.9 Less wieldy column names are also handled >>> np.random.seed(0) >>> df = pd.DataFrame({'A(quarterly)-2010': np.random.rand(3), ... 'A(quarterly)-2011': np.random.rand(3), ... 'B(quarterly)-2010': np.random.rand(3), ... 'B(quarterly)-2011': np.random.rand(3), ... 'X' : np.random.randint(3, size=3)}) >>> df['id'] = df.index >>> df # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS A(quarterly)-2010 A(quarterly)-2011 B(quarterly)-2010 ... 0 0.548814 0.544883 0.437587 ... 1 0.715189 0.423655 0.891773 ... 2 0.602763 0.645894 0.963663 ... X id 0 0 0 1 1 1 2 1 2 >>> pd.wide_to_long(df, ['A(quarterly)', 'B(quarterly)'], i='id', ... j='year', sep='-') ... # doctest: +NORMALIZE_WHITESPACE X A(quarterly) B(quarterly) id year 0 2010 0 0.548814 0.437587 1 2010 1 0.715189 0.891773 2 2010 1 0.602763 0.963663 0 2011 0 0.544883 0.383442 1 2011 1 0.423655 0.791725 2 2011 1 0.645894 0.528895 If we have many columns, we could also use a regex to find our stubnames and pass that list on to wide_to_long >>> stubnames = sorted( ... set([match[0] for match in df.columns.str.findall( ... r'[A-B]\(.*\)').values if match != [] ]) ... ) >>> list(stubnames) ['A(quarterly)', 'B(quarterly)'] All of the above examples have integers as suffixes. It is possible to have non-integers as suffixes. >>> df = pd.DataFrame({ ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], ... 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], ... 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] ... }) >>> df birth famid ht_one ht_two 0 1 1 2.8 3.4 1 2 1 2.9 3.8 2 3 1 2.2 2.9 3 1 2 2.0 3.2 4 2 2 1.8 2.8 5 3 2 1.9 2.4 6 1 3 2.2 3.3 7 2 3 2.3 3.4 8 3 3 2.1 2.9 >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age', sep='_', suffix='\w') >>> l ... # doctest: +NORMALIZE_WHITESPACE ht famid birth age 1 1 one 2.8 two 3.4 2 one 2.9 two 3.8 3 one 2.2 two 2.9 2 1 one 2.0 two 3.2 2 one 1.8 two 2.8 3 one 1.9 two 2.4 3 1 one 2.2 two 3.3 2 one 2.3 two 3.4 3 one 2.1 two 2.9 """ def get_var_names(df, stub, sep, suffix): regex = r'^{stub}{sep}{suffix}$'.format( stub=re.escape(stub), sep=re.escape(sep), suffix=suffix) pattern = re.compile(regex) return [col for col in df.columns if pattern.match(col)] def melt_stub(df, stub, i, j, value_vars, sep): newdf = melt(df, id_vars=i, value_vars=value_vars, value_name=stub.rstrip(sep), var_name=j) newdf[j] = Categorical(newdf[j]) newdf[j] = newdf[j].str.replace(re.escape(stub + sep), "") # GH17627 Cast numerics suffixes to int/float newdf[j] = to_numeric(newdf[j], errors='ignore') return newdf.set_index(i + [j]) if not is_list_like(stubnames): stubnames = [stubnames] else: stubnames = list(stubnames) if any(col in stubnames for col in df.columns): raise ValueError("stubname can't be identical to a column name") if not is_list_like(i): i = [i] else: i = list(i) if df[i].duplicated().any(): raise ValueError("the id variables need to uniquely identify each row") value_vars = [get_var_names(df, stub, sep, suffix) for stub in stubnames] value_vars_flattened = [e for sublist in value_vars for e in sublist] id_vars = list(set(df.columns.tolist()).difference(value_vars_flattened)) melted = [melt_stub(df, s, i, j, v, sep) for s, v in zip(stubnames, value_vars)] melted = melted[0].join(melted[1:], how='outer') if len(i) == 1: new = df[id_vars].set_index(i).join(melted) return new new = df[id_vars].merge(melted.reset_index(), on=i).set_index(i + [j]) return new
[ "def", "wide_to_long", "(", "df", ",", "stubnames", ",", "i", ",", "j", ",", "sep", "=", "\"\"", ",", "suffix", "=", "r'\\d+'", ")", ":", "def", "get_var_names", "(", "df", ",", "stub", ",", "sep", ",", "suffix", ")", ":", "regex", "=", "r'^{stub}{sep}{suffix}$'", ".", "format", "(", "stub", "=", "re", ".", "escape", "(", "stub", ")", ",", "sep", "=", "re", ".", "escape", "(", "sep", ")", ",", "suffix", "=", "suffix", ")", "pattern", "=", "re", ".", "compile", "(", "regex", ")", "return", "[", "col", "for", "col", "in", "df", ".", "columns", "if", "pattern", ".", "match", "(", "col", ")", "]", "def", "melt_stub", "(", "df", ",", "stub", ",", "i", ",", "j", ",", "value_vars", ",", "sep", ")", ":", "newdf", "=", "melt", "(", "df", ",", "id_vars", "=", "i", ",", "value_vars", "=", "value_vars", ",", "value_name", "=", "stub", ".", "rstrip", "(", "sep", ")", ",", "var_name", "=", "j", ")", "newdf", "[", "j", "]", "=", "Categorical", "(", "newdf", "[", "j", "]", ")", "newdf", "[", "j", "]", "=", "newdf", "[", "j", "]", ".", "str", ".", "replace", "(", "re", ".", "escape", "(", "stub", "+", "sep", ")", ",", "\"\"", ")", "# GH17627 Cast numerics suffixes to int/float", "newdf", "[", "j", "]", "=", "to_numeric", "(", "newdf", "[", "j", "]", ",", "errors", "=", "'ignore'", ")", "return", "newdf", ".", "set_index", "(", "i", "+", "[", "j", "]", ")", "if", "not", "is_list_like", "(", "stubnames", ")", ":", "stubnames", "=", "[", "stubnames", "]", "else", ":", "stubnames", "=", "list", "(", "stubnames", ")", "if", "any", "(", "col", "in", "stubnames", "for", "col", "in", "df", ".", "columns", ")", ":", "raise", "ValueError", "(", "\"stubname can't be identical to a column name\"", ")", "if", "not", "is_list_like", "(", "i", ")", ":", "i", "=", "[", "i", "]", "else", ":", "i", "=", "list", "(", "i", ")", "if", "df", "[", "i", "]", ".", "duplicated", "(", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "\"the id variables need to uniquely identify each row\"", ")", "value_vars", "=", "[", "get_var_names", "(", "df", ",", "stub", ",", "sep", ",", "suffix", ")", "for", "stub", "in", "stubnames", "]", "value_vars_flattened", "=", "[", "e", "for", "sublist", "in", "value_vars", "for", "e", "in", "sublist", "]", "id_vars", "=", "list", "(", "set", "(", "df", ".", "columns", ".", "tolist", "(", ")", ")", ".", "difference", "(", "value_vars_flattened", ")", ")", "melted", "=", "[", "melt_stub", "(", "df", ",", "s", ",", "i", ",", "j", ",", "v", ",", "sep", ")", "for", "s", ",", "v", "in", "zip", "(", "stubnames", ",", "value_vars", ")", "]", "melted", "=", "melted", "[", "0", "]", ".", "join", "(", "melted", "[", "1", ":", "]", ",", "how", "=", "'outer'", ")", "if", "len", "(", "i", ")", "==", "1", ":", "new", "=", "df", "[", "id_vars", "]", ".", "set_index", "(", "i", ")", ".", "join", "(", "melted", ")", "return", "new", "new", "=", "df", "[", "id_vars", "]", ".", "merge", "(", "melted", ".", "reset_index", "(", ")", ",", "on", "=", "i", ")", ".", "set_index", "(", "i", "+", "[", "j", "]", ")", "return", "new" ]
r""" Wide panel to long format. Less flexible but more user-friendly than melt. With stubnames ['A', 'B'], this function expects to find one or more group of columns with format A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,... You specify what you want to call this suffix in the resulting long format with `j` (for example `j='year'`) Each row of these wide variables are assumed to be uniquely identified by `i` (can be a single column name or a list of column names) All remaining variables in the data frame are left intact. Parameters ---------- df : DataFrame The wide-format DataFrame stubnames : str or list-like The stub name(s). The wide format variables are assumed to start with the stub names. i : str or list-like Column(s) to use as id variable(s) j : str The name of the sub-observation variable. What you wish to name your suffix in the long format. sep : str, default "" A character indicating the separation of the variable names in the wide format, to be stripped from the names in the long format. For example, if your column names are A-suffix1, A-suffix2, you can strip the hyphen by specifying `sep='-'` .. versionadded:: 0.20.0 suffix : str, default '\\d+' A regular expression capturing the wanted suffixes. '\\d+' captures numeric suffixes. Suffixes with no numbers could be specified with the negated character class '\\D+'. You can also further disambiguate suffixes, for example, if your wide variables are of the form A-one, B-two,.., and you have an unrelated column A-rating, you can ignore the last one by specifying `suffix='(!?one|two)'` .. versionadded:: 0.20.0 .. versionchanged:: 0.23.0 When all suffixes are numeric, they are cast to int64/float64. Returns ------- DataFrame A DataFrame that contains each stub name as a variable, with new index (i, j). Notes ----- All extra variables are left untouched. This simply uses `pandas.melt` under the hood, but is hard-coded to "do the right thing" in a typical case. Examples -------- >>> np.random.seed(123) >>> df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, ... "A1980" : {0 : "d", 1 : "e", 2 : "f"}, ... "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7}, ... "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1}, ... "X" : dict(zip(range(3), np.random.randn(3))) ... }) >>> df["id"] = df.index >>> df A1970 A1980 B1970 B1980 X id 0 a d 2.5 3.2 -1.085631 0 1 b e 1.2 1.3 0.997345 1 2 c f 0.7 0.1 0.282978 2 >>> pd.wide_to_long(df, ["A", "B"], i="id", j="year") ... # doctest: +NORMALIZE_WHITESPACE X A B id year 0 1970 -1.085631 a 2.5 1 1970 0.997345 b 1.2 2 1970 0.282978 c 0.7 0 1980 -1.085631 d 3.2 1 1980 0.997345 e 1.3 2 1980 0.282978 f 0.1 With multiple id columns >>> df = pd.DataFrame({ ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], ... 'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], ... 'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] ... }) >>> df birth famid ht1 ht2 0 1 1 2.8 3.4 1 2 1 2.9 3.8 2 3 1 2.2 2.9 3 1 2 2.0 3.2 4 2 2 1.8 2.8 5 3 2 1.9 2.4 6 1 3 2.2 3.3 7 2 3 2.3 3.4 8 3 3 2.1 2.9 >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age') >>> l ... # doctest: +NORMALIZE_WHITESPACE ht famid birth age 1 1 1 2.8 2 3.4 2 1 2.9 2 3.8 3 1 2.2 2 2.9 2 1 1 2.0 2 3.2 2 1 1.8 2 2.8 3 1 1.9 2 2.4 3 1 1 2.2 2 3.3 2 1 2.3 2 3.4 3 1 2.1 2 2.9 Going from long back to wide just takes some creative use of `unstack` >>> w = l.unstack() >>> w.columns = w.columns.map('{0[0]}{0[1]}'.format) >>> w.reset_index() famid birth ht1 ht2 0 1 1 2.8 3.4 1 1 2 2.9 3.8 2 1 3 2.2 2.9 3 2 1 2.0 3.2 4 2 2 1.8 2.8 5 2 3 1.9 2.4 6 3 1 2.2 3.3 7 3 2 2.3 3.4 8 3 3 2.1 2.9 Less wieldy column names are also handled >>> np.random.seed(0) >>> df = pd.DataFrame({'A(quarterly)-2010': np.random.rand(3), ... 'A(quarterly)-2011': np.random.rand(3), ... 'B(quarterly)-2010': np.random.rand(3), ... 'B(quarterly)-2011': np.random.rand(3), ... 'X' : np.random.randint(3, size=3)}) >>> df['id'] = df.index >>> df # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS A(quarterly)-2010 A(quarterly)-2011 B(quarterly)-2010 ... 0 0.548814 0.544883 0.437587 ... 1 0.715189 0.423655 0.891773 ... 2 0.602763 0.645894 0.963663 ... X id 0 0 0 1 1 1 2 1 2 >>> pd.wide_to_long(df, ['A(quarterly)', 'B(quarterly)'], i='id', ... j='year', sep='-') ... # doctest: +NORMALIZE_WHITESPACE X A(quarterly) B(quarterly) id year 0 2010 0 0.548814 0.437587 1 2010 1 0.715189 0.891773 2 2010 1 0.602763 0.963663 0 2011 0 0.544883 0.383442 1 2011 1 0.423655 0.791725 2 2011 1 0.645894 0.528895 If we have many columns, we could also use a regex to find our stubnames and pass that list on to wide_to_long >>> stubnames = sorted( ... set([match[0] for match in df.columns.str.findall( ... r'[A-B]\(.*\)').values if match != [] ]) ... ) >>> list(stubnames) ['A(quarterly)', 'B(quarterly)'] All of the above examples have integers as suffixes. It is possible to have non-integers as suffixes. >>> df = pd.DataFrame({ ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], ... 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], ... 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] ... }) >>> df birth famid ht_one ht_two 0 1 1 2.8 3.4 1 2 1 2.9 3.8 2 3 1 2.2 2.9 3 1 2 2.0 3.2 4 2 2 1.8 2.8 5 3 2 1.9 2.4 6 1 3 2.2 3.3 7 2 3 2.3 3.4 8 3 3 2.1 2.9 >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age', sep='_', suffix='\w') >>> l ... # doctest: +NORMALIZE_WHITESPACE ht famid birth age 1 1 one 2.8 two 3.4 2 one 2.9 two 3.8 3 one 2.2 two 2.9 2 1 one 2.0 two 3.2 2 one 1.8 two 2.8 3 one 1.9 two 2.4 3 1 one 2.2 two 3.3 2 one 2.3 two 3.4 3 one 2.1 two 2.9
[ "r", "Wide", "panel", "to", "long", "format", ".", "Less", "flexible", "but", "more", "user", "-", "friendly", "than", "melt", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/reshape/melt.py#L178-L458
19,460
pandas-dev/pandas
pandas/core/groupby/groupby.py
_GroupBy._get_indices
def _get_indices(self, names): """ Safe get multiple indices, translate keys for datelike to underlying repr. """ def get_converter(s): # possibly convert to the actual key types # in the indices, could be a Timestamp or a np.datetime64 if isinstance(s, (Timestamp, datetime.datetime)): return lambda key: Timestamp(key) elif isinstance(s, np.datetime64): return lambda key: Timestamp(key).asm8 else: return lambda key: key if len(names) == 0: return [] if len(self.indices) > 0: index_sample = next(iter(self.indices)) else: index_sample = None # Dummy sample name_sample = names[0] if isinstance(index_sample, tuple): if not isinstance(name_sample, tuple): msg = ("must supply a tuple to get_group with multiple" " grouping keys") raise ValueError(msg) if not len(name_sample) == len(index_sample): try: # If the original grouper was a tuple return [self.indices[name] for name in names] except KeyError: # turns out it wasn't a tuple msg = ("must supply a same-length tuple to get_group" " with multiple grouping keys") raise ValueError(msg) converters = [get_converter(s) for s in index_sample] names = (tuple(f(n) for f, n in zip(converters, name)) for name in names) else: converter = get_converter(index_sample) names = (converter(name) for name in names) return [self.indices.get(name, []) for name in names]
python
def _get_indices(self, names): """ Safe get multiple indices, translate keys for datelike to underlying repr. """ def get_converter(s): # possibly convert to the actual key types # in the indices, could be a Timestamp or a np.datetime64 if isinstance(s, (Timestamp, datetime.datetime)): return lambda key: Timestamp(key) elif isinstance(s, np.datetime64): return lambda key: Timestamp(key).asm8 else: return lambda key: key if len(names) == 0: return [] if len(self.indices) > 0: index_sample = next(iter(self.indices)) else: index_sample = None # Dummy sample name_sample = names[0] if isinstance(index_sample, tuple): if not isinstance(name_sample, tuple): msg = ("must supply a tuple to get_group with multiple" " grouping keys") raise ValueError(msg) if not len(name_sample) == len(index_sample): try: # If the original grouper was a tuple return [self.indices[name] for name in names] except KeyError: # turns out it wasn't a tuple msg = ("must supply a same-length tuple to get_group" " with multiple grouping keys") raise ValueError(msg) converters = [get_converter(s) for s in index_sample] names = (tuple(f(n) for f, n in zip(converters, name)) for name in names) else: converter = get_converter(index_sample) names = (converter(name) for name in names) return [self.indices.get(name, []) for name in names]
[ "def", "_get_indices", "(", "self", ",", "names", ")", ":", "def", "get_converter", "(", "s", ")", ":", "# possibly convert to the actual key types", "# in the indices, could be a Timestamp or a np.datetime64", "if", "isinstance", "(", "s", ",", "(", "Timestamp", ",", "datetime", ".", "datetime", ")", ")", ":", "return", "lambda", "key", ":", "Timestamp", "(", "key", ")", "elif", "isinstance", "(", "s", ",", "np", ".", "datetime64", ")", ":", "return", "lambda", "key", ":", "Timestamp", "(", "key", ")", ".", "asm8", "else", ":", "return", "lambda", "key", ":", "key", "if", "len", "(", "names", ")", "==", "0", ":", "return", "[", "]", "if", "len", "(", "self", ".", "indices", ")", ">", "0", ":", "index_sample", "=", "next", "(", "iter", "(", "self", ".", "indices", ")", ")", "else", ":", "index_sample", "=", "None", "# Dummy sample", "name_sample", "=", "names", "[", "0", "]", "if", "isinstance", "(", "index_sample", ",", "tuple", ")", ":", "if", "not", "isinstance", "(", "name_sample", ",", "tuple", ")", ":", "msg", "=", "(", "\"must supply a tuple to get_group with multiple\"", "\" grouping keys\"", ")", "raise", "ValueError", "(", "msg", ")", "if", "not", "len", "(", "name_sample", ")", "==", "len", "(", "index_sample", ")", ":", "try", ":", "# If the original grouper was a tuple", "return", "[", "self", ".", "indices", "[", "name", "]", "for", "name", "in", "names", "]", "except", "KeyError", ":", "# turns out it wasn't a tuple", "msg", "=", "(", "\"must supply a same-length tuple to get_group\"", "\" with multiple grouping keys\"", ")", "raise", "ValueError", "(", "msg", ")", "converters", "=", "[", "get_converter", "(", "s", ")", "for", "s", "in", "index_sample", "]", "names", "=", "(", "tuple", "(", "f", "(", "n", ")", "for", "f", ",", "n", "in", "zip", "(", "converters", ",", "name", ")", ")", "for", "name", "in", "names", ")", "else", ":", "converter", "=", "get_converter", "(", "index_sample", ")", "names", "=", "(", "converter", "(", "name", ")", "for", "name", "in", "names", ")", "return", "[", "self", ".", "indices", ".", "get", "(", "name", ",", "[", "]", ")", "for", "name", "in", "names", "]" ]
Safe get multiple indices, translate keys for datelike to underlying repr.
[ "Safe", "get", "multiple", "indices", "translate", "keys", "for", "datelike", "to", "underlying", "repr", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L409-L457
19,461
pandas-dev/pandas
pandas/core/groupby/groupby.py
_GroupBy._set_group_selection
def _set_group_selection(self): """ Create group based selection. Used when selection is not passed directly but instead via a grouper. NOTE: this should be paired with a call to _reset_group_selection """ grp = self.grouper if not (self.as_index and getattr(grp, 'groupings', None) is not None and self.obj.ndim > 1 and self._group_selection is None): return ax = self.obj._info_axis groupers = [g.name for g in grp.groupings if g.level is None and g.in_axis] if len(groupers): # GH12839 clear selected obj cache when group selection changes self._group_selection = ax.difference(Index(groupers), sort=False).tolist() self._reset_cache('_selected_obj')
python
def _set_group_selection(self): """ Create group based selection. Used when selection is not passed directly but instead via a grouper. NOTE: this should be paired with a call to _reset_group_selection """ grp = self.grouper if not (self.as_index and getattr(grp, 'groupings', None) is not None and self.obj.ndim > 1 and self._group_selection is None): return ax = self.obj._info_axis groupers = [g.name for g in grp.groupings if g.level is None and g.in_axis] if len(groupers): # GH12839 clear selected obj cache when group selection changes self._group_selection = ax.difference(Index(groupers), sort=False).tolist() self._reset_cache('_selected_obj')
[ "def", "_set_group_selection", "(", "self", ")", ":", "grp", "=", "self", ".", "grouper", "if", "not", "(", "self", ".", "as_index", "and", "getattr", "(", "grp", ",", "'groupings'", ",", "None", ")", "is", "not", "None", "and", "self", ".", "obj", ".", "ndim", ">", "1", "and", "self", ".", "_group_selection", "is", "None", ")", ":", "return", "ax", "=", "self", ".", "obj", ".", "_info_axis", "groupers", "=", "[", "g", ".", "name", "for", "g", "in", "grp", ".", "groupings", "if", "g", ".", "level", "is", "None", "and", "g", ".", "in_axis", "]", "if", "len", "(", "groupers", ")", ":", "# GH12839 clear selected obj cache when group selection changes", "self", ".", "_group_selection", "=", "ax", ".", "difference", "(", "Index", "(", "groupers", ")", ",", "sort", "=", "False", ")", ".", "tolist", "(", ")", "self", ".", "_reset_cache", "(", "'_selected_obj'", ")" ]
Create group based selection. Used when selection is not passed directly but instead via a grouper. NOTE: this should be paired with a call to _reset_group_selection
[ "Create", "group", "based", "selection", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L487-L510
19,462
pandas-dev/pandas
pandas/core/groupby/groupby.py
_GroupBy.get_group
def get_group(self, name, obj=None): """ Construct NDFrame from group with provided name. Parameters ---------- name : object the name of the group to get as a DataFrame obj : NDFrame, default None the NDFrame to take the DataFrame out of. If it is None, the object groupby was called on will be used Returns ------- group : same type as obj """ if obj is None: obj = self._selected_obj inds = self._get_index(name) if not len(inds): raise KeyError(name) return obj._take(inds, axis=self.axis)
python
def get_group(self, name, obj=None): """ Construct NDFrame from group with provided name. Parameters ---------- name : object the name of the group to get as a DataFrame obj : NDFrame, default None the NDFrame to take the DataFrame out of. If it is None, the object groupby was called on will be used Returns ------- group : same type as obj """ if obj is None: obj = self._selected_obj inds = self._get_index(name) if not len(inds): raise KeyError(name) return obj._take(inds, axis=self.axis)
[ "def", "get_group", "(", "self", ",", "name", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "obj", "=", "self", ".", "_selected_obj", "inds", "=", "self", ".", "_get_index", "(", "name", ")", "if", "not", "len", "(", "inds", ")", ":", "raise", "KeyError", "(", "name", ")", "return", "obj", ".", "_take", "(", "inds", ",", "axis", "=", "self", ".", "axis", ")" ]
Construct NDFrame from group with provided name. Parameters ---------- name : object the name of the group to get as a DataFrame obj : NDFrame, default None the NDFrame to take the DataFrame out of. If it is None, the object groupby was called on will be used Returns ------- group : same type as obj
[ "Construct", "NDFrame", "from", "group", "with", "provided", "name", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L630-L654
19,463
pandas-dev/pandas
pandas/core/groupby/groupby.py
_GroupBy._try_cast
def _try_cast(self, result, obj, numeric_only=False): """ Try to cast the result to our obj original type, we may have roundtripped through object in the mean-time. If numeric_only is True, then only try to cast numerics and not datetimelikes. """ if obj.ndim > 1: dtype = obj._values.dtype else: dtype = obj.dtype if not is_scalar(result): if is_datetime64tz_dtype(dtype): # GH 23683 # Prior results _may_ have been generated in UTC. # Ensure we localize to UTC first before converting # to the target timezone try: result = obj._values._from_sequence( result, dtype='datetime64[ns, UTC]' ) result = result.astype(dtype) except TypeError: # _try_cast was called at a point where the result # was already tz-aware pass elif is_extension_array_dtype(dtype): # The function can return something of any type, so check # if the type is compatible with the calling EA. try: result = obj._values._from_sequence(result, dtype=dtype) except Exception: # https://github.com/pandas-dev/pandas/issues/22850 # pandas has no control over what 3rd-party ExtensionArrays # do in _values_from_sequence. We still want ops to work # though, so we catch any regular Exception. pass elif numeric_only and is_numeric_dtype(dtype) or not numeric_only: result = maybe_downcast_to_dtype(result, dtype) return result
python
def _try_cast(self, result, obj, numeric_only=False): """ Try to cast the result to our obj original type, we may have roundtripped through object in the mean-time. If numeric_only is True, then only try to cast numerics and not datetimelikes. """ if obj.ndim > 1: dtype = obj._values.dtype else: dtype = obj.dtype if not is_scalar(result): if is_datetime64tz_dtype(dtype): # GH 23683 # Prior results _may_ have been generated in UTC. # Ensure we localize to UTC first before converting # to the target timezone try: result = obj._values._from_sequence( result, dtype='datetime64[ns, UTC]' ) result = result.astype(dtype) except TypeError: # _try_cast was called at a point where the result # was already tz-aware pass elif is_extension_array_dtype(dtype): # The function can return something of any type, so check # if the type is compatible with the calling EA. try: result = obj._values._from_sequence(result, dtype=dtype) except Exception: # https://github.com/pandas-dev/pandas/issues/22850 # pandas has no control over what 3rd-party ExtensionArrays # do in _values_from_sequence. We still want ops to work # though, so we catch any regular Exception. pass elif numeric_only and is_numeric_dtype(dtype) or not numeric_only: result = maybe_downcast_to_dtype(result, dtype) return result
[ "def", "_try_cast", "(", "self", ",", "result", ",", "obj", ",", "numeric_only", "=", "False", ")", ":", "if", "obj", ".", "ndim", ">", "1", ":", "dtype", "=", "obj", ".", "_values", ".", "dtype", "else", ":", "dtype", "=", "obj", ".", "dtype", "if", "not", "is_scalar", "(", "result", ")", ":", "if", "is_datetime64tz_dtype", "(", "dtype", ")", ":", "# GH 23683", "# Prior results _may_ have been generated in UTC.", "# Ensure we localize to UTC first before converting", "# to the target timezone", "try", ":", "result", "=", "obj", ".", "_values", ".", "_from_sequence", "(", "result", ",", "dtype", "=", "'datetime64[ns, UTC]'", ")", "result", "=", "result", ".", "astype", "(", "dtype", ")", "except", "TypeError", ":", "# _try_cast was called at a point where the result", "# was already tz-aware", "pass", "elif", "is_extension_array_dtype", "(", "dtype", ")", ":", "# The function can return something of any type, so check", "# if the type is compatible with the calling EA.", "try", ":", "result", "=", "obj", ".", "_values", ".", "_from_sequence", "(", "result", ",", "dtype", "=", "dtype", ")", "except", "Exception", ":", "# https://github.com/pandas-dev/pandas/issues/22850", "# pandas has no control over what 3rd-party ExtensionArrays", "# do in _values_from_sequence. We still want ops to work", "# though, so we catch any regular Exception.", "pass", "elif", "numeric_only", "and", "is_numeric_dtype", "(", "dtype", ")", "or", "not", "numeric_only", ":", "result", "=", "maybe_downcast_to_dtype", "(", "result", ",", "dtype", ")", "return", "result" ]
Try to cast the result to our obj original type, we may have roundtripped through object in the mean-time. If numeric_only is True, then only try to cast numerics and not datetimelikes.
[ "Try", "to", "cast", "the", "result", "to", "our", "obj", "original", "type", "we", "may", "have", "roundtripped", "through", "object", "in", "the", "mean", "-", "time", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L756-L799
19,464
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.sem
def sem(self, ddof=1): """ Compute standard error of the mean of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex. Parameters ---------- ddof : integer, default 1 degrees of freedom """ return self.std(ddof=ddof) / np.sqrt(self.count())
python
def sem(self, ddof=1): """ Compute standard error of the mean of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex. Parameters ---------- ddof : integer, default 1 degrees of freedom """ return self.std(ddof=ddof) / np.sqrt(self.count())
[ "def", "sem", "(", "self", ",", "ddof", "=", "1", ")", ":", "return", "self", ".", "std", "(", "ddof", "=", "ddof", ")", "/", "np", ".", "sqrt", "(", "self", ".", "count", "(", ")", ")" ]
Compute standard error of the mean of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex. Parameters ---------- ddof : integer, default 1 degrees of freedom
[ "Compute", "standard", "error", "of", "the", "mean", "of", "groups", "excluding", "missing", "values", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1224-L1236
19,465
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.size
def size(self): """ Compute group sizes. """ result = self.grouper.size() if isinstance(self.obj, Series): result.name = getattr(self.obj, 'name', None) return result
python
def size(self): """ Compute group sizes. """ result = self.grouper.size() if isinstance(self.obj, Series): result.name = getattr(self.obj, 'name', None) return result
[ "def", "size", "(", "self", ")", ":", "result", "=", "self", ".", "grouper", ".", "size", "(", ")", "if", "isinstance", "(", "self", ".", "obj", ",", "Series", ")", ":", "result", ".", "name", "=", "getattr", "(", "self", ".", "obj", ",", "'name'", ",", "None", ")", "return", "result" ]
Compute group sizes.
[ "Compute", "group", "sizes", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1240-L1248
19,466
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy._add_numeric_operations
def _add_numeric_operations(cls): """ Add numeric operations to the GroupBy generically. """ def groupby_function(name, alias, npfunc, numeric_only=True, _convert=False, min_count=-1): _local_template = "Compute %(f)s of group values" @Substitution(name='groupby', f=name) @Appender(_common_see_also) @Appender(_local_template) def f(self, **kwargs): if 'numeric_only' not in kwargs: kwargs['numeric_only'] = numeric_only if 'min_count' not in kwargs: kwargs['min_count'] = min_count self._set_group_selection() try: return self._cython_agg_general( alias, alt=npfunc, **kwargs) except AssertionError as e: raise SpecificationError(str(e)) except Exception: result = self.aggregate( lambda x: npfunc(x, axis=self.axis)) if _convert: result = result._convert(datetime=True) return result set_function_name(f, name, cls) return f def first_compat(x, axis=0): def first(x): x = x.to_numpy() x = x[notna(x)] if len(x) == 0: return np.nan return x[0] if isinstance(x, DataFrame): return x.apply(first, axis=axis) else: return first(x) def last_compat(x, axis=0): def last(x): x = x.to_numpy() x = x[notna(x)] if len(x) == 0: return np.nan return x[-1] if isinstance(x, DataFrame): return x.apply(last, axis=axis) else: return last(x) cls.sum = groupby_function('sum', 'add', np.sum, min_count=0) cls.prod = groupby_function('prod', 'prod', np.prod, min_count=0) cls.min = groupby_function('min', 'min', np.min, numeric_only=False) cls.max = groupby_function('max', 'max', np.max, numeric_only=False) cls.first = groupby_function('first', 'first', first_compat, numeric_only=False) cls.last = groupby_function('last', 'last', last_compat, numeric_only=False)
python
def _add_numeric_operations(cls): """ Add numeric operations to the GroupBy generically. """ def groupby_function(name, alias, npfunc, numeric_only=True, _convert=False, min_count=-1): _local_template = "Compute %(f)s of group values" @Substitution(name='groupby', f=name) @Appender(_common_see_also) @Appender(_local_template) def f(self, **kwargs): if 'numeric_only' not in kwargs: kwargs['numeric_only'] = numeric_only if 'min_count' not in kwargs: kwargs['min_count'] = min_count self._set_group_selection() try: return self._cython_agg_general( alias, alt=npfunc, **kwargs) except AssertionError as e: raise SpecificationError(str(e)) except Exception: result = self.aggregate( lambda x: npfunc(x, axis=self.axis)) if _convert: result = result._convert(datetime=True) return result set_function_name(f, name, cls) return f def first_compat(x, axis=0): def first(x): x = x.to_numpy() x = x[notna(x)] if len(x) == 0: return np.nan return x[0] if isinstance(x, DataFrame): return x.apply(first, axis=axis) else: return first(x) def last_compat(x, axis=0): def last(x): x = x.to_numpy() x = x[notna(x)] if len(x) == 0: return np.nan return x[-1] if isinstance(x, DataFrame): return x.apply(last, axis=axis) else: return last(x) cls.sum = groupby_function('sum', 'add', np.sum, min_count=0) cls.prod = groupby_function('prod', 'prod', np.prod, min_count=0) cls.min = groupby_function('min', 'min', np.min, numeric_only=False) cls.max = groupby_function('max', 'max', np.max, numeric_only=False) cls.first = groupby_function('first', 'first', first_compat, numeric_only=False) cls.last = groupby_function('last', 'last', last_compat, numeric_only=False)
[ "def", "_add_numeric_operations", "(", "cls", ")", ":", "def", "groupby_function", "(", "name", ",", "alias", ",", "npfunc", ",", "numeric_only", "=", "True", ",", "_convert", "=", "False", ",", "min_count", "=", "-", "1", ")", ":", "_local_template", "=", "\"Compute %(f)s of group values\"", "@", "Substitution", "(", "name", "=", "'groupby'", ",", "f", "=", "name", ")", "@", "Appender", "(", "_common_see_also", ")", "@", "Appender", "(", "_local_template", ")", "def", "f", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'numeric_only'", "not", "in", "kwargs", ":", "kwargs", "[", "'numeric_only'", "]", "=", "numeric_only", "if", "'min_count'", "not", "in", "kwargs", ":", "kwargs", "[", "'min_count'", "]", "=", "min_count", "self", ".", "_set_group_selection", "(", ")", "try", ":", "return", "self", ".", "_cython_agg_general", "(", "alias", ",", "alt", "=", "npfunc", ",", "*", "*", "kwargs", ")", "except", "AssertionError", "as", "e", ":", "raise", "SpecificationError", "(", "str", "(", "e", ")", ")", "except", "Exception", ":", "result", "=", "self", ".", "aggregate", "(", "lambda", "x", ":", "npfunc", "(", "x", ",", "axis", "=", "self", ".", "axis", ")", ")", "if", "_convert", ":", "result", "=", "result", ".", "_convert", "(", "datetime", "=", "True", ")", "return", "result", "set_function_name", "(", "f", ",", "name", ",", "cls", ")", "return", "f", "def", "first_compat", "(", "x", ",", "axis", "=", "0", ")", ":", "def", "first", "(", "x", ")", ":", "x", "=", "x", ".", "to_numpy", "(", ")", "x", "=", "x", "[", "notna", "(", "x", ")", "]", "if", "len", "(", "x", ")", "==", "0", ":", "return", "np", ".", "nan", "return", "x", "[", "0", "]", "if", "isinstance", "(", "x", ",", "DataFrame", ")", ":", "return", "x", ".", "apply", "(", "first", ",", "axis", "=", "axis", ")", "else", ":", "return", "first", "(", "x", ")", "def", "last_compat", "(", "x", ",", "axis", "=", "0", ")", ":", "def", "last", "(", "x", ")", ":", "x", "=", "x", ".", "to_numpy", "(", ")", "x", "=", "x", "[", "notna", "(", "x", ")", "]", "if", "len", "(", "x", ")", "==", "0", ":", "return", "np", ".", "nan", "return", "x", "[", "-", "1", "]", "if", "isinstance", "(", "x", ",", "DataFrame", ")", ":", "return", "x", ".", "apply", "(", "last", ",", "axis", "=", "axis", ")", "else", ":", "return", "last", "(", "x", ")", "cls", ".", "sum", "=", "groupby_function", "(", "'sum'", ",", "'add'", ",", "np", ".", "sum", ",", "min_count", "=", "0", ")", "cls", ".", "prod", "=", "groupby_function", "(", "'prod'", ",", "'prod'", ",", "np", ".", "prod", ",", "min_count", "=", "0", ")", "cls", ".", "min", "=", "groupby_function", "(", "'min'", ",", "'min'", ",", "np", ".", "min", ",", "numeric_only", "=", "False", ")", "cls", ".", "max", "=", "groupby_function", "(", "'max'", ",", "'max'", ",", "np", ".", "max", ",", "numeric_only", "=", "False", ")", "cls", ".", "first", "=", "groupby_function", "(", "'first'", ",", "'first'", ",", "first_compat", ",", "numeric_only", "=", "False", ")", "cls", ".", "last", "=", "groupby_function", "(", "'last'", ",", "'last'", ",", "last_compat", ",", "numeric_only", "=", "False", ")" ]
Add numeric operations to the GroupBy generically.
[ "Add", "numeric", "operations", "to", "the", "GroupBy", "generically", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1251-L1324
19,467
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.resample
def resample(self, rule, *args, **kwargs): """ Provide resampling when using a TimeGrouper. Given a grouper, the function resamples it according to a string "string" -> "frequency". See the :ref:`frequency aliases <timeseries.offset_aliases>` documentation for more details. Parameters ---------- rule : str or DateOffset The offset string or object representing target grouper conversion. *args, **kwargs Possible arguments are `how`, `fill_method`, `limit`, `kind` and `on`, and other arguments of `TimeGrouper`. Returns ------- Grouper Return a new grouper with our resampler appended. See Also -------- Grouper : Specify a frequency to resample with when grouping by a key. DatetimeIndex.resample : Frequency conversion and resampling of time series. Examples -------- >>> idx = pd.date_range('1/1/2000', periods=4, freq='T') >>> df = pd.DataFrame(data=4 * [range(2)], ... index=idx, ... columns=['a', 'b']) >>> df.iloc[2, 0] = 5 >>> df a b 2000-01-01 00:00:00 0 1 2000-01-01 00:01:00 0 1 2000-01-01 00:02:00 5 1 2000-01-01 00:03:00 0 1 Downsample the DataFrame into 3 minute bins and sum the values of the timestamps falling into a bin. >>> df.groupby('a').resample('3T').sum() a b a 0 2000-01-01 00:00:00 0 2 2000-01-01 00:03:00 0 1 5 2000-01-01 00:00:00 5 1 Upsample the series into 30 second bins. >>> df.groupby('a').resample('30S').sum() a b a 0 2000-01-01 00:00:00 0 1 2000-01-01 00:00:30 0 0 2000-01-01 00:01:00 0 1 2000-01-01 00:01:30 0 0 2000-01-01 00:02:00 0 0 2000-01-01 00:02:30 0 0 2000-01-01 00:03:00 0 1 5 2000-01-01 00:02:00 5 1 Resample by month. Values are assigned to the month of the period. >>> df.groupby('a').resample('M').sum() a b a 0 2000-01-31 0 3 5 2000-01-31 5 1 Downsample the series into 3 minute bins as above, but close the right side of the bin interval. >>> df.groupby('a').resample('3T', closed='right').sum() a b a 0 1999-12-31 23:57:00 0 1 2000-01-01 00:00:00 0 2 5 2000-01-01 00:00:00 5 1 Downsample the series into 3 minute bins and close the right side of the bin interval, but label each bin using the right edge instead of the left. >>> df.groupby('a').resample('3T', closed='right', label='right').sum() a b a 0 2000-01-01 00:00:00 0 1 2000-01-01 00:03:00 0 2 5 2000-01-01 00:03:00 5 1 Add an offset of twenty seconds. >>> df.groupby('a').resample('3T', loffset='20s').sum() a b a 0 2000-01-01 00:00:20 0 2 2000-01-01 00:03:20 0 1 5 2000-01-01 00:00:20 5 1 """ from pandas.core.resample import get_resampler_for_grouping return get_resampler_for_grouping(self, rule, *args, **kwargs)
python
def resample(self, rule, *args, **kwargs): """ Provide resampling when using a TimeGrouper. Given a grouper, the function resamples it according to a string "string" -> "frequency". See the :ref:`frequency aliases <timeseries.offset_aliases>` documentation for more details. Parameters ---------- rule : str or DateOffset The offset string or object representing target grouper conversion. *args, **kwargs Possible arguments are `how`, `fill_method`, `limit`, `kind` and `on`, and other arguments of `TimeGrouper`. Returns ------- Grouper Return a new grouper with our resampler appended. See Also -------- Grouper : Specify a frequency to resample with when grouping by a key. DatetimeIndex.resample : Frequency conversion and resampling of time series. Examples -------- >>> idx = pd.date_range('1/1/2000', periods=4, freq='T') >>> df = pd.DataFrame(data=4 * [range(2)], ... index=idx, ... columns=['a', 'b']) >>> df.iloc[2, 0] = 5 >>> df a b 2000-01-01 00:00:00 0 1 2000-01-01 00:01:00 0 1 2000-01-01 00:02:00 5 1 2000-01-01 00:03:00 0 1 Downsample the DataFrame into 3 minute bins and sum the values of the timestamps falling into a bin. >>> df.groupby('a').resample('3T').sum() a b a 0 2000-01-01 00:00:00 0 2 2000-01-01 00:03:00 0 1 5 2000-01-01 00:00:00 5 1 Upsample the series into 30 second bins. >>> df.groupby('a').resample('30S').sum() a b a 0 2000-01-01 00:00:00 0 1 2000-01-01 00:00:30 0 0 2000-01-01 00:01:00 0 1 2000-01-01 00:01:30 0 0 2000-01-01 00:02:00 0 0 2000-01-01 00:02:30 0 0 2000-01-01 00:03:00 0 1 5 2000-01-01 00:02:00 5 1 Resample by month. Values are assigned to the month of the period. >>> df.groupby('a').resample('M').sum() a b a 0 2000-01-31 0 3 5 2000-01-31 5 1 Downsample the series into 3 minute bins as above, but close the right side of the bin interval. >>> df.groupby('a').resample('3T', closed='right').sum() a b a 0 1999-12-31 23:57:00 0 1 2000-01-01 00:00:00 0 2 5 2000-01-01 00:00:00 5 1 Downsample the series into 3 minute bins and close the right side of the bin interval, but label each bin using the right edge instead of the left. >>> df.groupby('a').resample('3T', closed='right', label='right').sum() a b a 0 2000-01-01 00:00:00 0 1 2000-01-01 00:03:00 0 2 5 2000-01-01 00:03:00 5 1 Add an offset of twenty seconds. >>> df.groupby('a').resample('3T', loffset='20s').sum() a b a 0 2000-01-01 00:00:20 0 2 2000-01-01 00:03:20 0 1 5 2000-01-01 00:00:20 5 1 """ from pandas.core.resample import get_resampler_for_grouping return get_resampler_for_grouping(self, rule, *args, **kwargs)
[ "def", "resample", "(", "self", ",", "rule", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "core", ".", "resample", "import", "get_resampler_for_grouping", "return", "get_resampler_for_grouping", "(", "self", ",", "rule", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Provide resampling when using a TimeGrouper. Given a grouper, the function resamples it according to a string "string" -> "frequency". See the :ref:`frequency aliases <timeseries.offset_aliases>` documentation for more details. Parameters ---------- rule : str or DateOffset The offset string or object representing target grouper conversion. *args, **kwargs Possible arguments are `how`, `fill_method`, `limit`, `kind` and `on`, and other arguments of `TimeGrouper`. Returns ------- Grouper Return a new grouper with our resampler appended. See Also -------- Grouper : Specify a frequency to resample with when grouping by a key. DatetimeIndex.resample : Frequency conversion and resampling of time series. Examples -------- >>> idx = pd.date_range('1/1/2000', periods=4, freq='T') >>> df = pd.DataFrame(data=4 * [range(2)], ... index=idx, ... columns=['a', 'b']) >>> df.iloc[2, 0] = 5 >>> df a b 2000-01-01 00:00:00 0 1 2000-01-01 00:01:00 0 1 2000-01-01 00:02:00 5 1 2000-01-01 00:03:00 0 1 Downsample the DataFrame into 3 minute bins and sum the values of the timestamps falling into a bin. >>> df.groupby('a').resample('3T').sum() a b a 0 2000-01-01 00:00:00 0 2 2000-01-01 00:03:00 0 1 5 2000-01-01 00:00:00 5 1 Upsample the series into 30 second bins. >>> df.groupby('a').resample('30S').sum() a b a 0 2000-01-01 00:00:00 0 1 2000-01-01 00:00:30 0 0 2000-01-01 00:01:00 0 1 2000-01-01 00:01:30 0 0 2000-01-01 00:02:00 0 0 2000-01-01 00:02:30 0 0 2000-01-01 00:03:00 0 1 5 2000-01-01 00:02:00 5 1 Resample by month. Values are assigned to the month of the period. >>> df.groupby('a').resample('M').sum() a b a 0 2000-01-31 0 3 5 2000-01-31 5 1 Downsample the series into 3 minute bins as above, but close the right side of the bin interval. >>> df.groupby('a').resample('3T', closed='right').sum() a b a 0 1999-12-31 23:57:00 0 1 2000-01-01 00:00:00 0 2 5 2000-01-01 00:00:00 5 1 Downsample the series into 3 minute bins and close the right side of the bin interval, but label each bin using the right edge instead of the left. >>> df.groupby('a').resample('3T', closed='right', label='right').sum() a b a 0 2000-01-01 00:00:00 0 1 2000-01-01 00:03:00 0 2 5 2000-01-01 00:03:00 5 1 Add an offset of twenty seconds. >>> df.groupby('a').resample('3T', loffset='20s').sum() a b a 0 2000-01-01 00:00:20 0 2 2000-01-01 00:03:20 0 1 5 2000-01-01 00:00:20 5 1
[ "Provide", "resampling", "when", "using", "a", "TimeGrouper", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1346-L1453
19,468
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.rolling
def rolling(self, *args, **kwargs): """ Return a rolling grouper, providing rolling functionality per group. """ from pandas.core.window import RollingGroupby return RollingGroupby(self, *args, **kwargs)
python
def rolling(self, *args, **kwargs): """ Return a rolling grouper, providing rolling functionality per group. """ from pandas.core.window import RollingGroupby return RollingGroupby(self, *args, **kwargs)
[ "def", "rolling", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "core", ".", "window", "import", "RollingGroupby", "return", "RollingGroupby", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Return a rolling grouper, providing rolling functionality per group.
[ "Return", "a", "rolling", "grouper", "providing", "rolling", "functionality", "per", "group", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1457-L1462
19,469
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.expanding
def expanding(self, *args, **kwargs): """ Return an expanding grouper, providing expanding functionality per group. """ from pandas.core.window import ExpandingGroupby return ExpandingGroupby(self, *args, **kwargs)
python
def expanding(self, *args, **kwargs): """ Return an expanding grouper, providing expanding functionality per group. """ from pandas.core.window import ExpandingGroupby return ExpandingGroupby(self, *args, **kwargs)
[ "def", "expanding", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "core", ".", "window", "import", "ExpandingGroupby", "return", "ExpandingGroupby", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Return an expanding grouper, providing expanding functionality per group.
[ "Return", "an", "expanding", "grouper", "providing", "expanding", "functionality", "per", "group", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1466-L1472
19,470
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy._fill
def _fill(self, direction, limit=None): """ Shared function for `pad` and `backfill` to call Cython method. Parameters ---------- direction : {'ffill', 'bfill'} Direction passed to underlying Cython function. `bfill` will cause values to be filled backwards. `ffill` and any other values will default to a forward fill limit : int, default None Maximum number of consecutive values to fill. If `None`, this method will convert to -1 prior to passing to Cython Returns ------- `Series` or `DataFrame` with filled values See Also -------- pad backfill """ # Need int value for Cython if limit is None: limit = -1 return self._get_cythonized_result('group_fillna_indexer', self.grouper, needs_mask=True, cython_dtype=np.int64, result_is_index=True, direction=direction, limit=limit)
python
def _fill(self, direction, limit=None): """ Shared function for `pad` and `backfill` to call Cython method. Parameters ---------- direction : {'ffill', 'bfill'} Direction passed to underlying Cython function. `bfill` will cause values to be filled backwards. `ffill` and any other values will default to a forward fill limit : int, default None Maximum number of consecutive values to fill. If `None`, this method will convert to -1 prior to passing to Cython Returns ------- `Series` or `DataFrame` with filled values See Also -------- pad backfill """ # Need int value for Cython if limit is None: limit = -1 return self._get_cythonized_result('group_fillna_indexer', self.grouper, needs_mask=True, cython_dtype=np.int64, result_is_index=True, direction=direction, limit=limit)
[ "def", "_fill", "(", "self", ",", "direction", ",", "limit", "=", "None", ")", ":", "# Need int value for Cython", "if", "limit", "is", "None", ":", "limit", "=", "-", "1", "return", "self", ".", "_get_cythonized_result", "(", "'group_fillna_indexer'", ",", "self", ".", "grouper", ",", "needs_mask", "=", "True", ",", "cython_dtype", "=", "np", ".", "int64", ",", "result_is_index", "=", "True", ",", "direction", "=", "direction", ",", "limit", "=", "limit", ")" ]
Shared function for `pad` and `backfill` to call Cython method. Parameters ---------- direction : {'ffill', 'bfill'} Direction passed to underlying Cython function. `bfill` will cause values to be filled backwards. `ffill` and any other values will default to a forward fill limit : int, default None Maximum number of consecutive values to fill. If `None`, this method will convert to -1 prior to passing to Cython Returns ------- `Series` or `DataFrame` with filled values See Also -------- pad backfill
[ "Shared", "function", "for", "pad", "and", "backfill", "to", "call", "Cython", "method", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1474-L1505
19,471
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.quantile
def quantile(self, q=0.5, interpolation='linear'): """ Return group values at the given quantile, a la numpy.percentile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value(s) between 0 and 1 providing the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} Method to use when the desired quantile falls between two points. Returns ------- Series or DataFrame Return type determined by caller of GroupBy object. See Also -------- Series.quantile : Similar method for Series. DataFrame.quantile : Similar method for DataFrame. numpy.percentile : NumPy method to compute qth percentile. Examples -------- >>> df = pd.DataFrame([ ... ['a', 1], ['a', 2], ['a', 3], ... ['b', 1], ['b', 3], ['b', 5] ... ], columns=['key', 'val']) >>> df.groupby('key').quantile() val key a 2.0 b 3.0 """ def pre_processor( vals: np.ndarray ) -> Tuple[np.ndarray, Optional[Type]]: if is_object_dtype(vals): raise TypeError("'quantile' cannot be performed against " "'object' dtypes!") inference = None if is_integer_dtype(vals): inference = np.int64 elif is_datetime64_dtype(vals): inference = 'datetime64[ns]' vals = vals.astype(np.float) return vals, inference def post_processor( vals: np.ndarray, inference: Optional[Type] ) -> np.ndarray: if inference: # Check for edge case if not (is_integer_dtype(inference) and interpolation in {'linear', 'midpoint'}): vals = vals.astype(inference) return vals return self._get_cythonized_result('group_quantile', self.grouper, aggregate=True, needs_values=True, needs_mask=True, cython_dtype=np.float64, pre_processing=pre_processor, post_processing=post_processor, q=q, interpolation=interpolation)
python
def quantile(self, q=0.5, interpolation='linear'): """ Return group values at the given quantile, a la numpy.percentile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value(s) between 0 and 1 providing the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} Method to use when the desired quantile falls between two points. Returns ------- Series or DataFrame Return type determined by caller of GroupBy object. See Also -------- Series.quantile : Similar method for Series. DataFrame.quantile : Similar method for DataFrame. numpy.percentile : NumPy method to compute qth percentile. Examples -------- >>> df = pd.DataFrame([ ... ['a', 1], ['a', 2], ['a', 3], ... ['b', 1], ['b', 3], ['b', 5] ... ], columns=['key', 'val']) >>> df.groupby('key').quantile() val key a 2.0 b 3.0 """ def pre_processor( vals: np.ndarray ) -> Tuple[np.ndarray, Optional[Type]]: if is_object_dtype(vals): raise TypeError("'quantile' cannot be performed against " "'object' dtypes!") inference = None if is_integer_dtype(vals): inference = np.int64 elif is_datetime64_dtype(vals): inference = 'datetime64[ns]' vals = vals.astype(np.float) return vals, inference def post_processor( vals: np.ndarray, inference: Optional[Type] ) -> np.ndarray: if inference: # Check for edge case if not (is_integer_dtype(inference) and interpolation in {'linear', 'midpoint'}): vals = vals.astype(inference) return vals return self._get_cythonized_result('group_quantile', self.grouper, aggregate=True, needs_values=True, needs_mask=True, cython_dtype=np.float64, pre_processing=pre_processor, post_processing=post_processor, q=q, interpolation=interpolation)
[ "def", "quantile", "(", "self", ",", "q", "=", "0.5", ",", "interpolation", "=", "'linear'", ")", ":", "def", "pre_processor", "(", "vals", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "Optional", "[", "Type", "]", "]", ":", "if", "is_object_dtype", "(", "vals", ")", ":", "raise", "TypeError", "(", "\"'quantile' cannot be performed against \"", "\"'object' dtypes!\"", ")", "inference", "=", "None", "if", "is_integer_dtype", "(", "vals", ")", ":", "inference", "=", "np", ".", "int64", "elif", "is_datetime64_dtype", "(", "vals", ")", ":", "inference", "=", "'datetime64[ns]'", "vals", "=", "vals", ".", "astype", "(", "np", ".", "float", ")", "return", "vals", ",", "inference", "def", "post_processor", "(", "vals", ":", "np", ".", "ndarray", ",", "inference", ":", "Optional", "[", "Type", "]", ")", "->", "np", ".", "ndarray", ":", "if", "inference", ":", "# Check for edge case", "if", "not", "(", "is_integer_dtype", "(", "inference", ")", "and", "interpolation", "in", "{", "'linear'", ",", "'midpoint'", "}", ")", ":", "vals", "=", "vals", ".", "astype", "(", "inference", ")", "return", "vals", "return", "self", ".", "_get_cythonized_result", "(", "'group_quantile'", ",", "self", ".", "grouper", ",", "aggregate", "=", "True", ",", "needs_values", "=", "True", ",", "needs_mask", "=", "True", ",", "cython_dtype", "=", "np", ".", "float64", ",", "pre_processing", "=", "pre_processor", ",", "post_processing", "=", "post_processor", ",", "q", "=", "q", ",", "interpolation", "=", "interpolation", ")" ]
Return group values at the given quantile, a la numpy.percentile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value(s) between 0 and 1 providing the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} Method to use when the desired quantile falls between two points. Returns ------- Series or DataFrame Return type determined by caller of GroupBy object. See Also -------- Series.quantile : Similar method for Series. DataFrame.quantile : Similar method for DataFrame. numpy.percentile : NumPy method to compute qth percentile. Examples -------- >>> df = pd.DataFrame([ ... ['a', 1], ['a', 2], ['a', 3], ... ['b', 1], ['b', 3], ['b', 5] ... ], columns=['key', 'val']) >>> df.groupby('key').quantile() val key a 2.0 b 3.0
[ "Return", "group", "values", "at", "the", "given", "quantile", "a", "la", "numpy", ".", "percentile", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1707-L1777
19,472
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.ngroup
def ngroup(self, ascending=True): """ Number each group from 0 to the number of groups - 1. This is the enumerative complement of cumcount. Note that the numbers given to the groups match the order in which the groups would be seen when iterating over the groupby object, not the order they are first observed. .. versionadded:: 0.20.2 Parameters ---------- ascending : bool, default True If False, number in reverse, from number of group - 1 to 0. See Also -------- .cumcount : Number the rows in each group. Examples -------- >>> df = pd.DataFrame({"A": list("aaabba")}) >>> df A 0 a 1 a 2 a 3 b 4 b 5 a >>> df.groupby('A').ngroup() 0 0 1 0 2 0 3 1 4 1 5 0 dtype: int64 >>> df.groupby('A').ngroup(ascending=False) 0 1 1 1 2 1 3 0 4 0 5 1 dtype: int64 >>> df.groupby(["A", [1,1,2,3,2,1]]).ngroup() 0 0 1 0 2 1 3 3 4 2 5 0 dtype: int64 """ with _group_selection_context(self): index = self._selected_obj.index result = Series(self.grouper.group_info[0], index) if not ascending: result = self.ngroups - 1 - result return result
python
def ngroup(self, ascending=True): """ Number each group from 0 to the number of groups - 1. This is the enumerative complement of cumcount. Note that the numbers given to the groups match the order in which the groups would be seen when iterating over the groupby object, not the order they are first observed. .. versionadded:: 0.20.2 Parameters ---------- ascending : bool, default True If False, number in reverse, from number of group - 1 to 0. See Also -------- .cumcount : Number the rows in each group. Examples -------- >>> df = pd.DataFrame({"A": list("aaabba")}) >>> df A 0 a 1 a 2 a 3 b 4 b 5 a >>> df.groupby('A').ngroup() 0 0 1 0 2 0 3 1 4 1 5 0 dtype: int64 >>> df.groupby('A').ngroup(ascending=False) 0 1 1 1 2 1 3 0 4 0 5 1 dtype: int64 >>> df.groupby(["A", [1,1,2,3,2,1]]).ngroup() 0 0 1 0 2 1 3 3 4 2 5 0 dtype: int64 """ with _group_selection_context(self): index = self._selected_obj.index result = Series(self.grouper.group_info[0], index) if not ascending: result = self.ngroups - 1 - result return result
[ "def", "ngroup", "(", "self", ",", "ascending", "=", "True", ")", ":", "with", "_group_selection_context", "(", "self", ")", ":", "index", "=", "self", ".", "_selected_obj", ".", "index", "result", "=", "Series", "(", "self", ".", "grouper", ".", "group_info", "[", "0", "]", ",", "index", ")", "if", "not", "ascending", ":", "result", "=", "self", ".", "ngroups", "-", "1", "-", "result", "return", "result" ]
Number each group from 0 to the number of groups - 1. This is the enumerative complement of cumcount. Note that the numbers given to the groups match the order in which the groups would be seen when iterating over the groupby object, not the order they are first observed. .. versionadded:: 0.20.2 Parameters ---------- ascending : bool, default True If False, number in reverse, from number of group - 1 to 0. See Also -------- .cumcount : Number the rows in each group. Examples -------- >>> df = pd.DataFrame({"A": list("aaabba")}) >>> df A 0 a 1 a 2 a 3 b 4 b 5 a >>> df.groupby('A').ngroup() 0 0 1 0 2 0 3 1 4 1 5 0 dtype: int64 >>> df.groupby('A').ngroup(ascending=False) 0 1 1 1 2 1 3 0 4 0 5 1 dtype: int64 >>> df.groupby(["A", [1,1,2,3,2,1]]).ngroup() 0 0 1 0 2 1 3 3 4 2 5 0 dtype: int64
[ "Number", "each", "group", "from", "0", "to", "the", "number", "of", "groups", "-", "1", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1780-L1843
19,473
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.cumcount
def cumcount(self, ascending=True): """ Number each item in each group from 0 to the length of that group - 1. Essentially this is equivalent to >>> self.apply(lambda x: pd.Series(np.arange(len(x)), x.index)) Parameters ---------- ascending : bool, default True If False, number in reverse, from length of group - 1 to 0. See Also -------- .ngroup : Number the groups themselves. Examples -------- >>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']], ... columns=['A']) >>> df A 0 a 1 a 2 a 3 b 4 b 5 a >>> df.groupby('A').cumcount() 0 0 1 1 2 2 3 0 4 1 5 3 dtype: int64 >>> df.groupby('A').cumcount(ascending=False) 0 3 1 2 2 1 3 1 4 0 5 0 dtype: int64 """ with _group_selection_context(self): index = self._selected_obj.index cumcounts = self._cumcount_array(ascending=ascending) return Series(cumcounts, index)
python
def cumcount(self, ascending=True): """ Number each item in each group from 0 to the length of that group - 1. Essentially this is equivalent to >>> self.apply(lambda x: pd.Series(np.arange(len(x)), x.index)) Parameters ---------- ascending : bool, default True If False, number in reverse, from length of group - 1 to 0. See Also -------- .ngroup : Number the groups themselves. Examples -------- >>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']], ... columns=['A']) >>> df A 0 a 1 a 2 a 3 b 4 b 5 a >>> df.groupby('A').cumcount() 0 0 1 1 2 2 3 0 4 1 5 3 dtype: int64 >>> df.groupby('A').cumcount(ascending=False) 0 3 1 2 2 1 3 1 4 0 5 0 dtype: int64 """ with _group_selection_context(self): index = self._selected_obj.index cumcounts = self._cumcount_array(ascending=ascending) return Series(cumcounts, index)
[ "def", "cumcount", "(", "self", ",", "ascending", "=", "True", ")", ":", "with", "_group_selection_context", "(", "self", ")", ":", "index", "=", "self", ".", "_selected_obj", ".", "index", "cumcounts", "=", "self", ".", "_cumcount_array", "(", "ascending", "=", "ascending", ")", "return", "Series", "(", "cumcounts", ",", "index", ")" ]
Number each item in each group from 0 to the length of that group - 1. Essentially this is equivalent to >>> self.apply(lambda x: pd.Series(np.arange(len(x)), x.index)) Parameters ---------- ascending : bool, default True If False, number in reverse, from length of group - 1 to 0. See Also -------- .ngroup : Number the groups themselves. Examples -------- >>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']], ... columns=['A']) >>> df A 0 a 1 a 2 a 3 b 4 b 5 a >>> df.groupby('A').cumcount() 0 0 1 1 2 2 3 0 4 1 5 3 dtype: int64 >>> df.groupby('A').cumcount(ascending=False) 0 3 1 2 2 1 3 1 4 0 5 0 dtype: int64
[ "Number", "each", "item", "in", "each", "group", "from", "0", "to", "the", "length", "of", "that", "group", "-", "1", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1846-L1897
19,474
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.rank
def rank(self, method='average', ascending=True, na_option='keep', pct=False, axis=0): """ Provide the rank of values within each group. Parameters ---------- method : {'average', 'min', 'max', 'first', 'dense'}, default 'average' * average: average rank of group * min: lowest rank in group * max: highest rank in group * first: ranks assigned in order they appear in the array * dense: like 'min', but rank always increases by 1 between groups ascending : boolean, default True False for ranks by high (1) to low (N) na_option : {'keep', 'top', 'bottom'}, default 'keep' * keep: leave NA values where they are * top: smallest rank if ascending * bottom: smallest rank if descending pct : boolean, default False Compute percentage rank of data within each group axis : int, default 0 The axis of the object over which to compute the rank. Returns ------- DataFrame with ranking of values within each group """ if na_option not in {'keep', 'top', 'bottom'}: msg = "na_option must be one of 'keep', 'top', or 'bottom'" raise ValueError(msg) return self._cython_transform('rank', numeric_only=False, ties_method=method, ascending=ascending, na_option=na_option, pct=pct, axis=axis)
python
def rank(self, method='average', ascending=True, na_option='keep', pct=False, axis=0): """ Provide the rank of values within each group. Parameters ---------- method : {'average', 'min', 'max', 'first', 'dense'}, default 'average' * average: average rank of group * min: lowest rank in group * max: highest rank in group * first: ranks assigned in order they appear in the array * dense: like 'min', but rank always increases by 1 between groups ascending : boolean, default True False for ranks by high (1) to low (N) na_option : {'keep', 'top', 'bottom'}, default 'keep' * keep: leave NA values where they are * top: smallest rank if ascending * bottom: smallest rank if descending pct : boolean, default False Compute percentage rank of data within each group axis : int, default 0 The axis of the object over which to compute the rank. Returns ------- DataFrame with ranking of values within each group """ if na_option not in {'keep', 'top', 'bottom'}: msg = "na_option must be one of 'keep', 'top', or 'bottom'" raise ValueError(msg) return self._cython_transform('rank', numeric_only=False, ties_method=method, ascending=ascending, na_option=na_option, pct=pct, axis=axis)
[ "def", "rank", "(", "self", ",", "method", "=", "'average'", ",", "ascending", "=", "True", ",", "na_option", "=", "'keep'", ",", "pct", "=", "False", ",", "axis", "=", "0", ")", ":", "if", "na_option", "not", "in", "{", "'keep'", ",", "'top'", ",", "'bottom'", "}", ":", "msg", "=", "\"na_option must be one of 'keep', 'top', or 'bottom'\"", "raise", "ValueError", "(", "msg", ")", "return", "self", ".", "_cython_transform", "(", "'rank'", ",", "numeric_only", "=", "False", ",", "ties_method", "=", "method", ",", "ascending", "=", "ascending", ",", "na_option", "=", "na_option", ",", "pct", "=", "pct", ",", "axis", "=", "axis", ")" ]
Provide the rank of values within each group. Parameters ---------- method : {'average', 'min', 'max', 'first', 'dense'}, default 'average' * average: average rank of group * min: lowest rank in group * max: highest rank in group * first: ranks assigned in order they appear in the array * dense: like 'min', but rank always increases by 1 between groups ascending : boolean, default True False for ranks by high (1) to low (N) na_option : {'keep', 'top', 'bottom'}, default 'keep' * keep: leave NA values where they are * top: smallest rank if ascending * bottom: smallest rank if descending pct : boolean, default False Compute percentage rank of data within each group axis : int, default 0 The axis of the object over which to compute the rank. Returns ------- DataFrame with ranking of values within each group
[ "Provide", "the", "rank", "of", "values", "within", "each", "group", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1901-L1934
19,475
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.cumprod
def cumprod(self, axis=0, *args, **kwargs): """ Cumulative product for each group. """ nv.validate_groupby_func('cumprod', args, kwargs, ['numeric_only', 'skipna']) if axis != 0: return self.apply(lambda x: x.cumprod(axis=axis, **kwargs)) return self._cython_transform('cumprod', **kwargs)
python
def cumprod(self, axis=0, *args, **kwargs): """ Cumulative product for each group. """ nv.validate_groupby_func('cumprod', args, kwargs, ['numeric_only', 'skipna']) if axis != 0: return self.apply(lambda x: x.cumprod(axis=axis, **kwargs)) return self._cython_transform('cumprod', **kwargs)
[ "def", "cumprod", "(", "self", ",", "axis", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "nv", ".", "validate_groupby_func", "(", "'cumprod'", ",", "args", ",", "kwargs", ",", "[", "'numeric_only'", ",", "'skipna'", "]", ")", "if", "axis", "!=", "0", ":", "return", "self", ".", "apply", "(", "lambda", "x", ":", "x", ".", "cumprod", "(", "axis", "=", "axis", ",", "*", "*", "kwargs", ")", ")", "return", "self", ".", "_cython_transform", "(", "'cumprod'", ",", "*", "*", "kwargs", ")" ]
Cumulative product for each group.
[ "Cumulative", "product", "for", "each", "group", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1938-L1947
19,476
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.cummin
def cummin(self, axis=0, **kwargs): """ Cumulative min for each group. """ if axis != 0: return self.apply(lambda x: np.minimum.accumulate(x, axis)) return self._cython_transform('cummin', numeric_only=False)
python
def cummin(self, axis=0, **kwargs): """ Cumulative min for each group. """ if axis != 0: return self.apply(lambda x: np.minimum.accumulate(x, axis)) return self._cython_transform('cummin', numeric_only=False)
[ "def", "cummin", "(", "self", ",", "axis", "=", "0", ",", "*", "*", "kwargs", ")", ":", "if", "axis", "!=", "0", ":", "return", "self", ".", "apply", "(", "lambda", "x", ":", "np", ".", "minimum", ".", "accumulate", "(", "x", ",", "axis", ")", ")", "return", "self", ".", "_cython_transform", "(", "'cummin'", ",", "numeric_only", "=", "False", ")" ]
Cumulative min for each group.
[ "Cumulative", "min", "for", "each", "group", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1964-L1971
19,477
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.cummax
def cummax(self, axis=0, **kwargs): """ Cumulative max for each group. """ if axis != 0: return self.apply(lambda x: np.maximum.accumulate(x, axis)) return self._cython_transform('cummax', numeric_only=False)
python
def cummax(self, axis=0, **kwargs): """ Cumulative max for each group. """ if axis != 0: return self.apply(lambda x: np.maximum.accumulate(x, axis)) return self._cython_transform('cummax', numeric_only=False)
[ "def", "cummax", "(", "self", ",", "axis", "=", "0", ",", "*", "*", "kwargs", ")", ":", "if", "axis", "!=", "0", ":", "return", "self", ".", "apply", "(", "lambda", "x", ":", "np", ".", "maximum", ".", "accumulate", "(", "x", ",", "axis", ")", ")", "return", "self", ".", "_cython_transform", "(", "'cummax'", ",", "numeric_only", "=", "False", ")" ]
Cumulative max for each group.
[ "Cumulative", "max", "for", "each", "group", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1975-L1982
19,478
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy._get_cythonized_result
def _get_cythonized_result(self, how, grouper, aggregate=False, cython_dtype=None, needs_values=False, needs_mask=False, needs_ngroups=False, result_is_index=False, pre_processing=None, post_processing=None, **kwargs): """ Get result for Cythonized functions. Parameters ---------- how : str, Cythonized function name to be called grouper : Grouper object containing pertinent group info aggregate : bool, default False Whether the result should be aggregated to match the number of groups cython_dtype : default None Type of the array that will be modified by the Cython call. If `None`, the type will be inferred from the values of each slice needs_values : bool, default False Whether the values should be a part of the Cython call signature needs_mask : bool, default False Whether boolean mask needs to be part of the Cython call signature needs_ngroups : bool, default False Whether number of groups is part of the Cython call signature result_is_index : bool, default False Whether the result of the Cython operation is an index of values to be retrieved, instead of the actual values themselves pre_processing : function, default None Function to be applied to `values` prior to passing to Cython. Function should return a tuple where the first element is the values to be passed to Cython and the second element is an optional type which the values should be converted to after being returned by the Cython operation. Raises if `needs_values` is False. post_processing : function, default None Function to be applied to result of Cython function. Should accept an array of values as the first argument and type inferences as its second argument, i.e. the signature should be (ndarray, Type). **kwargs : dict Extra arguments to be passed back to Cython funcs Returns ------- `Series` or `DataFrame` with filled values """ if result_is_index and aggregate: raise ValueError("'result_is_index' and 'aggregate' cannot both " "be True!") if post_processing: if not callable(pre_processing): raise ValueError("'post_processing' must be a callable!") if pre_processing: if not callable(pre_processing): raise ValueError("'pre_processing' must be a callable!") if not needs_values: raise ValueError("Cannot use 'pre_processing' without " "specifying 'needs_values'!") labels, _, ngroups = grouper.group_info output = collections.OrderedDict() base_func = getattr(libgroupby, how) for name, obj in self._iterate_slices(): if aggregate: result_sz = ngroups else: result_sz = len(obj.values) if not cython_dtype: cython_dtype = obj.values.dtype result = np.zeros(result_sz, dtype=cython_dtype) func = partial(base_func, result, labels) inferences = None if needs_values: vals = obj.values if pre_processing: vals, inferences = pre_processing(vals) func = partial(func, vals) if needs_mask: mask = isna(obj.values).view(np.uint8) func = partial(func, mask) if needs_ngroups: func = partial(func, ngroups) func(**kwargs) # Call func to modify indexer values in place if result_is_index: result = algorithms.take_nd(obj.values, result) if post_processing: result = post_processing(result, inferences) output[name] = result if aggregate: return self._wrap_aggregated_output(output) else: return self._wrap_transformed_output(output)
python
def _get_cythonized_result(self, how, grouper, aggregate=False, cython_dtype=None, needs_values=False, needs_mask=False, needs_ngroups=False, result_is_index=False, pre_processing=None, post_processing=None, **kwargs): """ Get result for Cythonized functions. Parameters ---------- how : str, Cythonized function name to be called grouper : Grouper object containing pertinent group info aggregate : bool, default False Whether the result should be aggregated to match the number of groups cython_dtype : default None Type of the array that will be modified by the Cython call. If `None`, the type will be inferred from the values of each slice needs_values : bool, default False Whether the values should be a part of the Cython call signature needs_mask : bool, default False Whether boolean mask needs to be part of the Cython call signature needs_ngroups : bool, default False Whether number of groups is part of the Cython call signature result_is_index : bool, default False Whether the result of the Cython operation is an index of values to be retrieved, instead of the actual values themselves pre_processing : function, default None Function to be applied to `values` prior to passing to Cython. Function should return a tuple where the first element is the values to be passed to Cython and the second element is an optional type which the values should be converted to after being returned by the Cython operation. Raises if `needs_values` is False. post_processing : function, default None Function to be applied to result of Cython function. Should accept an array of values as the first argument and type inferences as its second argument, i.e. the signature should be (ndarray, Type). **kwargs : dict Extra arguments to be passed back to Cython funcs Returns ------- `Series` or `DataFrame` with filled values """ if result_is_index and aggregate: raise ValueError("'result_is_index' and 'aggregate' cannot both " "be True!") if post_processing: if not callable(pre_processing): raise ValueError("'post_processing' must be a callable!") if pre_processing: if not callable(pre_processing): raise ValueError("'pre_processing' must be a callable!") if not needs_values: raise ValueError("Cannot use 'pre_processing' without " "specifying 'needs_values'!") labels, _, ngroups = grouper.group_info output = collections.OrderedDict() base_func = getattr(libgroupby, how) for name, obj in self._iterate_slices(): if aggregate: result_sz = ngroups else: result_sz = len(obj.values) if not cython_dtype: cython_dtype = obj.values.dtype result = np.zeros(result_sz, dtype=cython_dtype) func = partial(base_func, result, labels) inferences = None if needs_values: vals = obj.values if pre_processing: vals, inferences = pre_processing(vals) func = partial(func, vals) if needs_mask: mask = isna(obj.values).view(np.uint8) func = partial(func, mask) if needs_ngroups: func = partial(func, ngroups) func(**kwargs) # Call func to modify indexer values in place if result_is_index: result = algorithms.take_nd(obj.values, result) if post_processing: result = post_processing(result, inferences) output[name] = result if aggregate: return self._wrap_aggregated_output(output) else: return self._wrap_transformed_output(output)
[ "def", "_get_cythonized_result", "(", "self", ",", "how", ",", "grouper", ",", "aggregate", "=", "False", ",", "cython_dtype", "=", "None", ",", "needs_values", "=", "False", ",", "needs_mask", "=", "False", ",", "needs_ngroups", "=", "False", ",", "result_is_index", "=", "False", ",", "pre_processing", "=", "None", ",", "post_processing", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "result_is_index", "and", "aggregate", ":", "raise", "ValueError", "(", "\"'result_is_index' and 'aggregate' cannot both \"", "\"be True!\"", ")", "if", "post_processing", ":", "if", "not", "callable", "(", "pre_processing", ")", ":", "raise", "ValueError", "(", "\"'post_processing' must be a callable!\"", ")", "if", "pre_processing", ":", "if", "not", "callable", "(", "pre_processing", ")", ":", "raise", "ValueError", "(", "\"'pre_processing' must be a callable!\"", ")", "if", "not", "needs_values", ":", "raise", "ValueError", "(", "\"Cannot use 'pre_processing' without \"", "\"specifying 'needs_values'!\"", ")", "labels", ",", "_", ",", "ngroups", "=", "grouper", ".", "group_info", "output", "=", "collections", ".", "OrderedDict", "(", ")", "base_func", "=", "getattr", "(", "libgroupby", ",", "how", ")", "for", "name", ",", "obj", "in", "self", ".", "_iterate_slices", "(", ")", ":", "if", "aggregate", ":", "result_sz", "=", "ngroups", "else", ":", "result_sz", "=", "len", "(", "obj", ".", "values", ")", "if", "not", "cython_dtype", ":", "cython_dtype", "=", "obj", ".", "values", ".", "dtype", "result", "=", "np", ".", "zeros", "(", "result_sz", ",", "dtype", "=", "cython_dtype", ")", "func", "=", "partial", "(", "base_func", ",", "result", ",", "labels", ")", "inferences", "=", "None", "if", "needs_values", ":", "vals", "=", "obj", ".", "values", "if", "pre_processing", ":", "vals", ",", "inferences", "=", "pre_processing", "(", "vals", ")", "func", "=", "partial", "(", "func", ",", "vals", ")", "if", "needs_mask", ":", "mask", "=", "isna", "(", "obj", ".", "values", ")", ".", "view", "(", "np", ".", "uint8", ")", "func", "=", "partial", "(", "func", ",", "mask", ")", "if", "needs_ngroups", ":", "func", "=", "partial", "(", "func", ",", "ngroups", ")", "func", "(", "*", "*", "kwargs", ")", "# Call func to modify indexer values in place", "if", "result_is_index", ":", "result", "=", "algorithms", ".", "take_nd", "(", "obj", ".", "values", ",", "result", ")", "if", "post_processing", ":", "result", "=", "post_processing", "(", "result", ",", "inferences", ")", "output", "[", "name", "]", "=", "result", "if", "aggregate", ":", "return", "self", ".", "_wrap_aggregated_output", "(", "output", ")", "else", ":", "return", "self", ".", "_wrap_transformed_output", "(", "output", ")" ]
Get result for Cythonized functions. Parameters ---------- how : str, Cythonized function name to be called grouper : Grouper object containing pertinent group info aggregate : bool, default False Whether the result should be aggregated to match the number of groups cython_dtype : default None Type of the array that will be modified by the Cython call. If `None`, the type will be inferred from the values of each slice needs_values : bool, default False Whether the values should be a part of the Cython call signature needs_mask : bool, default False Whether boolean mask needs to be part of the Cython call signature needs_ngroups : bool, default False Whether number of groups is part of the Cython call signature result_is_index : bool, default False Whether the result of the Cython operation is an index of values to be retrieved, instead of the actual values themselves pre_processing : function, default None Function to be applied to `values` prior to passing to Cython. Function should return a tuple where the first element is the values to be passed to Cython and the second element is an optional type which the values should be converted to after being returned by the Cython operation. Raises if `needs_values` is False. post_processing : function, default None Function to be applied to result of Cython function. Should accept an array of values as the first argument and type inferences as its second argument, i.e. the signature should be (ndarray, Type). **kwargs : dict Extra arguments to be passed back to Cython funcs Returns ------- `Series` or `DataFrame` with filled values
[ "Get", "result", "for", "Cythonized", "functions", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1984-L2088
19,479
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.shift
def shift(self, periods=1, freq=None, axis=0, fill_value=None): """ Shift each group by periods observations. Parameters ---------- periods : integer, default 1 number of periods to shift freq : frequency string axis : axis to shift, default 0 fill_value : optional .. versionadded:: 0.24.0 """ if freq is not None or axis != 0 or not isna(fill_value): return self.apply(lambda x: x.shift(periods, freq, axis, fill_value)) return self._get_cythonized_result('group_shift_indexer', self.grouper, cython_dtype=np.int64, needs_ngroups=True, result_is_index=True, periods=periods)
python
def shift(self, periods=1, freq=None, axis=0, fill_value=None): """ Shift each group by periods observations. Parameters ---------- periods : integer, default 1 number of periods to shift freq : frequency string axis : axis to shift, default 0 fill_value : optional .. versionadded:: 0.24.0 """ if freq is not None or axis != 0 or not isna(fill_value): return self.apply(lambda x: x.shift(periods, freq, axis, fill_value)) return self._get_cythonized_result('group_shift_indexer', self.grouper, cython_dtype=np.int64, needs_ngroups=True, result_is_index=True, periods=periods)
[ "def", "shift", "(", "self", ",", "periods", "=", "1", ",", "freq", "=", "None", ",", "axis", "=", "0", ",", "fill_value", "=", "None", ")", ":", "if", "freq", "is", "not", "None", "or", "axis", "!=", "0", "or", "not", "isna", "(", "fill_value", ")", ":", "return", "self", ".", "apply", "(", "lambda", "x", ":", "x", ".", "shift", "(", "periods", ",", "freq", ",", "axis", ",", "fill_value", ")", ")", "return", "self", ".", "_get_cythonized_result", "(", "'group_shift_indexer'", ",", "self", ".", "grouper", ",", "cython_dtype", "=", "np", ".", "int64", ",", "needs_ngroups", "=", "True", ",", "result_is_index", "=", "True", ",", "periods", "=", "periods", ")" ]
Shift each group by periods observations. Parameters ---------- periods : integer, default 1 number of periods to shift freq : frequency string axis : axis to shift, default 0 fill_value : optional .. versionadded:: 0.24.0
[ "Shift", "each", "group", "by", "periods", "observations", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L2092-L2115
19,480
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.head
def head(self, n=5): """ Return first n rows of each group. Essentially equivalent to ``.apply(lambda x: x.head(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) >>> df.groupby('A', as_index=False).head(1) A B 0 1 2 2 5 6 >>> df.groupby('A').head(1) A B 0 1 2 2 5 6 """ self._reset_group_selection() mask = self._cumcount_array() < n return self._selected_obj[mask]
python
def head(self, n=5): """ Return first n rows of each group. Essentially equivalent to ``.apply(lambda x: x.head(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) >>> df.groupby('A', as_index=False).head(1) A B 0 1 2 2 5 6 >>> df.groupby('A').head(1) A B 0 1 2 2 5 6 """ self._reset_group_selection() mask = self._cumcount_array() < n return self._selected_obj[mask]
[ "def", "head", "(", "self", ",", "n", "=", "5", ")", ":", "self", ".", "_reset_group_selection", "(", ")", "mask", "=", "self", ".", "_cumcount_array", "(", ")", "<", "n", "return", "self", ".", "_selected_obj", "[", "mask", "]" ]
Return first n rows of each group. Essentially equivalent to ``.apply(lambda x: x.head(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) >>> df.groupby('A', as_index=False).head(1) A B 0 1 2 2 5 6 >>> df.groupby('A').head(1) A B 0 1 2 2 5 6
[ "Return", "first", "n", "rows", "of", "each", "group", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L2137-L2160
19,481
pandas-dev/pandas
pandas/core/groupby/groupby.py
GroupBy.tail
def tail(self, n=5): """ Return last n rows of each group. Essentially equivalent to ``.apply(lambda x: x.tail(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]], columns=['A', 'B']) >>> df.groupby('A').tail(1) A B 1 a 2 3 b 2 >>> df.groupby('A').head(1) A B 0 a 1 2 b 1 """ self._reset_group_selection() mask = self._cumcount_array(ascending=False) < n return self._selected_obj[mask]
python
def tail(self, n=5): """ Return last n rows of each group. Essentially equivalent to ``.apply(lambda x: x.tail(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]], columns=['A', 'B']) >>> df.groupby('A').tail(1) A B 1 a 2 3 b 2 >>> df.groupby('A').head(1) A B 0 a 1 2 b 1 """ self._reset_group_selection() mask = self._cumcount_array(ascending=False) < n return self._selected_obj[mask]
[ "def", "tail", "(", "self", ",", "n", "=", "5", ")", ":", "self", ".", "_reset_group_selection", "(", ")", "mask", "=", "self", ".", "_cumcount_array", "(", "ascending", "=", "False", ")", "<", "n", "return", "self", ".", "_selected_obj", "[", "mask", "]" ]
Return last n rows of each group. Essentially equivalent to ``.apply(lambda x: x.tail(n))``, except ignores as_index flag. %(see_also)s Examples -------- >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]], columns=['A', 'B']) >>> df.groupby('A').tail(1) A B 1 a 2 3 b 2 >>> df.groupby('A').head(1) A B 0 a 1 2 b 1
[ "Return", "last", "n", "rows", "of", "each", "group", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L2164-L2187
19,482
pandas-dev/pandas
pandas/tseries/holiday.py
next_monday
def next_monday(dt): """ If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday, use Monday instead """ if dt.weekday() == 5: return dt + timedelta(2) elif dt.weekday() == 6: return dt + timedelta(1) return dt
python
def next_monday(dt): """ If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday, use Monday instead """ if dt.weekday() == 5: return dt + timedelta(2) elif dt.weekday() == 6: return dt + timedelta(1) return dt
[ "def", "next_monday", "(", "dt", ")", ":", "if", "dt", ".", "weekday", "(", ")", "==", "5", ":", "return", "dt", "+", "timedelta", "(", "2", ")", "elif", "dt", ".", "weekday", "(", ")", "==", "6", ":", "return", "dt", "+", "timedelta", "(", "1", ")", "return", "dt" ]
If holiday falls on Saturday, use following Monday instead; if holiday falls on Sunday, use Monday instead
[ "If", "holiday", "falls", "on", "Saturday", "use", "following", "Monday", "instead", ";", "if", "holiday", "falls", "on", "Sunday", "use", "Monday", "instead" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L15-L24
19,483
pandas-dev/pandas
pandas/tseries/holiday.py
previous_friday
def previous_friday(dt): """ If holiday falls on Saturday or Sunday, use previous Friday instead. """ if dt.weekday() == 5: return dt - timedelta(1) elif dt.weekday() == 6: return dt - timedelta(2) return dt
python
def previous_friday(dt): """ If holiday falls on Saturday or Sunday, use previous Friday instead. """ if dt.weekday() == 5: return dt - timedelta(1) elif dt.weekday() == 6: return dt - timedelta(2) return dt
[ "def", "previous_friday", "(", "dt", ")", ":", "if", "dt", ".", "weekday", "(", ")", "==", "5", ":", "return", "dt", "-", "timedelta", "(", "1", ")", "elif", "dt", ".", "weekday", "(", ")", "==", "6", ":", "return", "dt", "-", "timedelta", "(", "2", ")", "return", "dt" ]
If holiday falls on Saturday or Sunday, use previous Friday instead.
[ "If", "holiday", "falls", "on", "Saturday", "or", "Sunday", "use", "previous", "Friday", "instead", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L42-L50
19,484
pandas-dev/pandas
pandas/tseries/holiday.py
next_workday
def next_workday(dt): """ returns next weekday used for observances """ dt += timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt += timedelta(days=1) return dt
python
def next_workday(dt): """ returns next weekday used for observances """ dt += timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt += timedelta(days=1) return dt
[ "def", "next_workday", "(", "dt", ")", ":", "dt", "+=", "timedelta", "(", "days", "=", "1", ")", "while", "dt", ".", "weekday", "(", ")", ">", "4", ":", "# Mon-Fri are 0-4", "dt", "+=", "timedelta", "(", "days", "=", "1", ")", "return", "dt" ]
returns next weekday used for observances
[ "returns", "next", "weekday", "used", "for", "observances" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L87-L95
19,485
pandas-dev/pandas
pandas/tseries/holiday.py
previous_workday
def previous_workday(dt): """ returns previous weekday used for observances """ dt -= timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt -= timedelta(days=1) return dt
python
def previous_workday(dt): """ returns previous weekday used for observances """ dt -= timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt -= timedelta(days=1) return dt
[ "def", "previous_workday", "(", "dt", ")", ":", "dt", "-=", "timedelta", "(", "days", "=", "1", ")", "while", "dt", ".", "weekday", "(", ")", ">", "4", ":", "# Mon-Fri are 0-4", "dt", "-=", "timedelta", "(", "days", "=", "1", ")", "return", "dt" ]
returns previous weekday used for observances
[ "returns", "previous", "weekday", "used", "for", "observances" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L98-L106
19,486
pandas-dev/pandas
pandas/tseries/holiday.py
Holiday.dates
def dates(self, start_date, end_date, return_name=False): """ Calculate holidays observed between start date and end date Parameters ---------- start_date : starting date, datetime-like, optional end_date : ending date, datetime-like, optional return_name : bool, optional, default=False If True, return a series that has dates and holiday names. False will only return dates. """ start_date = Timestamp(start_date) end_date = Timestamp(end_date) filter_start_date = start_date filter_end_date = end_date if self.year is not None: dt = Timestamp(datetime(self.year, self.month, self.day)) if return_name: return Series(self.name, index=[dt]) else: return [dt] dates = self._reference_dates(start_date, end_date) holiday_dates = self._apply_rule(dates) if self.days_of_week is not None: holiday_dates = holiday_dates[np.in1d(holiday_dates.dayofweek, self.days_of_week)] if self.start_date is not None: filter_start_date = max(self.start_date.tz_localize( filter_start_date.tz), filter_start_date) if self.end_date is not None: filter_end_date = min(self.end_date.tz_localize( filter_end_date.tz), filter_end_date) holiday_dates = holiday_dates[(holiday_dates >= filter_start_date) & (holiday_dates <= filter_end_date)] if return_name: return Series(self.name, index=holiday_dates) return holiday_dates
python
def dates(self, start_date, end_date, return_name=False): """ Calculate holidays observed between start date and end date Parameters ---------- start_date : starting date, datetime-like, optional end_date : ending date, datetime-like, optional return_name : bool, optional, default=False If True, return a series that has dates and holiday names. False will only return dates. """ start_date = Timestamp(start_date) end_date = Timestamp(end_date) filter_start_date = start_date filter_end_date = end_date if self.year is not None: dt = Timestamp(datetime(self.year, self.month, self.day)) if return_name: return Series(self.name, index=[dt]) else: return [dt] dates = self._reference_dates(start_date, end_date) holiday_dates = self._apply_rule(dates) if self.days_of_week is not None: holiday_dates = holiday_dates[np.in1d(holiday_dates.dayofweek, self.days_of_week)] if self.start_date is not None: filter_start_date = max(self.start_date.tz_localize( filter_start_date.tz), filter_start_date) if self.end_date is not None: filter_end_date = min(self.end_date.tz_localize( filter_end_date.tz), filter_end_date) holiday_dates = holiday_dates[(holiday_dates >= filter_start_date) & (holiday_dates <= filter_end_date)] if return_name: return Series(self.name, index=holiday_dates) return holiday_dates
[ "def", "dates", "(", "self", ",", "start_date", ",", "end_date", ",", "return_name", "=", "False", ")", ":", "start_date", "=", "Timestamp", "(", "start_date", ")", "end_date", "=", "Timestamp", "(", "end_date", ")", "filter_start_date", "=", "start_date", "filter_end_date", "=", "end_date", "if", "self", ".", "year", "is", "not", "None", ":", "dt", "=", "Timestamp", "(", "datetime", "(", "self", ".", "year", ",", "self", ".", "month", ",", "self", ".", "day", ")", ")", "if", "return_name", ":", "return", "Series", "(", "self", ".", "name", ",", "index", "=", "[", "dt", "]", ")", "else", ":", "return", "[", "dt", "]", "dates", "=", "self", ".", "_reference_dates", "(", "start_date", ",", "end_date", ")", "holiday_dates", "=", "self", ".", "_apply_rule", "(", "dates", ")", "if", "self", ".", "days_of_week", "is", "not", "None", ":", "holiday_dates", "=", "holiday_dates", "[", "np", ".", "in1d", "(", "holiday_dates", ".", "dayofweek", ",", "self", ".", "days_of_week", ")", "]", "if", "self", ".", "start_date", "is", "not", "None", ":", "filter_start_date", "=", "max", "(", "self", ".", "start_date", ".", "tz_localize", "(", "filter_start_date", ".", "tz", ")", ",", "filter_start_date", ")", "if", "self", ".", "end_date", "is", "not", "None", ":", "filter_end_date", "=", "min", "(", "self", ".", "end_date", ".", "tz_localize", "(", "filter_end_date", ".", "tz", ")", ",", "filter_end_date", ")", "holiday_dates", "=", "holiday_dates", "[", "(", "holiday_dates", ">=", "filter_start_date", ")", "&", "(", "holiday_dates", "<=", "filter_end_date", ")", "]", "if", "return_name", ":", "return", "Series", "(", "self", ".", "name", ",", "index", "=", "holiday_dates", ")", "return", "holiday_dates" ]
Calculate holidays observed between start date and end date Parameters ---------- start_date : starting date, datetime-like, optional end_date : ending date, datetime-like, optional return_name : bool, optional, default=False If True, return a series that has dates and holiday names. False will only return dates.
[ "Calculate", "holidays", "observed", "between", "start", "date", "and", "end", "date" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L192-L233
19,487
pandas-dev/pandas
pandas/tseries/holiday.py
Holiday._reference_dates
def _reference_dates(self, start_date, end_date): """ Get reference dates for the holiday. Return reference dates for the holiday also returning the year prior to the start_date and year following the end_date. This ensures that any offsets to be applied will yield the holidays within the passed in dates. """ if self.start_date is not None: start_date = self.start_date.tz_localize(start_date.tz) if self.end_date is not None: end_date = self.end_date.tz_localize(start_date.tz) year_offset = DateOffset(years=1) reference_start_date = Timestamp( datetime(start_date.year - 1, self.month, self.day)) reference_end_date = Timestamp( datetime(end_date.year + 1, self.month, self.day)) # Don't process unnecessary holidays dates = date_range(start=reference_start_date, end=reference_end_date, freq=year_offset, tz=start_date.tz) return dates
python
def _reference_dates(self, start_date, end_date): """ Get reference dates for the holiday. Return reference dates for the holiday also returning the year prior to the start_date and year following the end_date. This ensures that any offsets to be applied will yield the holidays within the passed in dates. """ if self.start_date is not None: start_date = self.start_date.tz_localize(start_date.tz) if self.end_date is not None: end_date = self.end_date.tz_localize(start_date.tz) year_offset = DateOffset(years=1) reference_start_date = Timestamp( datetime(start_date.year - 1, self.month, self.day)) reference_end_date = Timestamp( datetime(end_date.year + 1, self.month, self.day)) # Don't process unnecessary holidays dates = date_range(start=reference_start_date, end=reference_end_date, freq=year_offset, tz=start_date.tz) return dates
[ "def", "_reference_dates", "(", "self", ",", "start_date", ",", "end_date", ")", ":", "if", "self", ".", "start_date", "is", "not", "None", ":", "start_date", "=", "self", ".", "start_date", ".", "tz_localize", "(", "start_date", ".", "tz", ")", "if", "self", ".", "end_date", "is", "not", "None", ":", "end_date", "=", "self", ".", "end_date", ".", "tz_localize", "(", "start_date", ".", "tz", ")", "year_offset", "=", "DateOffset", "(", "years", "=", "1", ")", "reference_start_date", "=", "Timestamp", "(", "datetime", "(", "start_date", ".", "year", "-", "1", ",", "self", ".", "month", ",", "self", ".", "day", ")", ")", "reference_end_date", "=", "Timestamp", "(", "datetime", "(", "end_date", ".", "year", "+", "1", ",", "self", ".", "month", ",", "self", ".", "day", ")", ")", "# Don't process unnecessary holidays", "dates", "=", "date_range", "(", "start", "=", "reference_start_date", ",", "end", "=", "reference_end_date", ",", "freq", "=", "year_offset", ",", "tz", "=", "start_date", ".", "tz", ")", "return", "dates" ]
Get reference dates for the holiday. Return reference dates for the holiday also returning the year prior to the start_date and year following the end_date. This ensures that any offsets to be applied will yield the holidays within the passed in dates.
[ "Get", "reference", "dates", "for", "the", "holiday", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L235-L261
19,488
pandas-dev/pandas
pandas/tseries/holiday.py
AbstractHolidayCalendar.holidays
def holidays(self, start=None, end=None, return_name=False): """ Returns a curve with holidays between start_date and end_date Parameters ---------- start : starting date, datetime-like, optional end : ending date, datetime-like, optional return_name : bool, optional If True, return a series that has dates and holiday names. False will only return a DatetimeIndex of dates. Returns ------- DatetimeIndex of holidays """ if self.rules is None: raise Exception('Holiday Calendar {name} does not have any ' 'rules specified'.format(name=self.name)) if start is None: start = AbstractHolidayCalendar.start_date if end is None: end = AbstractHolidayCalendar.end_date start = Timestamp(start) end = Timestamp(end) holidays = None # If we don't have a cache or the dates are outside the prior cache, we # get them again if (self._cache is None or start < self._cache[0] or end > self._cache[1]): for rule in self.rules: rule_holidays = rule.dates(start, end, return_name=True) if holidays is None: holidays = rule_holidays else: holidays = holidays.append(rule_holidays) self._cache = (start, end, holidays.sort_index()) holidays = self._cache[2] holidays = holidays[start:end] if return_name: return holidays else: return holidays.index
python
def holidays(self, start=None, end=None, return_name=False): """ Returns a curve with holidays between start_date and end_date Parameters ---------- start : starting date, datetime-like, optional end : ending date, datetime-like, optional return_name : bool, optional If True, return a series that has dates and holiday names. False will only return a DatetimeIndex of dates. Returns ------- DatetimeIndex of holidays """ if self.rules is None: raise Exception('Holiday Calendar {name} does not have any ' 'rules specified'.format(name=self.name)) if start is None: start = AbstractHolidayCalendar.start_date if end is None: end = AbstractHolidayCalendar.end_date start = Timestamp(start) end = Timestamp(end) holidays = None # If we don't have a cache or the dates are outside the prior cache, we # get them again if (self._cache is None or start < self._cache[0] or end > self._cache[1]): for rule in self.rules: rule_holidays = rule.dates(start, end, return_name=True) if holidays is None: holidays = rule_holidays else: holidays = holidays.append(rule_holidays) self._cache = (start, end, holidays.sort_index()) holidays = self._cache[2] holidays = holidays[start:end] if return_name: return holidays else: return holidays.index
[ "def", "holidays", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "return_name", "=", "False", ")", ":", "if", "self", ".", "rules", "is", "None", ":", "raise", "Exception", "(", "'Holiday Calendar {name} does not have any '", "'rules specified'", ".", "format", "(", "name", "=", "self", ".", "name", ")", ")", "if", "start", "is", "None", ":", "start", "=", "AbstractHolidayCalendar", ".", "start_date", "if", "end", "is", "None", ":", "end", "=", "AbstractHolidayCalendar", ".", "end_date", "start", "=", "Timestamp", "(", "start", ")", "end", "=", "Timestamp", "(", "end", ")", "holidays", "=", "None", "# If we don't have a cache or the dates are outside the prior cache, we", "# get them again", "if", "(", "self", ".", "_cache", "is", "None", "or", "start", "<", "self", ".", "_cache", "[", "0", "]", "or", "end", ">", "self", ".", "_cache", "[", "1", "]", ")", ":", "for", "rule", "in", "self", ".", "rules", ":", "rule_holidays", "=", "rule", ".", "dates", "(", "start", ",", "end", ",", "return_name", "=", "True", ")", "if", "holidays", "is", "None", ":", "holidays", "=", "rule_holidays", "else", ":", "holidays", "=", "holidays", ".", "append", "(", "rule_holidays", ")", "self", ".", "_cache", "=", "(", "start", ",", "end", ",", "holidays", ".", "sort_index", "(", ")", ")", "holidays", "=", "self", ".", "_cache", "[", "2", "]", "holidays", "=", "holidays", "[", "start", ":", "end", "]", "if", "return_name", ":", "return", "holidays", "else", ":", "return", "holidays", ".", "index" ]
Returns a curve with holidays between start_date and end_date Parameters ---------- start : starting date, datetime-like, optional end : ending date, datetime-like, optional return_name : bool, optional If True, return a series that has dates and holiday names. False will only return a DatetimeIndex of dates. Returns ------- DatetimeIndex of holidays
[ "Returns", "a", "curve", "with", "holidays", "between", "start_date", "and", "end_date" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L362-L412
19,489
pandas-dev/pandas
pandas/tseries/holiday.py
AbstractHolidayCalendar.merge_class
def merge_class(base, other): """ Merge holiday calendars together. The base calendar will take precedence to other. The merge will be done based on each holiday's name. Parameters ---------- base : AbstractHolidayCalendar instance/subclass or array of Holiday objects other : AbstractHolidayCalendar instance/subclass or array of Holiday objects """ try: other = other.rules except AttributeError: pass if not isinstance(other, list): other = [other] other_holidays = {holiday.name: holiday for holiday in other} try: base = base.rules except AttributeError: pass if not isinstance(base, list): base = [base] base_holidays = {holiday.name: holiday for holiday in base} other_holidays.update(base_holidays) return list(other_holidays.values())
python
def merge_class(base, other): """ Merge holiday calendars together. The base calendar will take precedence to other. The merge will be done based on each holiday's name. Parameters ---------- base : AbstractHolidayCalendar instance/subclass or array of Holiday objects other : AbstractHolidayCalendar instance/subclass or array of Holiday objects """ try: other = other.rules except AttributeError: pass if not isinstance(other, list): other = [other] other_holidays = {holiday.name: holiday for holiday in other} try: base = base.rules except AttributeError: pass if not isinstance(base, list): base = [base] base_holidays = {holiday.name: holiday for holiday in base} other_holidays.update(base_holidays) return list(other_holidays.values())
[ "def", "merge_class", "(", "base", ",", "other", ")", ":", "try", ":", "other", "=", "other", ".", "rules", "except", "AttributeError", ":", "pass", "if", "not", "isinstance", "(", "other", ",", "list", ")", ":", "other", "=", "[", "other", "]", "other_holidays", "=", "{", "holiday", ".", "name", ":", "holiday", "for", "holiday", "in", "other", "}", "try", ":", "base", "=", "base", ".", "rules", "except", "AttributeError", ":", "pass", "if", "not", "isinstance", "(", "base", ",", "list", ")", ":", "base", "=", "[", "base", "]", "base_holidays", "=", "{", "holiday", ".", "name", ":", "holiday", "for", "holiday", "in", "base", "}", "other_holidays", ".", "update", "(", "base_holidays", ")", "return", "list", "(", "other_holidays", ".", "values", "(", ")", ")" ]
Merge holiday calendars together. The base calendar will take precedence to other. The merge will be done based on each holiday's name. Parameters ---------- base : AbstractHolidayCalendar instance/subclass or array of Holiday objects other : AbstractHolidayCalendar instance/subclass or array of Holiday objects
[ "Merge", "holiday", "calendars", "together", ".", "The", "base", "calendar", "will", "take", "precedence", "to", "other", ".", "The", "merge", "will", "be", "done", "based", "on", "each", "holiday", "s", "name", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L415-L447
19,490
pandas-dev/pandas
pandas/tseries/holiday.py
AbstractHolidayCalendar.merge
def merge(self, other, inplace=False): """ Merge holiday calendars together. The caller's class rules take precedence. The merge will be done based on each holiday's name. Parameters ---------- other : holiday calendar inplace : bool (default=False) If True set rule_table to holidays, else return array of Holidays """ holidays = self.merge_class(self, other) if inplace: self.rules = holidays else: return holidays
python
def merge(self, other, inplace=False): """ Merge holiday calendars together. The caller's class rules take precedence. The merge will be done based on each holiday's name. Parameters ---------- other : holiday calendar inplace : bool (default=False) If True set rule_table to holidays, else return array of Holidays """ holidays = self.merge_class(self, other) if inplace: self.rules = holidays else: return holidays
[ "def", "merge", "(", "self", ",", "other", ",", "inplace", "=", "False", ")", ":", "holidays", "=", "self", ".", "merge_class", "(", "self", ",", "other", ")", "if", "inplace", ":", "self", ".", "rules", "=", "holidays", "else", ":", "return", "holidays" ]
Merge holiday calendars together. The caller's class rules take precedence. The merge will be done based on each holiday's name. Parameters ---------- other : holiday calendar inplace : bool (default=False) If True set rule_table to holidays, else return array of Holidays
[ "Merge", "holiday", "calendars", "together", ".", "The", "caller", "s", "class", "rules", "take", "precedence", ".", "The", "merge", "will", "be", "done", "based", "on", "each", "holiday", "s", "name", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L449-L465
19,491
pandas-dev/pandas
pandas/_config/config.py
register_option
def register_option(key, defval, doc='', validator=None, cb=None): """Register an option in the package-wide pandas config object Parameters ---------- key - a fully-qualified key, e.g. "x.y.option - z". defval - the default value of the option doc - a string description of the option validator - a function of a single argument, should raise `ValueError` if called with a value which is not a legal value for the option. cb - a function of a single argument "key", which is called immediately after an option value is set/reset. key is the full name of the option. Returns ------- Nothing. Raises ------ ValueError if `validator` is specified and `defval` is not a valid value. """ import tokenize import keyword key = key.lower() if key in _registered_options: msg = "Option '{key}' has already been registered" raise OptionError(msg.format(key=key)) if key in _reserved_keys: msg = "Option '{key}' is a reserved key" raise OptionError(msg.format(key=key)) # the default value should be legal if validator: validator(defval) # walk the nested dict, creating dicts as needed along the path path = key.split('.') for k in path: if not bool(re.match('^' + tokenize.Name + '$', k)): raise ValueError("{k} is not a valid identifier".format(k=k)) if keyword.iskeyword(k): raise ValueError("{k} is a python keyword".format(k=k)) cursor = _global_config msg = "Path prefix to option '{option}' is already an option" for i, p in enumerate(path[:-1]): if not isinstance(cursor, dict): raise OptionError(msg.format(option='.'.join(path[:i]))) if p not in cursor: cursor[p] = {} cursor = cursor[p] if not isinstance(cursor, dict): raise OptionError(msg.format(option='.'.join(path[:-1]))) cursor[path[-1]] = defval # initialize # save the option metadata _registered_options[key] = RegisteredOption(key=key, defval=defval, doc=doc, validator=validator, cb=cb)
python
def register_option(key, defval, doc='', validator=None, cb=None): """Register an option in the package-wide pandas config object Parameters ---------- key - a fully-qualified key, e.g. "x.y.option - z". defval - the default value of the option doc - a string description of the option validator - a function of a single argument, should raise `ValueError` if called with a value which is not a legal value for the option. cb - a function of a single argument "key", which is called immediately after an option value is set/reset. key is the full name of the option. Returns ------- Nothing. Raises ------ ValueError if `validator` is specified and `defval` is not a valid value. """ import tokenize import keyword key = key.lower() if key in _registered_options: msg = "Option '{key}' has already been registered" raise OptionError(msg.format(key=key)) if key in _reserved_keys: msg = "Option '{key}' is a reserved key" raise OptionError(msg.format(key=key)) # the default value should be legal if validator: validator(defval) # walk the nested dict, creating dicts as needed along the path path = key.split('.') for k in path: if not bool(re.match('^' + tokenize.Name + '$', k)): raise ValueError("{k} is not a valid identifier".format(k=k)) if keyword.iskeyword(k): raise ValueError("{k} is a python keyword".format(k=k)) cursor = _global_config msg = "Path prefix to option '{option}' is already an option" for i, p in enumerate(path[:-1]): if not isinstance(cursor, dict): raise OptionError(msg.format(option='.'.join(path[:i]))) if p not in cursor: cursor[p] = {} cursor = cursor[p] if not isinstance(cursor, dict): raise OptionError(msg.format(option='.'.join(path[:-1]))) cursor[path[-1]] = defval # initialize # save the option metadata _registered_options[key] = RegisteredOption(key=key, defval=defval, doc=doc, validator=validator, cb=cb)
[ "def", "register_option", "(", "key", ",", "defval", ",", "doc", "=", "''", ",", "validator", "=", "None", ",", "cb", "=", "None", ")", ":", "import", "tokenize", "import", "keyword", "key", "=", "key", ".", "lower", "(", ")", "if", "key", "in", "_registered_options", ":", "msg", "=", "\"Option '{key}' has already been registered\"", "raise", "OptionError", "(", "msg", ".", "format", "(", "key", "=", "key", ")", ")", "if", "key", "in", "_reserved_keys", ":", "msg", "=", "\"Option '{key}' is a reserved key\"", "raise", "OptionError", "(", "msg", ".", "format", "(", "key", "=", "key", ")", ")", "# the default value should be legal", "if", "validator", ":", "validator", "(", "defval", ")", "# walk the nested dict, creating dicts as needed along the path", "path", "=", "key", ".", "split", "(", "'.'", ")", "for", "k", "in", "path", ":", "if", "not", "bool", "(", "re", ".", "match", "(", "'^'", "+", "tokenize", ".", "Name", "+", "'$'", ",", "k", ")", ")", ":", "raise", "ValueError", "(", "\"{k} is not a valid identifier\"", ".", "format", "(", "k", "=", "k", ")", ")", "if", "keyword", ".", "iskeyword", "(", "k", ")", ":", "raise", "ValueError", "(", "\"{k} is a python keyword\"", ".", "format", "(", "k", "=", "k", ")", ")", "cursor", "=", "_global_config", "msg", "=", "\"Path prefix to option '{option}' is already an option\"", "for", "i", ",", "p", "in", "enumerate", "(", "path", "[", ":", "-", "1", "]", ")", ":", "if", "not", "isinstance", "(", "cursor", ",", "dict", ")", ":", "raise", "OptionError", "(", "msg", ".", "format", "(", "option", "=", "'.'", ".", "join", "(", "path", "[", ":", "i", "]", ")", ")", ")", "if", "p", "not", "in", "cursor", ":", "cursor", "[", "p", "]", "=", "{", "}", "cursor", "=", "cursor", "[", "p", "]", "if", "not", "isinstance", "(", "cursor", ",", "dict", ")", ":", "raise", "OptionError", "(", "msg", ".", "format", "(", "option", "=", "'.'", ".", "join", "(", "path", "[", ":", "-", "1", "]", ")", ")", ")", "cursor", "[", "path", "[", "-", "1", "]", "]", "=", "defval", "# initialize", "# save the option metadata", "_registered_options", "[", "key", "]", "=", "RegisteredOption", "(", "key", "=", "key", ",", "defval", "=", "defval", ",", "doc", "=", "doc", ",", "validator", "=", "validator", ",", "cb", "=", "cb", ")" ]
Register an option in the package-wide pandas config object Parameters ---------- key - a fully-qualified key, e.g. "x.y.option - z". defval - the default value of the option doc - a string description of the option validator - a function of a single argument, should raise `ValueError` if called with a value which is not a legal value for the option. cb - a function of a single argument "key", which is called immediately after an option value is set/reset. key is the full name of the option. Returns ------- Nothing. Raises ------ ValueError if `validator` is specified and `defval` is not a valid value.
[ "Register", "an", "option", "in", "the", "package", "-", "wide", "pandas", "config", "object" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/_config/config.py#L415-L479
19,492
pandas-dev/pandas
pandas/_config/config.py
deprecate_option
def deprecate_option(key, msg=None, rkey=None, removal_ver=None): """ Mark option `key` as deprecated, if code attempts to access this option, a warning will be produced, using `msg` if given, or a default message if not. if `rkey` is given, any access to the key will be re-routed to `rkey`. Neither the existence of `key` nor that if `rkey` is checked. If they do not exist, any subsequence access will fail as usual, after the deprecation warning is given. Parameters ---------- key - the name of the option to be deprecated. must be a fully-qualified option name (e.g "x.y.z.rkey"). msg - (Optional) a warning message to output when the key is referenced. if no message is given a default message will be emitted. rkey - (Optional) the name of an option to reroute access to. If specified, any referenced `key` will be re-routed to `rkey` including set/get/reset. rkey must be a fully-qualified option name (e.g "x.y.z.rkey"). used by the default message if no `msg` is specified. removal_ver - (Optional) specifies the version in which this option will be removed. used by the default message if no `msg` is specified. Returns ------- Nothing Raises ------ OptionError - if key has already been deprecated. """ key = key.lower() if key in _deprecated_options: msg = "Option '{key}' has already been defined as deprecated." raise OptionError(msg.format(key=key)) _deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver)
python
def deprecate_option(key, msg=None, rkey=None, removal_ver=None): """ Mark option `key` as deprecated, if code attempts to access this option, a warning will be produced, using `msg` if given, or a default message if not. if `rkey` is given, any access to the key will be re-routed to `rkey`. Neither the existence of `key` nor that if `rkey` is checked. If they do not exist, any subsequence access will fail as usual, after the deprecation warning is given. Parameters ---------- key - the name of the option to be deprecated. must be a fully-qualified option name (e.g "x.y.z.rkey"). msg - (Optional) a warning message to output when the key is referenced. if no message is given a default message will be emitted. rkey - (Optional) the name of an option to reroute access to. If specified, any referenced `key` will be re-routed to `rkey` including set/get/reset. rkey must be a fully-qualified option name (e.g "x.y.z.rkey"). used by the default message if no `msg` is specified. removal_ver - (Optional) specifies the version in which this option will be removed. used by the default message if no `msg` is specified. Returns ------- Nothing Raises ------ OptionError - if key has already been deprecated. """ key = key.lower() if key in _deprecated_options: msg = "Option '{key}' has already been defined as deprecated." raise OptionError(msg.format(key=key)) _deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver)
[ "def", "deprecate_option", "(", "key", ",", "msg", "=", "None", ",", "rkey", "=", "None", ",", "removal_ver", "=", "None", ")", ":", "key", "=", "key", ".", "lower", "(", ")", "if", "key", "in", "_deprecated_options", ":", "msg", "=", "\"Option '{key}' has already been defined as deprecated.\"", "raise", "OptionError", "(", "msg", ".", "format", "(", "key", "=", "key", ")", ")", "_deprecated_options", "[", "key", "]", "=", "DeprecatedOption", "(", "key", ",", "msg", ",", "rkey", ",", "removal_ver", ")" ]
Mark option `key` as deprecated, if code attempts to access this option, a warning will be produced, using `msg` if given, or a default message if not. if `rkey` is given, any access to the key will be re-routed to `rkey`. Neither the existence of `key` nor that if `rkey` is checked. If they do not exist, any subsequence access will fail as usual, after the deprecation warning is given. Parameters ---------- key - the name of the option to be deprecated. must be a fully-qualified option name (e.g "x.y.z.rkey"). msg - (Optional) a warning message to output when the key is referenced. if no message is given a default message will be emitted. rkey - (Optional) the name of an option to reroute access to. If specified, any referenced `key` will be re-routed to `rkey` including set/get/reset. rkey must be a fully-qualified option name (e.g "x.y.z.rkey"). used by the default message if no `msg` is specified. removal_ver - (Optional) specifies the version in which this option will be removed. used by the default message if no `msg` is specified. Returns ------- Nothing Raises ------ OptionError - if key has already been deprecated.
[ "Mark", "option", "key", "as", "deprecated", "if", "code", "attempts", "to", "access", "this", "option", "a", "warning", "will", "be", "produced", "using", "msg", "if", "given", "or", "a", "default", "message", "if", "not", ".", "if", "rkey", "is", "given", "any", "access", "to", "the", "key", "will", "be", "re", "-", "routed", "to", "rkey", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/_config/config.py#L482-L527
19,493
pandas-dev/pandas
pandas/_config/config.py
_select_options
def _select_options(pat): """returns a list of keys matching `pat` if pat=="all", returns all registered options """ # short-circuit for exact key if pat in _registered_options: return [pat] # else look through all of them keys = sorted(_registered_options.keys()) if pat == 'all': # reserved key return keys return [k for k in keys if re.search(pat, k, re.I)]
python
def _select_options(pat): """returns a list of keys matching `pat` if pat=="all", returns all registered options """ # short-circuit for exact key if pat in _registered_options: return [pat] # else look through all of them keys = sorted(_registered_options.keys()) if pat == 'all': # reserved key return keys return [k for k in keys if re.search(pat, k, re.I)]
[ "def", "_select_options", "(", "pat", ")", ":", "# short-circuit for exact key", "if", "pat", "in", "_registered_options", ":", "return", "[", "pat", "]", "# else look through all of them", "keys", "=", "sorted", "(", "_registered_options", ".", "keys", "(", ")", ")", "if", "pat", "==", "'all'", ":", "# reserved key", "return", "keys", "return", "[", "k", "for", "k", "in", "keys", "if", "re", ".", "search", "(", "pat", ",", "k", ",", "re", ".", "I", ")", "]" ]
returns a list of keys matching `pat` if pat=="all", returns all registered options
[ "returns", "a", "list", "of", "keys", "matching", "pat" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/_config/config.py#L533-L548
19,494
pandas-dev/pandas
pandas/_config/config.py
_translate_key
def _translate_key(key): """ if key id deprecated and a replacement key defined, will return the replacement key, otherwise returns `key` as - is """ d = _get_deprecated_option(key) if d: return d.rkey or key else: return key
python
def _translate_key(key): """ if key id deprecated and a replacement key defined, will return the replacement key, otherwise returns `key` as - is """ d = _get_deprecated_option(key) if d: return d.rkey or key else: return key
[ "def", "_translate_key", "(", "key", ")", ":", "d", "=", "_get_deprecated_option", "(", "key", ")", "if", "d", ":", "return", "d", ".", "rkey", "or", "key", "else", ":", "return", "key" ]
if key id deprecated and a replacement key defined, will return the replacement key, otherwise returns `key` as - is
[ "if", "key", "id", "deprecated", "and", "a", "replacement", "key", "defined", "will", "return", "the", "replacement", "key", "otherwise", "returns", "key", "as", "-", "is" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/_config/config.py#L594-L604
19,495
pandas-dev/pandas
pandas/_config/config.py
_build_option_description
def _build_option_description(k): """ Builds a formatted description of a registered option and prints it """ o = _get_registered_option(k) d = _get_deprecated_option(k) s = '{k} '.format(k=k) if o.doc: s += '\n'.join(o.doc.strip().split('\n')) else: s += 'No description available.' if o: s += ('\n [default: {default}] [currently: {current}]' .format(default=o.defval, current=_get_option(k, True))) if d: s += '\n (Deprecated' s += (', use `{rkey}` instead.' .format(rkey=d.rkey if d.rkey else '')) s += ')' return s
python
def _build_option_description(k): """ Builds a formatted description of a registered option and prints it """ o = _get_registered_option(k) d = _get_deprecated_option(k) s = '{k} '.format(k=k) if o.doc: s += '\n'.join(o.doc.strip().split('\n')) else: s += 'No description available.' if o: s += ('\n [default: {default}] [currently: {current}]' .format(default=o.defval, current=_get_option(k, True))) if d: s += '\n (Deprecated' s += (', use `{rkey}` instead.' .format(rkey=d.rkey if d.rkey else '')) s += ')' return s
[ "def", "_build_option_description", "(", "k", ")", ":", "o", "=", "_get_registered_option", "(", "k", ")", "d", "=", "_get_deprecated_option", "(", "k", ")", "s", "=", "'{k} '", ".", "format", "(", "k", "=", "k", ")", "if", "o", ".", "doc", ":", "s", "+=", "'\\n'", ".", "join", "(", "o", ".", "doc", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "else", ":", "s", "+=", "'No description available.'", "if", "o", ":", "s", "+=", "(", "'\\n [default: {default}] [currently: {current}]'", ".", "format", "(", "default", "=", "o", ".", "defval", ",", "current", "=", "_get_option", "(", "k", ",", "True", ")", ")", ")", "if", "d", ":", "s", "+=", "'\\n (Deprecated'", "s", "+=", "(", "', use `{rkey}` instead.'", ".", "format", "(", "rkey", "=", "d", ".", "rkey", "if", "d", ".", "rkey", "else", "''", ")", ")", "s", "+=", "')'", "return", "s" ]
Builds a formatted description of a registered option and prints it
[ "Builds", "a", "formatted", "description", "of", "a", "registered", "option", "and", "prints", "it" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/_config/config.py#L636-L659
19,496
pandas-dev/pandas
pandas/_config/config.py
config_prefix
def config_prefix(prefix): """contextmanager for multiple invocations of API with a common prefix supported API functions: (register / get / set )__option Warning: This is not thread - safe, and won't work properly if you import the API functions into your module using the "from x import y" construct. Example: import pandas._config.config as cf with cf.config_prefix("display.font"): cf.register_option("color", "red") cf.register_option("size", " 5 pt") cf.set_option(size, " 6 pt") cf.get_option(size) ... etc' will register options "display.font.color", "display.font.size", set the value of "display.font.size"... and so on. """ # Note: reset_option relies on set_option, and on key directly # it does not fit in to this monkey-patching scheme global register_option, get_option, set_option, reset_option def wrap(func): def inner(key, *args, **kwds): pkey = '{prefix}.{key}'.format(prefix=prefix, key=key) return func(pkey, *args, **kwds) return inner _register_option = register_option _get_option = get_option _set_option = set_option set_option = wrap(set_option) get_option = wrap(get_option) register_option = wrap(register_option) yield None set_option = _set_option get_option = _get_option register_option = _register_option
python
def config_prefix(prefix): """contextmanager for multiple invocations of API with a common prefix supported API functions: (register / get / set )__option Warning: This is not thread - safe, and won't work properly if you import the API functions into your module using the "from x import y" construct. Example: import pandas._config.config as cf with cf.config_prefix("display.font"): cf.register_option("color", "red") cf.register_option("size", " 5 pt") cf.set_option(size, " 6 pt") cf.get_option(size) ... etc' will register options "display.font.color", "display.font.size", set the value of "display.font.size"... and so on. """ # Note: reset_option relies on set_option, and on key directly # it does not fit in to this monkey-patching scheme global register_option, get_option, set_option, reset_option def wrap(func): def inner(key, *args, **kwds): pkey = '{prefix}.{key}'.format(prefix=prefix, key=key) return func(pkey, *args, **kwds) return inner _register_option = register_option _get_option = get_option _set_option = set_option set_option = wrap(set_option) get_option = wrap(get_option) register_option = wrap(register_option) yield None set_option = _set_option get_option = _get_option register_option = _register_option
[ "def", "config_prefix", "(", "prefix", ")", ":", "# Note: reset_option relies on set_option, and on key directly", "# it does not fit in to this monkey-patching scheme", "global", "register_option", ",", "get_option", ",", "set_option", ",", "reset_option", "def", "wrap", "(", "func", ")", ":", "def", "inner", "(", "key", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "pkey", "=", "'{prefix}.{key}'", ".", "format", "(", "prefix", "=", "prefix", ",", "key", "=", "key", ")", "return", "func", "(", "pkey", ",", "*", "args", ",", "*", "*", "kwds", ")", "return", "inner", "_register_option", "=", "register_option", "_get_option", "=", "get_option", "_set_option", "=", "set_option", "set_option", "=", "wrap", "(", "set_option", ")", "get_option", "=", "wrap", "(", "get_option", ")", "register_option", "=", "wrap", "(", "register_option", ")", "yield", "None", "set_option", "=", "_set_option", "get_option", "=", "_get_option", "register_option", "=", "_register_option" ]
contextmanager for multiple invocations of API with a common prefix supported API functions: (register / get / set )__option Warning: This is not thread - safe, and won't work properly if you import the API functions into your module using the "from x import y" construct. Example: import pandas._config.config as cf with cf.config_prefix("display.font"): cf.register_option("color", "red") cf.register_option("size", " 5 pt") cf.set_option(size, " 6 pt") cf.get_option(size) ... etc' will register options "display.font.color", "display.font.size", set the value of "display.font.size"... and so on.
[ "contextmanager", "for", "multiple", "invocations", "of", "API", "with", "a", "common", "prefix" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/_config/config.py#L696-L741
19,497
pandas-dev/pandas
pandas/core/arrays/interval.py
maybe_convert_platform_interval
def maybe_convert_platform_interval(values): """ Try to do platform conversion, with special casing for IntervalArray. Wrapper around maybe_convert_platform that alters the default return dtype in certain cases to be compatible with IntervalArray. For example, empty lists return with integer dtype instead of object dtype, which is prohibited for IntervalArray. Parameters ---------- values : array-like Returns ------- array """ if isinstance(values, (list, tuple)) and len(values) == 0: # GH 19016 # empty lists/tuples get object dtype by default, but this is not # prohibited for IntervalArray, so coerce to integer instead return np.array([], dtype=np.int64) elif is_categorical_dtype(values): values = np.asarray(values) return maybe_convert_platform(values)
python
def maybe_convert_platform_interval(values): """ Try to do platform conversion, with special casing for IntervalArray. Wrapper around maybe_convert_platform that alters the default return dtype in certain cases to be compatible with IntervalArray. For example, empty lists return with integer dtype instead of object dtype, which is prohibited for IntervalArray. Parameters ---------- values : array-like Returns ------- array """ if isinstance(values, (list, tuple)) and len(values) == 0: # GH 19016 # empty lists/tuples get object dtype by default, but this is not # prohibited for IntervalArray, so coerce to integer instead return np.array([], dtype=np.int64) elif is_categorical_dtype(values): values = np.asarray(values) return maybe_convert_platform(values)
[ "def", "maybe_convert_platform_interval", "(", "values", ")", ":", "if", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "values", ")", "==", "0", ":", "# GH 19016", "# empty lists/tuples get object dtype by default, but this is not", "# prohibited for IntervalArray, so coerce to integer instead", "return", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "np", ".", "int64", ")", "elif", "is_categorical_dtype", "(", "values", ")", ":", "values", "=", "np", ".", "asarray", "(", "values", ")", "return", "maybe_convert_platform", "(", "values", ")" ]
Try to do platform conversion, with special casing for IntervalArray. Wrapper around maybe_convert_platform that alters the default return dtype in certain cases to be compatible with IntervalArray. For example, empty lists return with integer dtype instead of object dtype, which is prohibited for IntervalArray. Parameters ---------- values : array-like Returns ------- array
[ "Try", "to", "do", "platform", "conversion", "with", "special", "casing", "for", "IntervalArray", ".", "Wrapper", "around", "maybe_convert_platform", "that", "alters", "the", "default", "return", "dtype", "in", "certain", "cases", "to", "be", "compatible", "with", "IntervalArray", ".", "For", "example", "empty", "lists", "return", "with", "integer", "dtype", "instead", "of", "object", "dtype", "which", "is", "prohibited", "for", "IntervalArray", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/interval.py#L1078-L1102
19,498
pandas-dev/pandas
pandas/core/dtypes/inference.py
is_file_like
def is_file_like(obj): """ Check if the object is a file-like object. For objects to be considered file-like, they must be an iterator AND have either a `read` and/or `write` method as an attribute. Note: file-like objects must be iterable, but iterable objects need not be file-like. .. versionadded:: 0.20.0 Parameters ---------- obj : The object to check Returns ------- is_file_like : bool Whether `obj` has file-like properties. Examples -------- >>> buffer(StringIO("data")) >>> is_file_like(buffer) True >>> is_file_like([1, 2, 3]) False """ if not (hasattr(obj, 'read') or hasattr(obj, 'write')): return False if not hasattr(obj, "__iter__"): return False return True
python
def is_file_like(obj): """ Check if the object is a file-like object. For objects to be considered file-like, they must be an iterator AND have either a `read` and/or `write` method as an attribute. Note: file-like objects must be iterable, but iterable objects need not be file-like. .. versionadded:: 0.20.0 Parameters ---------- obj : The object to check Returns ------- is_file_like : bool Whether `obj` has file-like properties. Examples -------- >>> buffer(StringIO("data")) >>> is_file_like(buffer) True >>> is_file_like([1, 2, 3]) False """ if not (hasattr(obj, 'read') or hasattr(obj, 'write')): return False if not hasattr(obj, "__iter__"): return False return True
[ "def", "is_file_like", "(", "obj", ")", ":", "if", "not", "(", "hasattr", "(", "obj", ",", "'read'", ")", "or", "hasattr", "(", "obj", ",", "'write'", ")", ")", ":", "return", "False", "if", "not", "hasattr", "(", "obj", ",", "\"__iter__\"", ")", ":", "return", "False", "return", "True" ]
Check if the object is a file-like object. For objects to be considered file-like, they must be an iterator AND have either a `read` and/or `write` method as an attribute. Note: file-like objects must be iterable, but iterable objects need not be file-like. .. versionadded:: 0.20.0 Parameters ---------- obj : The object to check Returns ------- is_file_like : bool Whether `obj` has file-like properties. Examples -------- >>> buffer(StringIO("data")) >>> is_file_like(buffer) True >>> is_file_like([1, 2, 3]) False
[ "Check", "if", "the", "object", "is", "a", "file", "-", "like", "object", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/inference.py#L152-L189
19,499
pandas-dev/pandas
pandas/core/dtypes/inference.py
is_list_like
def is_list_like(obj, allow_sets=True): """ Check if the object is list-like. Objects that are considered list-like are for example Python lists, tuples, sets, NumPy arrays, and Pandas Series. Strings and datetime objects, however, are not considered list-like. Parameters ---------- obj : The object to check allow_sets : boolean, default True If this parameter is False, sets will not be considered list-like .. versionadded:: 0.24.0 Returns ------- is_list_like : bool Whether `obj` has list-like properties. Examples -------- >>> is_list_like([1, 2, 3]) True >>> is_list_like({1, 2, 3}) True >>> is_list_like(datetime(2017, 1, 1)) False >>> is_list_like("foo") False >>> is_list_like(1) False >>> is_list_like(np.array([2])) True >>> is_list_like(np.array(2))) False """ return (isinstance(obj, abc.Iterable) and # we do not count strings/unicode/bytes as list-like not isinstance(obj, (str, bytes)) and # exclude zero-dimensional numpy arrays, effectively scalars not (isinstance(obj, np.ndarray) and obj.ndim == 0) and # exclude sets if allow_sets is False not (allow_sets is False and isinstance(obj, abc.Set)))
python
def is_list_like(obj, allow_sets=True): """ Check if the object is list-like. Objects that are considered list-like are for example Python lists, tuples, sets, NumPy arrays, and Pandas Series. Strings and datetime objects, however, are not considered list-like. Parameters ---------- obj : The object to check allow_sets : boolean, default True If this parameter is False, sets will not be considered list-like .. versionadded:: 0.24.0 Returns ------- is_list_like : bool Whether `obj` has list-like properties. Examples -------- >>> is_list_like([1, 2, 3]) True >>> is_list_like({1, 2, 3}) True >>> is_list_like(datetime(2017, 1, 1)) False >>> is_list_like("foo") False >>> is_list_like(1) False >>> is_list_like(np.array([2])) True >>> is_list_like(np.array(2))) False """ return (isinstance(obj, abc.Iterable) and # we do not count strings/unicode/bytes as list-like not isinstance(obj, (str, bytes)) and # exclude zero-dimensional numpy arrays, effectively scalars not (isinstance(obj, np.ndarray) and obj.ndim == 0) and # exclude sets if allow_sets is False not (allow_sets is False and isinstance(obj, abc.Set)))
[ "def", "is_list_like", "(", "obj", ",", "allow_sets", "=", "True", ")", ":", "return", "(", "isinstance", "(", "obj", ",", "abc", ".", "Iterable", ")", "and", "# we do not count strings/unicode/bytes as list-like", "not", "isinstance", "(", "obj", ",", "(", "str", ",", "bytes", ")", ")", "and", "# exclude zero-dimensional numpy arrays, effectively scalars", "not", "(", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", "and", "obj", ".", "ndim", "==", "0", ")", "and", "# exclude sets if allow_sets is False", "not", "(", "allow_sets", "is", "False", "and", "isinstance", "(", "obj", ",", "abc", ".", "Set", ")", ")", ")" ]
Check if the object is list-like. Objects that are considered list-like are for example Python lists, tuples, sets, NumPy arrays, and Pandas Series. Strings and datetime objects, however, are not considered list-like. Parameters ---------- obj : The object to check allow_sets : boolean, default True If this parameter is False, sets will not be considered list-like .. versionadded:: 0.24.0 Returns ------- is_list_like : bool Whether `obj` has list-like properties. Examples -------- >>> is_list_like([1, 2, 3]) True >>> is_list_like({1, 2, 3}) True >>> is_list_like(datetime(2017, 1, 1)) False >>> is_list_like("foo") False >>> is_list_like(1) False >>> is_list_like(np.array([2])) True >>> is_list_like(np.array(2))) False
[ "Check", "if", "the", "object", "is", "list", "-", "like", "." ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/inference.py#L245-L293