partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
DataFrame.diff
First discrete difference of element. Calculates the difference of a DataFrame element compared with another element in the DataFrame (default is the element in the same column of the previous row). Parameters ---------- periods : int, default 1 Periods to shift for calculating difference, accepts negative values. axis : {0 or 'index', 1 or 'columns'}, default 0 Take difference over rows (0) or columns (1). .. versionadded:: 0.16.1. Returns ------- DataFrame See Also -------- Series.diff: First discrete difference for a Series. DataFrame.pct_change: Percent change over given number of periods. DataFrame.shift: Shift index by desired number of periods with an optional time freq. Examples -------- Difference with previous row >>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6], ... 'b': [1, 1, 2, 3, 5, 8], ... 'c': [1, 4, 9, 16, 25, 36]}) >>> df a b c 0 1 1 1 1 2 1 4 2 3 2 9 3 4 3 16 4 5 5 25 5 6 8 36 >>> df.diff() a b c 0 NaN NaN NaN 1 1.0 0.0 3.0 2 1.0 1.0 5.0 3 1.0 1.0 7.0 4 1.0 2.0 9.0 5 1.0 3.0 11.0 Difference with previous column >>> df.diff(axis=1) a b c 0 NaN 0.0 0.0 1 NaN -1.0 3.0 2 NaN -1.0 7.0 3 NaN -1.0 13.0 4 NaN 0.0 20.0 5 NaN 2.0 28.0 Difference with 3rd previous row >>> df.diff(periods=3) a b c 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 3.0 2.0 15.0 4 3.0 4.0 21.0 5 3.0 6.0 27.0 Difference with following row >>> df.diff(periods=-1) a b c 0 -1.0 0.0 -3.0 1 -1.0 -1.0 -5.0 2 -1.0 -1.0 -7.0 3 -1.0 -2.0 -9.0 4 -1.0 -3.0 -11.0 5 NaN NaN NaN
pandas/core/frame.py
def diff(self, periods=1, axis=0): """ First discrete difference of element. Calculates the difference of a DataFrame element compared with another element in the DataFrame (default is the element in the same column of the previous row). Parameters ---------- periods : int, default 1 Periods to shift for calculating difference, accepts negative values. axis : {0 or 'index', 1 or 'columns'}, default 0 Take difference over rows (0) or columns (1). .. versionadded:: 0.16.1. Returns ------- DataFrame See Also -------- Series.diff: First discrete difference for a Series. DataFrame.pct_change: Percent change over given number of periods. DataFrame.shift: Shift index by desired number of periods with an optional time freq. Examples -------- Difference with previous row >>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6], ... 'b': [1, 1, 2, 3, 5, 8], ... 'c': [1, 4, 9, 16, 25, 36]}) >>> df a b c 0 1 1 1 1 2 1 4 2 3 2 9 3 4 3 16 4 5 5 25 5 6 8 36 >>> df.diff() a b c 0 NaN NaN NaN 1 1.0 0.0 3.0 2 1.0 1.0 5.0 3 1.0 1.0 7.0 4 1.0 2.0 9.0 5 1.0 3.0 11.0 Difference with previous column >>> df.diff(axis=1) a b c 0 NaN 0.0 0.0 1 NaN -1.0 3.0 2 NaN -1.0 7.0 3 NaN -1.0 13.0 4 NaN 0.0 20.0 5 NaN 2.0 28.0 Difference with 3rd previous row >>> df.diff(periods=3) a b c 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 3.0 2.0 15.0 4 3.0 4.0 21.0 5 3.0 6.0 27.0 Difference with following row >>> df.diff(periods=-1) a b c 0 -1.0 0.0 -3.0 1 -1.0 -1.0 -5.0 2 -1.0 -1.0 -7.0 3 -1.0 -2.0 -9.0 4 -1.0 -3.0 -11.0 5 NaN NaN NaN """ bm_axis = self._get_block_manager_axis(axis) new_data = self._data.diff(n=periods, axis=bm_axis) return self._constructor(new_data)
def diff(self, periods=1, axis=0): """ First discrete difference of element. Calculates the difference of a DataFrame element compared with another element in the DataFrame (default is the element in the same column of the previous row). Parameters ---------- periods : int, default 1 Periods to shift for calculating difference, accepts negative values. axis : {0 or 'index', 1 or 'columns'}, default 0 Take difference over rows (0) or columns (1). .. versionadded:: 0.16.1. Returns ------- DataFrame See Also -------- Series.diff: First discrete difference for a Series. DataFrame.pct_change: Percent change over given number of periods. DataFrame.shift: Shift index by desired number of periods with an optional time freq. Examples -------- Difference with previous row >>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6], ... 'b': [1, 1, 2, 3, 5, 8], ... 'c': [1, 4, 9, 16, 25, 36]}) >>> df a b c 0 1 1 1 1 2 1 4 2 3 2 9 3 4 3 16 4 5 5 25 5 6 8 36 >>> df.diff() a b c 0 NaN NaN NaN 1 1.0 0.0 3.0 2 1.0 1.0 5.0 3 1.0 1.0 7.0 4 1.0 2.0 9.0 5 1.0 3.0 11.0 Difference with previous column >>> df.diff(axis=1) a b c 0 NaN 0.0 0.0 1 NaN -1.0 3.0 2 NaN -1.0 7.0 3 NaN -1.0 13.0 4 NaN 0.0 20.0 5 NaN 2.0 28.0 Difference with 3rd previous row >>> df.diff(periods=3) a b c 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 3.0 2.0 15.0 4 3.0 4.0 21.0 5 3.0 6.0 27.0 Difference with following row >>> df.diff(periods=-1) a b c 0 -1.0 0.0 -3.0 1 -1.0 -1.0 -5.0 2 -1.0 -1.0 -7.0 3 -1.0 -2.0 -9.0 4 -1.0 -3.0 -11.0 5 NaN NaN NaN """ bm_axis = self._get_block_manager_axis(axis) new_data = self._data.diff(n=periods, axis=bm_axis) return self._constructor(new_data)
[ "First", "discrete", "difference", "of", "element", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L6145-L6234
[ "def", "diff", "(", "self", ",", "periods", "=", "1", ",", "axis", "=", "0", ")", ":", "bm_axis", "=", "self", ".", "_get_block_manager_axis", "(", "axis", ")", "new_data", "=", "self", ".", "_data", ".", "diff", "(", "n", "=", "periods", ",", "axis", "=", "bm_axis", ")", "return", "self", ".", "_constructor", "(", "new_data", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame._gotitem
Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on
pandas/core/frame.py
def _gotitem(self, key: Union[str, List[str]], ndim: int, subset: Optional[Union[Series, ABCDataFrame]] = None, ) -> Union[Series, ABCDataFrame]: """ Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on """ if subset is None: subset = self elif subset.ndim == 1: # is Series return subset # TODO: _shallow_copy(subset)? return subset[key]
def _gotitem(self, key: Union[str, List[str]], ndim: int, subset: Optional[Union[Series, ABCDataFrame]] = None, ) -> Union[Series, ABCDataFrame]: """ Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on """ if subset is None: subset = self elif subset.ndim == 1: # is Series return subset # TODO: _shallow_copy(subset)? return subset[key]
[ "Sub", "-", "classes", "to", "define", ".", "Return", "a", "sliced", "object", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L6239-L6261
[ "def", "_gotitem", "(", "self", ",", "key", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "ndim", ":", "int", ",", "subset", ":", "Optional", "[", "Union", "[", "Series", ",", "ABCDataFrame", "]", "]", "=", "None", ",", ")", "->", "Union", "[", "Series", ",", "ABCDataFrame", "]", ":", "if", "subset", "is", "None", ":", "subset", "=", "self", "elif", "subset", ".", "ndim", "==", "1", ":", "# is Series", "return", "subset", "# TODO: _shallow_copy(subset)?", "return", "subset", "[", "key", "]" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.apply
Apply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame's index (``axis=0``) or the DataFrame's columns (``axis=1``). By default (``result_type=None``), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the `result_type` argument. Parameters ---------- func : function Function to apply to each column or row. axis : {0 or 'index', 1 or 'columns'}, default 0 Axis along which the function is applied: * 0 or 'index': apply function to each column. * 1 or 'columns': apply function to each row. broadcast : bool, optional Only relevant for aggregation functions: * ``False`` or ``None`` : returns a Series whose length is the length of the index or the number of columns (based on the `axis` parameter) * ``True`` : results will be broadcast to the original shape of the frame, the original index and columns will be retained. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='broadcast'. raw : bool, default False * ``False`` : passes each row or column as a Series to the function. * ``True`` : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance. reduce : bool or None, default None Try to apply reduction procedures. If the DataFrame is empty, `apply` will use `reduce` to determine whether the result should be a Series or a DataFrame. If ``reduce=None`` (the default), `apply`'s return value will be guessed by calling `func` on an empty Series (note: while guessing, exceptions raised by `func` will be ignored). If ``reduce=True`` a Series will always be returned, and if ``reduce=False`` a DataFrame will always be returned. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by ``result_type='reduce'``. result_type : {'expand', 'reduce', 'broadcast', None}, default None These only act when ``axis=1`` (columns): * 'expand' : list-like results will be turned into columns. * 'reduce' : returns a Series if possible rather than expanding list-like results. This is the opposite of 'expand'. * 'broadcast' : results will be broadcast to the original shape of the DataFrame, the original index and columns will be retained. The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns. .. versionadded:: 0.23.0 args : tuple Positional arguments to pass to `func` in addition to the array/series. **kwds Additional keyword arguments to pass as keywords arguments to `func`. Returns ------- Series or DataFrame Result of applying ``func`` along the given axis of the DataFrame. See Also -------- DataFrame.applymap: For elementwise operations. DataFrame.aggregate: Only perform aggregating type operations. DataFrame.transform: Only perform transforming type operations. Notes ----- In the current implementation apply calls `func` twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if `func` has side-effects, as they will take effect twice for the first column/row. Examples -------- >>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B']) >>> df A B 0 4 9 1 4 9 2 4 9 Using a numpy universal function (in this case the same as ``np.sqrt(df)``): >>> df.apply(np.sqrt) A B 0 2.0 3.0 1 2.0 3.0 2 2.0 3.0 Using a reducing function on either axis >>> df.apply(np.sum, axis=0) A 12 B 27 dtype: int64 >>> df.apply(np.sum, axis=1) 0 13 1 13 2 13 dtype: int64 Retuning a list-like will result in a Series >>> df.apply(lambda x: [1, 2], axis=1) 0 [1, 2] 1 [1, 2] 2 [1, 2] dtype: object Passing result_type='expand' will expand list-like results to columns of a Dataframe >>> df.apply(lambda x: [1, 2], axis=1, result_type='expand') 0 1 0 1 2 1 1 2 2 1 2 Returning a Series inside the function is similar to passing ``result_type='expand'``. The resulting column names will be the Series index. >>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1) foo bar 0 1 2 1 1 2 2 1 2 Passing ``result_type='broadcast'`` will ensure the same shape result, whether list-like or scalar is returned by the function, and broadcast it along the axis. The resulting column names will be the originals. >>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast') A B 0 1 2 1 1 2 2 1 2
pandas/core/frame.py
def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, args=(), **kwds): """ Apply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame's index (``axis=0``) or the DataFrame's columns (``axis=1``). By default (``result_type=None``), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the `result_type` argument. Parameters ---------- func : function Function to apply to each column or row. axis : {0 or 'index', 1 or 'columns'}, default 0 Axis along which the function is applied: * 0 or 'index': apply function to each column. * 1 or 'columns': apply function to each row. broadcast : bool, optional Only relevant for aggregation functions: * ``False`` or ``None`` : returns a Series whose length is the length of the index or the number of columns (based on the `axis` parameter) * ``True`` : results will be broadcast to the original shape of the frame, the original index and columns will be retained. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='broadcast'. raw : bool, default False * ``False`` : passes each row or column as a Series to the function. * ``True`` : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance. reduce : bool or None, default None Try to apply reduction procedures. If the DataFrame is empty, `apply` will use `reduce` to determine whether the result should be a Series or a DataFrame. If ``reduce=None`` (the default), `apply`'s return value will be guessed by calling `func` on an empty Series (note: while guessing, exceptions raised by `func` will be ignored). If ``reduce=True`` a Series will always be returned, and if ``reduce=False`` a DataFrame will always be returned. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by ``result_type='reduce'``. result_type : {'expand', 'reduce', 'broadcast', None}, default None These only act when ``axis=1`` (columns): * 'expand' : list-like results will be turned into columns. * 'reduce' : returns a Series if possible rather than expanding list-like results. This is the opposite of 'expand'. * 'broadcast' : results will be broadcast to the original shape of the DataFrame, the original index and columns will be retained. The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns. .. versionadded:: 0.23.0 args : tuple Positional arguments to pass to `func` in addition to the array/series. **kwds Additional keyword arguments to pass as keywords arguments to `func`. Returns ------- Series or DataFrame Result of applying ``func`` along the given axis of the DataFrame. See Also -------- DataFrame.applymap: For elementwise operations. DataFrame.aggregate: Only perform aggregating type operations. DataFrame.transform: Only perform transforming type operations. Notes ----- In the current implementation apply calls `func` twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if `func` has side-effects, as they will take effect twice for the first column/row. Examples -------- >>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B']) >>> df A B 0 4 9 1 4 9 2 4 9 Using a numpy universal function (in this case the same as ``np.sqrt(df)``): >>> df.apply(np.sqrt) A B 0 2.0 3.0 1 2.0 3.0 2 2.0 3.0 Using a reducing function on either axis >>> df.apply(np.sum, axis=0) A 12 B 27 dtype: int64 >>> df.apply(np.sum, axis=1) 0 13 1 13 2 13 dtype: int64 Retuning a list-like will result in a Series >>> df.apply(lambda x: [1, 2], axis=1) 0 [1, 2] 1 [1, 2] 2 [1, 2] dtype: object Passing result_type='expand' will expand list-like results to columns of a Dataframe >>> df.apply(lambda x: [1, 2], axis=1, result_type='expand') 0 1 0 1 2 1 1 2 2 1 2 Returning a Series inside the function is similar to passing ``result_type='expand'``. The resulting column names will be the Series index. >>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1) foo bar 0 1 2 1 1 2 2 1 2 Passing ``result_type='broadcast'`` will ensure the same shape result, whether list-like or scalar is returned by the function, and broadcast it along the axis. The resulting column names will be the originals. >>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast') A B 0 1 2 1 1 2 2 1 2 """ from pandas.core.apply import frame_apply op = frame_apply(self, func=func, axis=axis, broadcast=broadcast, raw=raw, reduce=reduce, result_type=result_type, args=args, kwds=kwds) return op.get_result()
def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, args=(), **kwds): """ Apply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame's index (``axis=0``) or the DataFrame's columns (``axis=1``). By default (``result_type=None``), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the `result_type` argument. Parameters ---------- func : function Function to apply to each column or row. axis : {0 or 'index', 1 or 'columns'}, default 0 Axis along which the function is applied: * 0 or 'index': apply function to each column. * 1 or 'columns': apply function to each row. broadcast : bool, optional Only relevant for aggregation functions: * ``False`` or ``None`` : returns a Series whose length is the length of the index or the number of columns (based on the `axis` parameter) * ``True`` : results will be broadcast to the original shape of the frame, the original index and columns will be retained. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='broadcast'. raw : bool, default False * ``False`` : passes each row or column as a Series to the function. * ``True`` : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance. reduce : bool or None, default None Try to apply reduction procedures. If the DataFrame is empty, `apply` will use `reduce` to determine whether the result should be a Series or a DataFrame. If ``reduce=None`` (the default), `apply`'s return value will be guessed by calling `func` on an empty Series (note: while guessing, exceptions raised by `func` will be ignored). If ``reduce=True`` a Series will always be returned, and if ``reduce=False`` a DataFrame will always be returned. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by ``result_type='reduce'``. result_type : {'expand', 'reduce', 'broadcast', None}, default None These only act when ``axis=1`` (columns): * 'expand' : list-like results will be turned into columns. * 'reduce' : returns a Series if possible rather than expanding list-like results. This is the opposite of 'expand'. * 'broadcast' : results will be broadcast to the original shape of the DataFrame, the original index and columns will be retained. The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns. .. versionadded:: 0.23.0 args : tuple Positional arguments to pass to `func` in addition to the array/series. **kwds Additional keyword arguments to pass as keywords arguments to `func`. Returns ------- Series or DataFrame Result of applying ``func`` along the given axis of the DataFrame. See Also -------- DataFrame.applymap: For elementwise operations. DataFrame.aggregate: Only perform aggregating type operations. DataFrame.transform: Only perform transforming type operations. Notes ----- In the current implementation apply calls `func` twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if `func` has side-effects, as they will take effect twice for the first column/row. Examples -------- >>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B']) >>> df A B 0 4 9 1 4 9 2 4 9 Using a numpy universal function (in this case the same as ``np.sqrt(df)``): >>> df.apply(np.sqrt) A B 0 2.0 3.0 1 2.0 3.0 2 2.0 3.0 Using a reducing function on either axis >>> df.apply(np.sum, axis=0) A 12 B 27 dtype: int64 >>> df.apply(np.sum, axis=1) 0 13 1 13 2 13 dtype: int64 Retuning a list-like will result in a Series >>> df.apply(lambda x: [1, 2], axis=1) 0 [1, 2] 1 [1, 2] 2 [1, 2] dtype: object Passing result_type='expand' will expand list-like results to columns of a Dataframe >>> df.apply(lambda x: [1, 2], axis=1, result_type='expand') 0 1 0 1 2 1 1 2 2 1 2 Returning a Series inside the function is similar to passing ``result_type='expand'``. The resulting column names will be the Series index. >>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1) foo bar 0 1 2 1 1 2 2 1 2 Passing ``result_type='broadcast'`` will ensure the same shape result, whether list-like or scalar is returned by the function, and broadcast it along the axis. The resulting column names will be the originals. >>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast') A B 0 1 2 1 1 2 2 1 2 """ from pandas.core.apply import frame_apply op = frame_apply(self, func=func, axis=axis, broadcast=broadcast, raw=raw, reduce=reduce, result_type=result_type, args=args, kwds=kwds) return op.get_result()
[ "Apply", "a", "function", "along", "an", "axis", "of", "the", "DataFrame", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L6355-L6534
[ "def", "apply", "(", "self", ",", "func", ",", "axis", "=", "0", ",", "broadcast", "=", "None", ",", "raw", "=", "False", ",", "reduce", "=", "None", ",", "result_type", "=", "None", ",", "args", "=", "(", ")", ",", "*", "*", "kwds", ")", ":", "from", "pandas", ".", "core", ".", "apply", "import", "frame_apply", "op", "=", "frame_apply", "(", "self", ",", "func", "=", "func", ",", "axis", "=", "axis", ",", "broadcast", "=", "broadcast", ",", "raw", "=", "raw", ",", "reduce", "=", "reduce", ",", "result_type", "=", "result_type", ",", "args", "=", "args", ",", "kwds", "=", "kwds", ")", "return", "op", ".", "get_result", "(", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.applymap
Apply a function to a Dataframe elementwise. This method applies a function that accepts and returns a scalar to every element of a DataFrame. Parameters ---------- func : callable Python function, returns a single value from a single value. Returns ------- DataFrame Transformed DataFrame. See Also -------- DataFrame.apply : Apply a function along input axis of DataFrame. Notes ----- In the current implementation applymap calls `func` twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if `func` has side-effects, as they will take effect twice for the first column/row. Examples -------- >>> df = pd.DataFrame([[1, 2.12], [3.356, 4.567]]) >>> df 0 1 0 1.000 2.120 1 3.356 4.567 >>> df.applymap(lambda x: len(str(x))) 0 1 0 3 4 1 5 5 Note that a vectorized version of `func` often exists, which will be much faster. You could square each number elementwise. >>> df.applymap(lambda x: x**2) 0 1 0 1.000000 4.494400 1 11.262736 20.857489 But it's better to avoid applymap in that case. >>> df ** 2 0 1 0 1.000000 4.494400 1 11.262736 20.857489
pandas/core/frame.py
def applymap(self, func): """ Apply a function to a Dataframe elementwise. This method applies a function that accepts and returns a scalar to every element of a DataFrame. Parameters ---------- func : callable Python function, returns a single value from a single value. Returns ------- DataFrame Transformed DataFrame. See Also -------- DataFrame.apply : Apply a function along input axis of DataFrame. Notes ----- In the current implementation applymap calls `func` twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if `func` has side-effects, as they will take effect twice for the first column/row. Examples -------- >>> df = pd.DataFrame([[1, 2.12], [3.356, 4.567]]) >>> df 0 1 0 1.000 2.120 1 3.356 4.567 >>> df.applymap(lambda x: len(str(x))) 0 1 0 3 4 1 5 5 Note that a vectorized version of `func` often exists, which will be much faster. You could square each number elementwise. >>> df.applymap(lambda x: x**2) 0 1 0 1.000000 4.494400 1 11.262736 20.857489 But it's better to avoid applymap in that case. >>> df ** 2 0 1 0 1.000000 4.494400 1 11.262736 20.857489 """ # if we have a dtype == 'M8[ns]', provide boxed values def infer(x): if x.empty: return lib.map_infer(x, func) return lib.map_infer(x.astype(object).values, func) return self.apply(infer)
def applymap(self, func): """ Apply a function to a Dataframe elementwise. This method applies a function that accepts and returns a scalar to every element of a DataFrame. Parameters ---------- func : callable Python function, returns a single value from a single value. Returns ------- DataFrame Transformed DataFrame. See Also -------- DataFrame.apply : Apply a function along input axis of DataFrame. Notes ----- In the current implementation applymap calls `func` twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if `func` has side-effects, as they will take effect twice for the first column/row. Examples -------- >>> df = pd.DataFrame([[1, 2.12], [3.356, 4.567]]) >>> df 0 1 0 1.000 2.120 1 3.356 4.567 >>> df.applymap(lambda x: len(str(x))) 0 1 0 3 4 1 5 5 Note that a vectorized version of `func` often exists, which will be much faster. You could square each number elementwise. >>> df.applymap(lambda x: x**2) 0 1 0 1.000000 4.494400 1 11.262736 20.857489 But it's better to avoid applymap in that case. >>> df ** 2 0 1 0 1.000000 4.494400 1 11.262736 20.857489 """ # if we have a dtype == 'M8[ns]', provide boxed values def infer(x): if x.empty: return lib.map_infer(x, func) return lib.map_infer(x.astype(object).values, func) return self.apply(infer)
[ "Apply", "a", "function", "to", "a", "Dataframe", "elementwise", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L6536-L6600
[ "def", "applymap", "(", "self", ",", "func", ")", ":", "# if we have a dtype == 'M8[ns]', provide boxed values", "def", "infer", "(", "x", ")", ":", "if", "x", ".", "empty", ":", "return", "lib", ".", "map_infer", "(", "x", ",", "func", ")", "return", "lib", ".", "map_infer", "(", "x", ".", "astype", "(", "object", ")", ".", "values", ",", "func", ")", "return", "self", ".", "apply", "(", "infer", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.append
Append rows of `other` to the end of caller, returning a new object. Columns in `other` that are not in the caller are added as new columns. Parameters ---------- other : DataFrame or Series/dict-like object, or list of these The data to append. ignore_index : boolean, default False If True, do not use the index labels. verify_integrity : boolean, default False If True, raise ValueError on creating index with duplicates. sort : boolean, default None Sort columns if the columns of `self` and `other` are not aligned. The default sorting is deprecated and will change to not-sorting in a future version of pandas. Explicitly pass ``sort=True`` to silence the warning and sort. Explicitly pass ``sort=False`` to silence the warning and not sort. .. versionadded:: 0.23.0 Returns ------- DataFrame See Also -------- concat : General function to concatenate DataFrame, Series or Panel objects. Notes ----- If a list of dict/series is passed and the keys are all contained in the DataFrame's index, the order of the columns in the resulting DataFrame will be unchanged. Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once. Examples -------- >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB')) >>> df A B 0 1 2 1 3 4 >>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB')) >>> df.append(df2) A B 0 1 2 1 3 4 0 5 6 1 7 8 With `ignore_index` set to True: >>> df.append(df2, ignore_index=True) A B 0 1 2 1 3 4 2 5 6 3 7 8 The following, while not recommended methods for generating DataFrames, show two ways to generate a DataFrame from multiple data sources. Less efficient: >>> df = pd.DataFrame(columns=['A']) >>> for i in range(5): ... df = df.append({'A': i}, ignore_index=True) >>> df A 0 0 1 1 2 2 3 3 4 4 More efficient: >>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)], ... ignore_index=True) A 0 0 1 1 2 2 3 3 4 4
pandas/core/frame.py
def append(self, other, ignore_index=False, verify_integrity=False, sort=None): """ Append rows of `other` to the end of caller, returning a new object. Columns in `other` that are not in the caller are added as new columns. Parameters ---------- other : DataFrame or Series/dict-like object, or list of these The data to append. ignore_index : boolean, default False If True, do not use the index labels. verify_integrity : boolean, default False If True, raise ValueError on creating index with duplicates. sort : boolean, default None Sort columns if the columns of `self` and `other` are not aligned. The default sorting is deprecated and will change to not-sorting in a future version of pandas. Explicitly pass ``sort=True`` to silence the warning and sort. Explicitly pass ``sort=False`` to silence the warning and not sort. .. versionadded:: 0.23.0 Returns ------- DataFrame See Also -------- concat : General function to concatenate DataFrame, Series or Panel objects. Notes ----- If a list of dict/series is passed and the keys are all contained in the DataFrame's index, the order of the columns in the resulting DataFrame will be unchanged. Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once. Examples -------- >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB')) >>> df A B 0 1 2 1 3 4 >>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB')) >>> df.append(df2) A B 0 1 2 1 3 4 0 5 6 1 7 8 With `ignore_index` set to True: >>> df.append(df2, ignore_index=True) A B 0 1 2 1 3 4 2 5 6 3 7 8 The following, while not recommended methods for generating DataFrames, show two ways to generate a DataFrame from multiple data sources. Less efficient: >>> df = pd.DataFrame(columns=['A']) >>> for i in range(5): ... df = df.append({'A': i}, ignore_index=True) >>> df A 0 0 1 1 2 2 3 3 4 4 More efficient: >>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)], ... ignore_index=True) A 0 0 1 1 2 2 3 3 4 4 """ if isinstance(other, (Series, dict)): if isinstance(other, dict): other = Series(other) if other.name is None and not ignore_index: raise TypeError('Can only append a Series if ignore_index=True' ' or if the Series has a name') if other.name is None: index = None else: # other must have the same index name as self, otherwise # index name will be reset index = Index([other.name], name=self.index.name) idx_diff = other.index.difference(self.columns) try: combined_columns = self.columns.append(idx_diff) except TypeError: combined_columns = self.columns.astype(object).append(idx_diff) other = other.reindex(combined_columns, copy=False) other = DataFrame(other.values.reshape((1, len(other))), index=index, columns=combined_columns) other = other._convert(datetime=True, timedelta=True) if not self.columns.equals(combined_columns): self = self.reindex(columns=combined_columns) elif isinstance(other, list) and not isinstance(other[0], DataFrame): other = DataFrame(other) if (self.columns.get_indexer(other.columns) >= 0).all(): other = other.reindex(columns=self.columns) from pandas.core.reshape.concat import concat if isinstance(other, (list, tuple)): to_concat = [self] + other else: to_concat = [self, other] return concat(to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity, sort=sort)
def append(self, other, ignore_index=False, verify_integrity=False, sort=None): """ Append rows of `other` to the end of caller, returning a new object. Columns in `other` that are not in the caller are added as new columns. Parameters ---------- other : DataFrame or Series/dict-like object, or list of these The data to append. ignore_index : boolean, default False If True, do not use the index labels. verify_integrity : boolean, default False If True, raise ValueError on creating index with duplicates. sort : boolean, default None Sort columns if the columns of `self` and `other` are not aligned. The default sorting is deprecated and will change to not-sorting in a future version of pandas. Explicitly pass ``sort=True`` to silence the warning and sort. Explicitly pass ``sort=False`` to silence the warning and not sort. .. versionadded:: 0.23.0 Returns ------- DataFrame See Also -------- concat : General function to concatenate DataFrame, Series or Panel objects. Notes ----- If a list of dict/series is passed and the keys are all contained in the DataFrame's index, the order of the columns in the resulting DataFrame will be unchanged. Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once. Examples -------- >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB')) >>> df A B 0 1 2 1 3 4 >>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB')) >>> df.append(df2) A B 0 1 2 1 3 4 0 5 6 1 7 8 With `ignore_index` set to True: >>> df.append(df2, ignore_index=True) A B 0 1 2 1 3 4 2 5 6 3 7 8 The following, while not recommended methods for generating DataFrames, show two ways to generate a DataFrame from multiple data sources. Less efficient: >>> df = pd.DataFrame(columns=['A']) >>> for i in range(5): ... df = df.append({'A': i}, ignore_index=True) >>> df A 0 0 1 1 2 2 3 3 4 4 More efficient: >>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)], ... ignore_index=True) A 0 0 1 1 2 2 3 3 4 4 """ if isinstance(other, (Series, dict)): if isinstance(other, dict): other = Series(other) if other.name is None and not ignore_index: raise TypeError('Can only append a Series if ignore_index=True' ' or if the Series has a name') if other.name is None: index = None else: # other must have the same index name as self, otherwise # index name will be reset index = Index([other.name], name=self.index.name) idx_diff = other.index.difference(self.columns) try: combined_columns = self.columns.append(idx_diff) except TypeError: combined_columns = self.columns.astype(object).append(idx_diff) other = other.reindex(combined_columns, copy=False) other = DataFrame(other.values.reshape((1, len(other))), index=index, columns=combined_columns) other = other._convert(datetime=True, timedelta=True) if not self.columns.equals(combined_columns): self = self.reindex(columns=combined_columns) elif isinstance(other, list) and not isinstance(other[0], DataFrame): other = DataFrame(other) if (self.columns.get_indexer(other.columns) >= 0).all(): other = other.reindex(columns=self.columns) from pandas.core.reshape.concat import concat if isinstance(other, (list, tuple)): to_concat = [self] + other else: to_concat = [self, other] return concat(to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity, sort=sort)
[ "Append", "rows", "of", "other", "to", "the", "end", "of", "caller", "returning", "a", "new", "object", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L6605-L6739
[ "def", "append", "(", "self", ",", "other", ",", "ignore_index", "=", "False", ",", "verify_integrity", "=", "False", ",", "sort", "=", "None", ")", ":", "if", "isinstance", "(", "other", ",", "(", "Series", ",", "dict", ")", ")", ":", "if", "isinstance", "(", "other", ",", "dict", ")", ":", "other", "=", "Series", "(", "other", ")", "if", "other", ".", "name", "is", "None", "and", "not", "ignore_index", ":", "raise", "TypeError", "(", "'Can only append a Series if ignore_index=True'", "' or if the Series has a name'", ")", "if", "other", ".", "name", "is", "None", ":", "index", "=", "None", "else", ":", "# other must have the same index name as self, otherwise", "# index name will be reset", "index", "=", "Index", "(", "[", "other", ".", "name", "]", ",", "name", "=", "self", ".", "index", ".", "name", ")", "idx_diff", "=", "other", ".", "index", ".", "difference", "(", "self", ".", "columns", ")", "try", ":", "combined_columns", "=", "self", ".", "columns", ".", "append", "(", "idx_diff", ")", "except", "TypeError", ":", "combined_columns", "=", "self", ".", "columns", ".", "astype", "(", "object", ")", ".", "append", "(", "idx_diff", ")", "other", "=", "other", ".", "reindex", "(", "combined_columns", ",", "copy", "=", "False", ")", "other", "=", "DataFrame", "(", "other", ".", "values", ".", "reshape", "(", "(", "1", ",", "len", "(", "other", ")", ")", ")", ",", "index", "=", "index", ",", "columns", "=", "combined_columns", ")", "other", "=", "other", ".", "_convert", "(", "datetime", "=", "True", ",", "timedelta", "=", "True", ")", "if", "not", "self", ".", "columns", ".", "equals", "(", "combined_columns", ")", ":", "self", "=", "self", ".", "reindex", "(", "columns", "=", "combined_columns", ")", "elif", "isinstance", "(", "other", ",", "list", ")", "and", "not", "isinstance", "(", "other", "[", "0", "]", ",", "DataFrame", ")", ":", "other", "=", "DataFrame", "(", "other", ")", "if", "(", "self", ".", "columns", ".", "get_indexer", "(", "other", ".", "columns", ")", ">=", "0", ")", ".", "all", "(", ")", ":", "other", "=", "other", ".", "reindex", "(", "columns", "=", "self", ".", "columns", ")", "from", "pandas", ".", "core", ".", "reshape", ".", "concat", "import", "concat", "if", "isinstance", "(", "other", ",", "(", "list", ",", "tuple", ")", ")", ":", "to_concat", "=", "[", "self", "]", "+", "other", "else", ":", "to_concat", "=", "[", "self", ",", "other", "]", "return", "concat", "(", "to_concat", ",", "ignore_index", "=", "ignore_index", ",", "verify_integrity", "=", "verify_integrity", ",", "sort", "=", "sort", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.join
Join columns of another DataFrame. Join columns with `other` DataFrame either on index or on a key column. Efficiently join multiple DataFrame objects by index at once by passing a list. Parameters ---------- other : DataFrame, Series, or list of DataFrame Index should be similar to one of the columns in this one. If a Series is passed, its name attribute must be set, and that will be used as the column name in the resulting joined DataFrame. on : str, list of str, or array-like, optional Column or index level name(s) in the caller to join on the index in `other`, otherwise joins index-on-index. If multiple values given, the `other` DataFrame must have a MultiIndex. Can pass an array as the join key if it is not already contained in the calling DataFrame. Like an Excel VLOOKUP operation. how : {'left', 'right', 'outer', 'inner'}, default 'left' How to handle the operation of the two objects. * left: use calling frame's index (or column if on is specified) * right: use `other`'s index. * outer: form union of calling frame's index (or column if on is specified) with `other`'s index, and sort it. lexicographically. * inner: form intersection of calling frame's index (or column if on is specified) with `other`'s index, preserving the order of the calling's one. lsuffix : str, default '' Suffix to use from left frame's overlapping columns. rsuffix : str, default '' Suffix to use from right frame's overlapping columns. sort : bool, default False Order result DataFrame lexicographically by the join key. If False, the order of the join key depends on the join type (how keyword). Returns ------- DataFrame A dataframe containing columns from both the caller and `other`. See Also -------- DataFrame.merge : For column(s)-on-columns(s) operations. Notes ----- Parameters `on`, `lsuffix`, and `rsuffix` are not supported when passing a list of `DataFrame` objects. Support for specifying index levels as the `on` parameter was added in version 0.23.0. Examples -------- >>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'], ... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']}) >>> df key A 0 K0 A0 1 K1 A1 2 K2 A2 3 K3 A3 4 K4 A4 5 K5 A5 >>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'], ... 'B': ['B0', 'B1', 'B2']}) >>> other key B 0 K0 B0 1 K1 B1 2 K2 B2 Join DataFrames using their indexes. >>> df.join(other, lsuffix='_caller', rsuffix='_other') key_caller A key_other B 0 K0 A0 K0 B0 1 K1 A1 K1 B1 2 K2 A2 K2 B2 3 K3 A3 NaN NaN 4 K4 A4 NaN NaN 5 K5 A5 NaN NaN If we want to join using the key columns, we need to set key to be the index in both `df` and `other`. The joined DataFrame will have key as its index. >>> df.set_index('key').join(other.set_index('key')) A B key K0 A0 B0 K1 A1 B1 K2 A2 B2 K3 A3 NaN K4 A4 NaN K5 A5 NaN Another option to join using the key columns is to use the `on` parameter. DataFrame.join always uses `other`'s index but we can use any column in `df`. This method preserves the original DataFrame's index in the result. >>> df.join(other.set_index('key'), on='key') key A B 0 K0 A0 B0 1 K1 A1 B1 2 K2 A2 B2 3 K3 A3 NaN 4 K4 A4 NaN 5 K5 A5 NaN
pandas/core/frame.py
def join(self, other, on=None, how='left', lsuffix='', rsuffix='', sort=False): """ Join columns of another DataFrame. Join columns with `other` DataFrame either on index or on a key column. Efficiently join multiple DataFrame objects by index at once by passing a list. Parameters ---------- other : DataFrame, Series, or list of DataFrame Index should be similar to one of the columns in this one. If a Series is passed, its name attribute must be set, and that will be used as the column name in the resulting joined DataFrame. on : str, list of str, or array-like, optional Column or index level name(s) in the caller to join on the index in `other`, otherwise joins index-on-index. If multiple values given, the `other` DataFrame must have a MultiIndex. Can pass an array as the join key if it is not already contained in the calling DataFrame. Like an Excel VLOOKUP operation. how : {'left', 'right', 'outer', 'inner'}, default 'left' How to handle the operation of the two objects. * left: use calling frame's index (or column if on is specified) * right: use `other`'s index. * outer: form union of calling frame's index (or column if on is specified) with `other`'s index, and sort it. lexicographically. * inner: form intersection of calling frame's index (or column if on is specified) with `other`'s index, preserving the order of the calling's one. lsuffix : str, default '' Suffix to use from left frame's overlapping columns. rsuffix : str, default '' Suffix to use from right frame's overlapping columns. sort : bool, default False Order result DataFrame lexicographically by the join key. If False, the order of the join key depends on the join type (how keyword). Returns ------- DataFrame A dataframe containing columns from both the caller and `other`. See Also -------- DataFrame.merge : For column(s)-on-columns(s) operations. Notes ----- Parameters `on`, `lsuffix`, and `rsuffix` are not supported when passing a list of `DataFrame` objects. Support for specifying index levels as the `on` parameter was added in version 0.23.0. Examples -------- >>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'], ... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']}) >>> df key A 0 K0 A0 1 K1 A1 2 K2 A2 3 K3 A3 4 K4 A4 5 K5 A5 >>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'], ... 'B': ['B0', 'B1', 'B2']}) >>> other key B 0 K0 B0 1 K1 B1 2 K2 B2 Join DataFrames using their indexes. >>> df.join(other, lsuffix='_caller', rsuffix='_other') key_caller A key_other B 0 K0 A0 K0 B0 1 K1 A1 K1 B1 2 K2 A2 K2 B2 3 K3 A3 NaN NaN 4 K4 A4 NaN NaN 5 K5 A5 NaN NaN If we want to join using the key columns, we need to set key to be the index in both `df` and `other`. The joined DataFrame will have key as its index. >>> df.set_index('key').join(other.set_index('key')) A B key K0 A0 B0 K1 A1 B1 K2 A2 B2 K3 A3 NaN K4 A4 NaN K5 A5 NaN Another option to join using the key columns is to use the `on` parameter. DataFrame.join always uses `other`'s index but we can use any column in `df`. This method preserves the original DataFrame's index in the result. >>> df.join(other.set_index('key'), on='key') key A B 0 K0 A0 B0 1 K1 A1 B1 2 K2 A2 B2 3 K3 A3 NaN 4 K4 A4 NaN 5 K5 A5 NaN """ # For SparseDataFrame's benefit return self._join_compat(other, on=on, how=how, lsuffix=lsuffix, rsuffix=rsuffix, sort=sort)
def join(self, other, on=None, how='left', lsuffix='', rsuffix='', sort=False): """ Join columns of another DataFrame. Join columns with `other` DataFrame either on index or on a key column. Efficiently join multiple DataFrame objects by index at once by passing a list. Parameters ---------- other : DataFrame, Series, or list of DataFrame Index should be similar to one of the columns in this one. If a Series is passed, its name attribute must be set, and that will be used as the column name in the resulting joined DataFrame. on : str, list of str, or array-like, optional Column or index level name(s) in the caller to join on the index in `other`, otherwise joins index-on-index. If multiple values given, the `other` DataFrame must have a MultiIndex. Can pass an array as the join key if it is not already contained in the calling DataFrame. Like an Excel VLOOKUP operation. how : {'left', 'right', 'outer', 'inner'}, default 'left' How to handle the operation of the two objects. * left: use calling frame's index (or column if on is specified) * right: use `other`'s index. * outer: form union of calling frame's index (or column if on is specified) with `other`'s index, and sort it. lexicographically. * inner: form intersection of calling frame's index (or column if on is specified) with `other`'s index, preserving the order of the calling's one. lsuffix : str, default '' Suffix to use from left frame's overlapping columns. rsuffix : str, default '' Suffix to use from right frame's overlapping columns. sort : bool, default False Order result DataFrame lexicographically by the join key. If False, the order of the join key depends on the join type (how keyword). Returns ------- DataFrame A dataframe containing columns from both the caller and `other`. See Also -------- DataFrame.merge : For column(s)-on-columns(s) operations. Notes ----- Parameters `on`, `lsuffix`, and `rsuffix` are not supported when passing a list of `DataFrame` objects. Support for specifying index levels as the `on` parameter was added in version 0.23.0. Examples -------- >>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'], ... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']}) >>> df key A 0 K0 A0 1 K1 A1 2 K2 A2 3 K3 A3 4 K4 A4 5 K5 A5 >>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'], ... 'B': ['B0', 'B1', 'B2']}) >>> other key B 0 K0 B0 1 K1 B1 2 K2 B2 Join DataFrames using their indexes. >>> df.join(other, lsuffix='_caller', rsuffix='_other') key_caller A key_other B 0 K0 A0 K0 B0 1 K1 A1 K1 B1 2 K2 A2 K2 B2 3 K3 A3 NaN NaN 4 K4 A4 NaN NaN 5 K5 A5 NaN NaN If we want to join using the key columns, we need to set key to be the index in both `df` and `other`. The joined DataFrame will have key as its index. >>> df.set_index('key').join(other.set_index('key')) A B key K0 A0 B0 K1 A1 B1 K2 A2 B2 K3 A3 NaN K4 A4 NaN K5 A5 NaN Another option to join using the key columns is to use the `on` parameter. DataFrame.join always uses `other`'s index but we can use any column in `df`. This method preserves the original DataFrame's index in the result. >>> df.join(other.set_index('key'), on='key') key A B 0 K0 A0 B0 1 K1 A1 B1 2 K2 A2 B2 3 K3 A3 NaN 4 K4 A4 NaN 5 K5 A5 NaN """ # For SparseDataFrame's benefit return self._join_compat(other, on=on, how=how, lsuffix=lsuffix, rsuffix=rsuffix, sort=sort)
[ "Join", "columns", "of", "another", "DataFrame", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L6741-L6862
[ "def", "join", "(", "self", ",", "other", ",", "on", "=", "None", ",", "how", "=", "'left'", ",", "lsuffix", "=", "''", ",", "rsuffix", "=", "''", ",", "sort", "=", "False", ")", ":", "# For SparseDataFrame's benefit", "return", "self", ".", "_join_compat", "(", "other", ",", "on", "=", "on", ",", "how", "=", "how", ",", "lsuffix", "=", "lsuffix", ",", "rsuffix", "=", "rsuffix", ",", "sort", "=", "sort", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.round
Round a DataFrame to a variable number of decimal places. Parameters ---------- decimals : int, dict, Series Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if `decimals` is a dict-like, or in the index if `decimals` is a Series. Any columns not included in `decimals` will be left as is. Elements of `decimals` which are not columns of the input will be ignored. *args Additional keywords have no effect but might be accepted for compatibility with numpy. **kwargs Additional keywords have no effect but might be accepted for compatibility with numpy. Returns ------- DataFrame A DataFrame with the affected columns rounded to the specified number of decimal places. See Also -------- numpy.around : Round a numpy array to the given number of decimals. Series.round : Round a Series to the given number of decimals. Examples -------- >>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .18)], ... columns=['dogs', 'cats']) >>> df dogs cats 0 0.21 0.32 1 0.01 0.67 2 0.66 0.03 3 0.21 0.18 By providing an integer each column is rounded to the same number of decimal places >>> df.round(1) dogs cats 0 0.2 0.3 1 0.0 0.7 2 0.7 0.0 3 0.2 0.2 With a dict, the number of places for specific columns can be specfified with the column names as key and the number of decimal places as value >>> df.round({'dogs': 1, 'cats': 0}) dogs cats 0 0.2 0.0 1 0.0 1.0 2 0.7 0.0 3 0.2 0.0 Using a Series, the number of places for specific columns can be specfified with the column names as index and the number of decimal places as value >>> decimals = pd.Series([0, 1], index=['cats', 'dogs']) >>> df.round(decimals) dogs cats 0 0.2 0.0 1 0.0 1.0 2 0.7 0.0 3 0.2 0.0
pandas/core/frame.py
def round(self, decimals=0, *args, **kwargs): """ Round a DataFrame to a variable number of decimal places. Parameters ---------- decimals : int, dict, Series Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if `decimals` is a dict-like, or in the index if `decimals` is a Series. Any columns not included in `decimals` will be left as is. Elements of `decimals` which are not columns of the input will be ignored. *args Additional keywords have no effect but might be accepted for compatibility with numpy. **kwargs Additional keywords have no effect but might be accepted for compatibility with numpy. Returns ------- DataFrame A DataFrame with the affected columns rounded to the specified number of decimal places. See Also -------- numpy.around : Round a numpy array to the given number of decimals. Series.round : Round a Series to the given number of decimals. Examples -------- >>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .18)], ... columns=['dogs', 'cats']) >>> df dogs cats 0 0.21 0.32 1 0.01 0.67 2 0.66 0.03 3 0.21 0.18 By providing an integer each column is rounded to the same number of decimal places >>> df.round(1) dogs cats 0 0.2 0.3 1 0.0 0.7 2 0.7 0.0 3 0.2 0.2 With a dict, the number of places for specific columns can be specfified with the column names as key and the number of decimal places as value >>> df.round({'dogs': 1, 'cats': 0}) dogs cats 0 0.2 0.0 1 0.0 1.0 2 0.7 0.0 3 0.2 0.0 Using a Series, the number of places for specific columns can be specfified with the column names as index and the number of decimal places as value >>> decimals = pd.Series([0, 1], index=['cats', 'dogs']) >>> df.round(decimals) dogs cats 0 0.2 0.0 1 0.0 1.0 2 0.7 0.0 3 0.2 0.0 """ from pandas.core.reshape.concat import concat def _dict_round(df, decimals): for col, vals in df.iteritems(): try: yield _series_round(vals, decimals[col]) except KeyError: yield vals def _series_round(s, decimals): if is_integer_dtype(s) or is_float_dtype(s): return s.round(decimals) return s nv.validate_round(args, kwargs) if isinstance(decimals, (dict, Series)): if isinstance(decimals, Series): if not decimals.index.is_unique: raise ValueError("Index of decimals must be unique") new_cols = [col for col in _dict_round(self, decimals)] elif is_integer(decimals): # Dispatch to Series.round new_cols = [_series_round(v, decimals) for _, v in self.iteritems()] else: raise TypeError("decimals must be an integer, a dict-like or a " "Series") if len(new_cols) > 0: return self._constructor(concat(new_cols, axis=1), index=self.index, columns=self.columns) else: return self
def round(self, decimals=0, *args, **kwargs): """ Round a DataFrame to a variable number of decimal places. Parameters ---------- decimals : int, dict, Series Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if `decimals` is a dict-like, or in the index if `decimals` is a Series. Any columns not included in `decimals` will be left as is. Elements of `decimals` which are not columns of the input will be ignored. *args Additional keywords have no effect but might be accepted for compatibility with numpy. **kwargs Additional keywords have no effect but might be accepted for compatibility with numpy. Returns ------- DataFrame A DataFrame with the affected columns rounded to the specified number of decimal places. See Also -------- numpy.around : Round a numpy array to the given number of decimals. Series.round : Round a Series to the given number of decimals. Examples -------- >>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .18)], ... columns=['dogs', 'cats']) >>> df dogs cats 0 0.21 0.32 1 0.01 0.67 2 0.66 0.03 3 0.21 0.18 By providing an integer each column is rounded to the same number of decimal places >>> df.round(1) dogs cats 0 0.2 0.3 1 0.0 0.7 2 0.7 0.0 3 0.2 0.2 With a dict, the number of places for specific columns can be specfified with the column names as key and the number of decimal places as value >>> df.round({'dogs': 1, 'cats': 0}) dogs cats 0 0.2 0.0 1 0.0 1.0 2 0.7 0.0 3 0.2 0.0 Using a Series, the number of places for specific columns can be specfified with the column names as index and the number of decimal places as value >>> decimals = pd.Series([0, 1], index=['cats', 'dogs']) >>> df.round(decimals) dogs cats 0 0.2 0.0 1 0.0 1.0 2 0.7 0.0 3 0.2 0.0 """ from pandas.core.reshape.concat import concat def _dict_round(df, decimals): for col, vals in df.iteritems(): try: yield _series_round(vals, decimals[col]) except KeyError: yield vals def _series_round(s, decimals): if is_integer_dtype(s) or is_float_dtype(s): return s.round(decimals) return s nv.validate_round(args, kwargs) if isinstance(decimals, (dict, Series)): if isinstance(decimals, Series): if not decimals.index.is_unique: raise ValueError("Index of decimals must be unique") new_cols = [col for col in _dict_round(self, decimals)] elif is_integer(decimals): # Dispatch to Series.round new_cols = [_series_round(v, decimals) for _, v in self.iteritems()] else: raise TypeError("decimals must be an integer, a dict-like or a " "Series") if len(new_cols) > 0: return self._constructor(concat(new_cols, axis=1), index=self.index, columns=self.columns) else: return self
[ "Round", "a", "DataFrame", "to", "a", "variable", "number", "of", "decimal", "places", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L6917-L7028
[ "def", "round", "(", "self", ",", "decimals", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "core", ".", "reshape", ".", "concat", "import", "concat", "def", "_dict_round", "(", "df", ",", "decimals", ")", ":", "for", "col", ",", "vals", "in", "df", ".", "iteritems", "(", ")", ":", "try", ":", "yield", "_series_round", "(", "vals", ",", "decimals", "[", "col", "]", ")", "except", "KeyError", ":", "yield", "vals", "def", "_series_round", "(", "s", ",", "decimals", ")", ":", "if", "is_integer_dtype", "(", "s", ")", "or", "is_float_dtype", "(", "s", ")", ":", "return", "s", ".", "round", "(", "decimals", ")", "return", "s", "nv", ".", "validate_round", "(", "args", ",", "kwargs", ")", "if", "isinstance", "(", "decimals", ",", "(", "dict", ",", "Series", ")", ")", ":", "if", "isinstance", "(", "decimals", ",", "Series", ")", ":", "if", "not", "decimals", ".", "index", ".", "is_unique", ":", "raise", "ValueError", "(", "\"Index of decimals must be unique\"", ")", "new_cols", "=", "[", "col", "for", "col", "in", "_dict_round", "(", "self", ",", "decimals", ")", "]", "elif", "is_integer", "(", "decimals", ")", ":", "# Dispatch to Series.round", "new_cols", "=", "[", "_series_round", "(", "v", ",", "decimals", ")", "for", "_", ",", "v", "in", "self", ".", "iteritems", "(", ")", "]", "else", ":", "raise", "TypeError", "(", "\"decimals must be an integer, a dict-like or a \"", "\"Series\"", ")", "if", "len", "(", "new_cols", ")", ">", "0", ":", "return", "self", ".", "_constructor", "(", "concat", "(", "new_cols", ",", "axis", "=", "1", ")", ",", "index", "=", "self", ".", "index", ",", "columns", "=", "self", ".", "columns", ")", "else", ":", "return", "self" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.corr
Compute pairwise correlation of columns, excluding NA/null values. Parameters ---------- method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman rank correlation * callable: callable with input two 1d ndarrays and returning a float. Note that the returned matrix from corr will have 1 along the diagonals and will be symmetric regardless of the callable's behavior .. versionadded:: 0.24.0 min_periods : int, optional Minimum number of observations required per pair of columns to have a valid result. Currently only available for Pearson and Spearman correlation. Returns ------- DataFrame Correlation matrix. See Also -------- DataFrame.corrwith Series.corr Examples -------- >>> def histogram_intersection(a, b): ... v = np.minimum(a, b).sum().round(decimals=1) ... return v >>> df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], ... columns=['dogs', 'cats']) >>> df.corr(method=histogram_intersection) dogs cats dogs 1.0 0.3 cats 0.3 1.0
pandas/core/frame.py
def corr(self, method='pearson', min_periods=1): """ Compute pairwise correlation of columns, excluding NA/null values. Parameters ---------- method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman rank correlation * callable: callable with input two 1d ndarrays and returning a float. Note that the returned matrix from corr will have 1 along the diagonals and will be symmetric regardless of the callable's behavior .. versionadded:: 0.24.0 min_periods : int, optional Minimum number of observations required per pair of columns to have a valid result. Currently only available for Pearson and Spearman correlation. Returns ------- DataFrame Correlation matrix. See Also -------- DataFrame.corrwith Series.corr Examples -------- >>> def histogram_intersection(a, b): ... v = np.minimum(a, b).sum().round(decimals=1) ... return v >>> df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], ... columns=['dogs', 'cats']) >>> df.corr(method=histogram_intersection) dogs cats dogs 1.0 0.3 cats 0.3 1.0 """ numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() mat = numeric_df.values if method == 'pearson': correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods) elif method == 'spearman': correl = libalgos.nancorr_spearman(ensure_float64(mat), minp=min_periods) elif method == 'kendall' or callable(method): if min_periods is None: min_periods = 1 mat = ensure_float64(mat).T corrf = nanops.get_corr_func(method) K = len(cols) correl = np.empty((K, K), dtype=float) mask = np.isfinite(mat) for i, ac in enumerate(mat): for j, bc in enumerate(mat): if i > j: continue valid = mask[i] & mask[j] if valid.sum() < min_periods: c = np.nan elif i == j: c = 1. elif not valid.all(): c = corrf(ac[valid], bc[valid]) else: c = corrf(ac, bc) correl[i, j] = c correl[j, i] = c else: raise ValueError("method must be either 'pearson', " "'spearman', 'kendall', or a callable, " "'{method}' was supplied".format(method=method)) return self._constructor(correl, index=idx, columns=cols)
def corr(self, method='pearson', min_periods=1): """ Compute pairwise correlation of columns, excluding NA/null values. Parameters ---------- method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman rank correlation * callable: callable with input two 1d ndarrays and returning a float. Note that the returned matrix from corr will have 1 along the diagonals and will be symmetric regardless of the callable's behavior .. versionadded:: 0.24.0 min_periods : int, optional Minimum number of observations required per pair of columns to have a valid result. Currently only available for Pearson and Spearman correlation. Returns ------- DataFrame Correlation matrix. See Also -------- DataFrame.corrwith Series.corr Examples -------- >>> def histogram_intersection(a, b): ... v = np.minimum(a, b).sum().round(decimals=1) ... return v >>> df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], ... columns=['dogs', 'cats']) >>> df.corr(method=histogram_intersection) dogs cats dogs 1.0 0.3 cats 0.3 1.0 """ numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() mat = numeric_df.values if method == 'pearson': correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods) elif method == 'spearman': correl = libalgos.nancorr_spearman(ensure_float64(mat), minp=min_periods) elif method == 'kendall' or callable(method): if min_periods is None: min_periods = 1 mat = ensure_float64(mat).T corrf = nanops.get_corr_func(method) K = len(cols) correl = np.empty((K, K), dtype=float) mask = np.isfinite(mat) for i, ac in enumerate(mat): for j, bc in enumerate(mat): if i > j: continue valid = mask[i] & mask[j] if valid.sum() < min_periods: c = np.nan elif i == j: c = 1. elif not valid.all(): c = corrf(ac[valid], bc[valid]) else: c = corrf(ac, bc) correl[i, j] = c correl[j, i] = c else: raise ValueError("method must be either 'pearson', " "'spearman', 'kendall', or a callable, " "'{method}' was supplied".format(method=method)) return self._constructor(correl, index=idx, columns=cols)
[ "Compute", "pairwise", "correlation", "of", "columns", "excluding", "NA", "/", "null", "values", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7033-L7115
[ "def", "corr", "(", "self", ",", "method", "=", "'pearson'", ",", "min_periods", "=", "1", ")", ":", "numeric_df", "=", "self", ".", "_get_numeric_data", "(", ")", "cols", "=", "numeric_df", ".", "columns", "idx", "=", "cols", ".", "copy", "(", ")", "mat", "=", "numeric_df", ".", "values", "if", "method", "==", "'pearson'", ":", "correl", "=", "libalgos", ".", "nancorr", "(", "ensure_float64", "(", "mat", ")", ",", "minp", "=", "min_periods", ")", "elif", "method", "==", "'spearman'", ":", "correl", "=", "libalgos", ".", "nancorr_spearman", "(", "ensure_float64", "(", "mat", ")", ",", "minp", "=", "min_periods", ")", "elif", "method", "==", "'kendall'", "or", "callable", "(", "method", ")", ":", "if", "min_periods", "is", "None", ":", "min_periods", "=", "1", "mat", "=", "ensure_float64", "(", "mat", ")", ".", "T", "corrf", "=", "nanops", ".", "get_corr_func", "(", "method", ")", "K", "=", "len", "(", "cols", ")", "correl", "=", "np", ".", "empty", "(", "(", "K", ",", "K", ")", ",", "dtype", "=", "float", ")", "mask", "=", "np", ".", "isfinite", "(", "mat", ")", "for", "i", ",", "ac", "in", "enumerate", "(", "mat", ")", ":", "for", "j", ",", "bc", "in", "enumerate", "(", "mat", ")", ":", "if", "i", ">", "j", ":", "continue", "valid", "=", "mask", "[", "i", "]", "&", "mask", "[", "j", "]", "if", "valid", ".", "sum", "(", ")", "<", "min_periods", ":", "c", "=", "np", ".", "nan", "elif", "i", "==", "j", ":", "c", "=", "1.", "elif", "not", "valid", ".", "all", "(", ")", ":", "c", "=", "corrf", "(", "ac", "[", "valid", "]", ",", "bc", "[", "valid", "]", ")", "else", ":", "c", "=", "corrf", "(", "ac", ",", "bc", ")", "correl", "[", "i", ",", "j", "]", "=", "c", "correl", "[", "j", ",", "i", "]", "=", "c", "else", ":", "raise", "ValueError", "(", "\"method must be either 'pearson', \"", "\"'spearman', 'kendall', or a callable, \"", "\"'{method}' was supplied\"", ".", "format", "(", "method", "=", "method", ")", ")", "return", "self", ".", "_constructor", "(", "correl", ",", "index", "=", "idx", ",", "columns", "=", "cols", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.cov
Compute pairwise covariance of columns, excluding NA/null values. Compute the pairwise covariance among the series of a DataFrame. The returned data frame is the `covariance matrix <https://en.wikipedia.org/wiki/Covariance_matrix>`__ of the columns of the DataFrame. Both NA and null values are automatically excluded from the calculation. (See the note below about bias from missing values.) A threshold can be set for the minimum number of observations for each value created. Comparisons with observations below this threshold will be returned as ``NaN``. This method is generally used for the analysis of time series data to understand the relationship between different measures across time. Parameters ---------- min_periods : int, optional Minimum number of observations required per pair of columns to have a valid result. Returns ------- DataFrame The covariance matrix of the series of the DataFrame. See Also -------- Series.cov : Compute covariance with another Series. core.window.EWM.cov: Exponential weighted sample covariance. core.window.Expanding.cov : Expanding sample covariance. core.window.Rolling.cov : Rolling sample covariance. Notes ----- Returns the covariance matrix of the DataFrame's time series. The covariance is normalized by N-1. For DataFrames that have Series that are missing data (assuming that data is `missing at random <https://en.wikipedia.org/wiki/Missing_data#Missing_at_random>`__) the returned covariance matrix will be an unbiased estimate of the variance and covariance between the member Series. However, for many applications this estimate may not be acceptable because the estimate covariance matrix is not guaranteed to be positive semi-definite. This could lead to estimate correlations having absolute values which are greater than one, and/or a non-invertible covariance matrix. See `Estimation of covariance matrices <http://en.wikipedia.org/w/index.php?title=Estimation_of_covariance_ matrices>`__ for more details. Examples -------- >>> df = pd.DataFrame([(1, 2), (0, 3), (2, 0), (1, 1)], ... columns=['dogs', 'cats']) >>> df.cov() dogs cats dogs 0.666667 -1.000000 cats -1.000000 1.666667 >>> np.random.seed(42) >>> df = pd.DataFrame(np.random.randn(1000, 5), ... columns=['a', 'b', 'c', 'd', 'e']) >>> df.cov() a b c d e a 0.998438 -0.020161 0.059277 -0.008943 0.014144 b -0.020161 1.059352 -0.008543 -0.024738 0.009826 c 0.059277 -0.008543 1.010670 -0.001486 -0.000271 d -0.008943 -0.024738 -0.001486 0.921297 -0.013692 e 0.014144 0.009826 -0.000271 -0.013692 0.977795 **Minimum number of periods** This method also supports an optional ``min_periods`` keyword that specifies the required minimum number of non-NA observations for each column pair in order to have a valid result: >>> np.random.seed(42) >>> df = pd.DataFrame(np.random.randn(20, 3), ... columns=['a', 'b', 'c']) >>> df.loc[df.index[:5], 'a'] = np.nan >>> df.loc[df.index[5:10], 'b'] = np.nan >>> df.cov(min_periods=12) a b c a 0.316741 NaN -0.150812 b NaN 1.248003 0.191417 c -0.150812 0.191417 0.895202
pandas/core/frame.py
def cov(self, min_periods=None): """ Compute pairwise covariance of columns, excluding NA/null values. Compute the pairwise covariance among the series of a DataFrame. The returned data frame is the `covariance matrix <https://en.wikipedia.org/wiki/Covariance_matrix>`__ of the columns of the DataFrame. Both NA and null values are automatically excluded from the calculation. (See the note below about bias from missing values.) A threshold can be set for the minimum number of observations for each value created. Comparisons with observations below this threshold will be returned as ``NaN``. This method is generally used for the analysis of time series data to understand the relationship between different measures across time. Parameters ---------- min_periods : int, optional Minimum number of observations required per pair of columns to have a valid result. Returns ------- DataFrame The covariance matrix of the series of the DataFrame. See Also -------- Series.cov : Compute covariance with another Series. core.window.EWM.cov: Exponential weighted sample covariance. core.window.Expanding.cov : Expanding sample covariance. core.window.Rolling.cov : Rolling sample covariance. Notes ----- Returns the covariance matrix of the DataFrame's time series. The covariance is normalized by N-1. For DataFrames that have Series that are missing data (assuming that data is `missing at random <https://en.wikipedia.org/wiki/Missing_data#Missing_at_random>`__) the returned covariance matrix will be an unbiased estimate of the variance and covariance between the member Series. However, for many applications this estimate may not be acceptable because the estimate covariance matrix is not guaranteed to be positive semi-definite. This could lead to estimate correlations having absolute values which are greater than one, and/or a non-invertible covariance matrix. See `Estimation of covariance matrices <http://en.wikipedia.org/w/index.php?title=Estimation_of_covariance_ matrices>`__ for more details. Examples -------- >>> df = pd.DataFrame([(1, 2), (0, 3), (2, 0), (1, 1)], ... columns=['dogs', 'cats']) >>> df.cov() dogs cats dogs 0.666667 -1.000000 cats -1.000000 1.666667 >>> np.random.seed(42) >>> df = pd.DataFrame(np.random.randn(1000, 5), ... columns=['a', 'b', 'c', 'd', 'e']) >>> df.cov() a b c d e a 0.998438 -0.020161 0.059277 -0.008943 0.014144 b -0.020161 1.059352 -0.008543 -0.024738 0.009826 c 0.059277 -0.008543 1.010670 -0.001486 -0.000271 d -0.008943 -0.024738 -0.001486 0.921297 -0.013692 e 0.014144 0.009826 -0.000271 -0.013692 0.977795 **Minimum number of periods** This method also supports an optional ``min_periods`` keyword that specifies the required minimum number of non-NA observations for each column pair in order to have a valid result: >>> np.random.seed(42) >>> df = pd.DataFrame(np.random.randn(20, 3), ... columns=['a', 'b', 'c']) >>> df.loc[df.index[:5], 'a'] = np.nan >>> df.loc[df.index[5:10], 'b'] = np.nan >>> df.cov(min_periods=12) a b c a 0.316741 NaN -0.150812 b NaN 1.248003 0.191417 c -0.150812 0.191417 0.895202 """ numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() mat = numeric_df.values if notna(mat).all(): if min_periods is not None and min_periods > len(mat): baseCov = np.empty((mat.shape[1], mat.shape[1])) baseCov.fill(np.nan) else: baseCov = np.cov(mat.T) baseCov = baseCov.reshape((len(cols), len(cols))) else: baseCov = libalgos.nancorr(ensure_float64(mat), cov=True, minp=min_periods) return self._constructor(baseCov, index=idx, columns=cols)
def cov(self, min_periods=None): """ Compute pairwise covariance of columns, excluding NA/null values. Compute the pairwise covariance among the series of a DataFrame. The returned data frame is the `covariance matrix <https://en.wikipedia.org/wiki/Covariance_matrix>`__ of the columns of the DataFrame. Both NA and null values are automatically excluded from the calculation. (See the note below about bias from missing values.) A threshold can be set for the minimum number of observations for each value created. Comparisons with observations below this threshold will be returned as ``NaN``. This method is generally used for the analysis of time series data to understand the relationship between different measures across time. Parameters ---------- min_periods : int, optional Minimum number of observations required per pair of columns to have a valid result. Returns ------- DataFrame The covariance matrix of the series of the DataFrame. See Also -------- Series.cov : Compute covariance with another Series. core.window.EWM.cov: Exponential weighted sample covariance. core.window.Expanding.cov : Expanding sample covariance. core.window.Rolling.cov : Rolling sample covariance. Notes ----- Returns the covariance matrix of the DataFrame's time series. The covariance is normalized by N-1. For DataFrames that have Series that are missing data (assuming that data is `missing at random <https://en.wikipedia.org/wiki/Missing_data#Missing_at_random>`__) the returned covariance matrix will be an unbiased estimate of the variance and covariance between the member Series. However, for many applications this estimate may not be acceptable because the estimate covariance matrix is not guaranteed to be positive semi-definite. This could lead to estimate correlations having absolute values which are greater than one, and/or a non-invertible covariance matrix. See `Estimation of covariance matrices <http://en.wikipedia.org/w/index.php?title=Estimation_of_covariance_ matrices>`__ for more details. Examples -------- >>> df = pd.DataFrame([(1, 2), (0, 3), (2, 0), (1, 1)], ... columns=['dogs', 'cats']) >>> df.cov() dogs cats dogs 0.666667 -1.000000 cats -1.000000 1.666667 >>> np.random.seed(42) >>> df = pd.DataFrame(np.random.randn(1000, 5), ... columns=['a', 'b', 'c', 'd', 'e']) >>> df.cov() a b c d e a 0.998438 -0.020161 0.059277 -0.008943 0.014144 b -0.020161 1.059352 -0.008543 -0.024738 0.009826 c 0.059277 -0.008543 1.010670 -0.001486 -0.000271 d -0.008943 -0.024738 -0.001486 0.921297 -0.013692 e 0.014144 0.009826 -0.000271 -0.013692 0.977795 **Minimum number of periods** This method also supports an optional ``min_periods`` keyword that specifies the required minimum number of non-NA observations for each column pair in order to have a valid result: >>> np.random.seed(42) >>> df = pd.DataFrame(np.random.randn(20, 3), ... columns=['a', 'b', 'c']) >>> df.loc[df.index[:5], 'a'] = np.nan >>> df.loc[df.index[5:10], 'b'] = np.nan >>> df.cov(min_periods=12) a b c a 0.316741 NaN -0.150812 b NaN 1.248003 0.191417 c -0.150812 0.191417 0.895202 """ numeric_df = self._get_numeric_data() cols = numeric_df.columns idx = cols.copy() mat = numeric_df.values if notna(mat).all(): if min_periods is not None and min_periods > len(mat): baseCov = np.empty((mat.shape[1], mat.shape[1])) baseCov.fill(np.nan) else: baseCov = np.cov(mat.T) baseCov = baseCov.reshape((len(cols), len(cols))) else: baseCov = libalgos.nancorr(ensure_float64(mat), cov=True, minp=min_periods) return self._constructor(baseCov, index=idx, columns=cols)
[ "Compute", "pairwise", "covariance", "of", "columns", "excluding", "NA", "/", "null", "values", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7117-L7226
[ "def", "cov", "(", "self", ",", "min_periods", "=", "None", ")", ":", "numeric_df", "=", "self", ".", "_get_numeric_data", "(", ")", "cols", "=", "numeric_df", ".", "columns", "idx", "=", "cols", ".", "copy", "(", ")", "mat", "=", "numeric_df", ".", "values", "if", "notna", "(", "mat", ")", ".", "all", "(", ")", ":", "if", "min_periods", "is", "not", "None", "and", "min_periods", ">", "len", "(", "mat", ")", ":", "baseCov", "=", "np", ".", "empty", "(", "(", "mat", ".", "shape", "[", "1", "]", ",", "mat", ".", "shape", "[", "1", "]", ")", ")", "baseCov", ".", "fill", "(", "np", ".", "nan", ")", "else", ":", "baseCov", "=", "np", ".", "cov", "(", "mat", ".", "T", ")", "baseCov", "=", "baseCov", ".", "reshape", "(", "(", "len", "(", "cols", ")", ",", "len", "(", "cols", ")", ")", ")", "else", ":", "baseCov", "=", "libalgos", ".", "nancorr", "(", "ensure_float64", "(", "mat", ")", ",", "cov", "=", "True", ",", "minp", "=", "min_periods", ")", "return", "self", ".", "_constructor", "(", "baseCov", ",", "index", "=", "idx", ",", "columns", "=", "cols", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.corrwith
Compute pairwise correlation between rows or columns of DataFrame with rows or columns of Series or DataFrame. DataFrames are first aligned along both axes before computing the correlations. Parameters ---------- other : DataFrame, Series Object with which to compute correlations. axis : {0 or 'index', 1 or 'columns'}, default 0 0 or 'index' to compute column-wise, 1 or 'columns' for row-wise. drop : bool, default False Drop missing indices from result. method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman rank correlation * callable: callable with input two 1d ndarrays and returning a float .. versionadded:: 0.24.0 Returns ------- Series Pairwise correlations. See Also ------- DataFrame.corr
pandas/core/frame.py
def corrwith(self, other, axis=0, drop=False, method='pearson'): """ Compute pairwise correlation between rows or columns of DataFrame with rows or columns of Series or DataFrame. DataFrames are first aligned along both axes before computing the correlations. Parameters ---------- other : DataFrame, Series Object with which to compute correlations. axis : {0 or 'index', 1 or 'columns'}, default 0 0 or 'index' to compute column-wise, 1 or 'columns' for row-wise. drop : bool, default False Drop missing indices from result. method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman rank correlation * callable: callable with input two 1d ndarrays and returning a float .. versionadded:: 0.24.0 Returns ------- Series Pairwise correlations. See Also ------- DataFrame.corr """ axis = self._get_axis_number(axis) this = self._get_numeric_data() if isinstance(other, Series): return this.apply(lambda x: other.corr(x, method=method), axis=axis) other = other._get_numeric_data() left, right = this.align(other, join='inner', copy=False) if axis == 1: left = left.T right = right.T if method == 'pearson': # mask missing values left = left + right * 0 right = right + left * 0 # demeaned data ldem = left - left.mean() rdem = right - right.mean() num = (ldem * rdem).sum() dom = (left.count() - 1) * left.std() * right.std() correl = num / dom elif method in ['kendall', 'spearman'] or callable(method): def c(x): return nanops.nancorr(x[0], x[1], method=method) correl = Series(map(c, zip(left.values.T, right.values.T)), index=left.columns) else: raise ValueError("Invalid method {method} was passed, " "valid methods are: 'pearson', 'kendall', " "'spearman', or callable". format(method=method)) if not drop: # Find non-matching labels along the given axis # and append missing correlations (GH 22375) raxis = 1 if axis == 0 else 0 result_index = (this._get_axis(raxis). union(other._get_axis(raxis))) idx_diff = result_index.difference(correl.index) if len(idx_diff) > 0: correl = correl.append(Series([np.nan] * len(idx_diff), index=idx_diff)) return correl
def corrwith(self, other, axis=0, drop=False, method='pearson'): """ Compute pairwise correlation between rows or columns of DataFrame with rows or columns of Series or DataFrame. DataFrames are first aligned along both axes before computing the correlations. Parameters ---------- other : DataFrame, Series Object with which to compute correlations. axis : {0 or 'index', 1 or 'columns'}, default 0 0 or 'index' to compute column-wise, 1 or 'columns' for row-wise. drop : bool, default False Drop missing indices from result. method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman rank correlation * callable: callable with input two 1d ndarrays and returning a float .. versionadded:: 0.24.0 Returns ------- Series Pairwise correlations. See Also ------- DataFrame.corr """ axis = self._get_axis_number(axis) this = self._get_numeric_data() if isinstance(other, Series): return this.apply(lambda x: other.corr(x, method=method), axis=axis) other = other._get_numeric_data() left, right = this.align(other, join='inner', copy=False) if axis == 1: left = left.T right = right.T if method == 'pearson': # mask missing values left = left + right * 0 right = right + left * 0 # demeaned data ldem = left - left.mean() rdem = right - right.mean() num = (ldem * rdem).sum() dom = (left.count() - 1) * left.std() * right.std() correl = num / dom elif method in ['kendall', 'spearman'] or callable(method): def c(x): return nanops.nancorr(x[0], x[1], method=method) correl = Series(map(c, zip(left.values.T, right.values.T)), index=left.columns) else: raise ValueError("Invalid method {method} was passed, " "valid methods are: 'pearson', 'kendall', " "'spearman', or callable". format(method=method)) if not drop: # Find non-matching labels along the given axis # and append missing correlations (GH 22375) raxis = 1 if axis == 0 else 0 result_index = (this._get_axis(raxis). union(other._get_axis(raxis))) idx_diff = result_index.difference(correl.index) if len(idx_diff) > 0: correl = correl.append(Series([np.nan] * len(idx_diff), index=idx_diff)) return correl
[ "Compute", "pairwise", "correlation", "between", "rows", "or", "columns", "of", "DataFrame", "with", "rows", "or", "columns", "of", "Series", "or", "DataFrame", ".", "DataFrames", "are", "first", "aligned", "along", "both", "axes", "before", "computing", "the", "correlations", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7228-L7314
[ "def", "corrwith", "(", "self", ",", "other", ",", "axis", "=", "0", ",", "drop", "=", "False", ",", "method", "=", "'pearson'", ")", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "this", "=", "self", ".", "_get_numeric_data", "(", ")", "if", "isinstance", "(", "other", ",", "Series", ")", ":", "return", "this", ".", "apply", "(", "lambda", "x", ":", "other", ".", "corr", "(", "x", ",", "method", "=", "method", ")", ",", "axis", "=", "axis", ")", "other", "=", "other", ".", "_get_numeric_data", "(", ")", "left", ",", "right", "=", "this", ".", "align", "(", "other", ",", "join", "=", "'inner'", ",", "copy", "=", "False", ")", "if", "axis", "==", "1", ":", "left", "=", "left", ".", "T", "right", "=", "right", ".", "T", "if", "method", "==", "'pearson'", ":", "# mask missing values", "left", "=", "left", "+", "right", "*", "0", "right", "=", "right", "+", "left", "*", "0", "# demeaned data", "ldem", "=", "left", "-", "left", ".", "mean", "(", ")", "rdem", "=", "right", "-", "right", ".", "mean", "(", ")", "num", "=", "(", "ldem", "*", "rdem", ")", ".", "sum", "(", ")", "dom", "=", "(", "left", ".", "count", "(", ")", "-", "1", ")", "*", "left", ".", "std", "(", ")", "*", "right", ".", "std", "(", ")", "correl", "=", "num", "/", "dom", "elif", "method", "in", "[", "'kendall'", ",", "'spearman'", "]", "or", "callable", "(", "method", ")", ":", "def", "c", "(", "x", ")", ":", "return", "nanops", ".", "nancorr", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ",", "method", "=", "method", ")", "correl", "=", "Series", "(", "map", "(", "c", ",", "zip", "(", "left", ".", "values", ".", "T", ",", "right", ".", "values", ".", "T", ")", ")", ",", "index", "=", "left", ".", "columns", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid method {method} was passed, \"", "\"valid methods are: 'pearson', 'kendall', \"", "\"'spearman', or callable\"", ".", "format", "(", "method", "=", "method", ")", ")", "if", "not", "drop", ":", "# Find non-matching labels along the given axis", "# and append missing correlations (GH 22375)", "raxis", "=", "1", "if", "axis", "==", "0", "else", "0", "result_index", "=", "(", "this", ".", "_get_axis", "(", "raxis", ")", ".", "union", "(", "other", ".", "_get_axis", "(", "raxis", ")", ")", ")", "idx_diff", "=", "result_index", ".", "difference", "(", "correl", ".", "index", ")", "if", "len", "(", "idx_diff", ")", ">", "0", ":", "correl", "=", "correl", ".", "append", "(", "Series", "(", "[", "np", ".", "nan", "]", "*", "len", "(", "idx_diff", ")", ",", "index", "=", "idx_diff", ")", ")", "return", "correl" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.count
Count non-NA cells for each column or row. The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending on `pandas.options.mode.use_inf_as_na`) are considered NA. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 If 0 or 'index' counts are generated for each column. If 1 or 'columns' counts are generated for each **row**. level : int or str, optional If the axis is a `MultiIndex` (hierarchical), count along a particular `level`, collapsing into a `DataFrame`. A `str` specifies the level name. numeric_only : bool, default False Include only `float`, `int` or `boolean` data. Returns ------- Series or DataFrame For each column/row the number of non-NA/null entries. If `level` is specified returns a `DataFrame`. See Also -------- Series.count: Number of non-NA elements in a Series. DataFrame.shape: Number of DataFrame rows and columns (including NA elements). DataFrame.isna: Boolean same-sized DataFrame showing places of NA elements. Examples -------- Constructing DataFrame from a dictionary: >>> df = pd.DataFrame({"Person": ... ["John", "Myla", "Lewis", "John", "Myla"], ... "Age": [24., np.nan, 21., 33, 26], ... "Single": [False, True, True, True, False]}) >>> df Person Age Single 0 John 24.0 False 1 Myla NaN True 2 Lewis 21.0 True 3 John 33.0 True 4 Myla 26.0 False Notice the uncounted NA values: >>> df.count() Person 5 Age 4 Single 5 dtype: int64 Counts for each **row**: >>> df.count(axis='columns') 0 3 1 2 2 3 3 3 4 3 dtype: int64 Counts for one level of a `MultiIndex`: >>> df.set_index(["Person", "Single"]).count(level="Person") Age Person John 2 Lewis 1 Myla 1
pandas/core/frame.py
def count(self, axis=0, level=None, numeric_only=False): """ Count non-NA cells for each column or row. The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending on `pandas.options.mode.use_inf_as_na`) are considered NA. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 If 0 or 'index' counts are generated for each column. If 1 or 'columns' counts are generated for each **row**. level : int or str, optional If the axis is a `MultiIndex` (hierarchical), count along a particular `level`, collapsing into a `DataFrame`. A `str` specifies the level name. numeric_only : bool, default False Include only `float`, `int` or `boolean` data. Returns ------- Series or DataFrame For each column/row the number of non-NA/null entries. If `level` is specified returns a `DataFrame`. See Also -------- Series.count: Number of non-NA elements in a Series. DataFrame.shape: Number of DataFrame rows and columns (including NA elements). DataFrame.isna: Boolean same-sized DataFrame showing places of NA elements. Examples -------- Constructing DataFrame from a dictionary: >>> df = pd.DataFrame({"Person": ... ["John", "Myla", "Lewis", "John", "Myla"], ... "Age": [24., np.nan, 21., 33, 26], ... "Single": [False, True, True, True, False]}) >>> df Person Age Single 0 John 24.0 False 1 Myla NaN True 2 Lewis 21.0 True 3 John 33.0 True 4 Myla 26.0 False Notice the uncounted NA values: >>> df.count() Person 5 Age 4 Single 5 dtype: int64 Counts for each **row**: >>> df.count(axis='columns') 0 3 1 2 2 3 3 3 4 3 dtype: int64 Counts for one level of a `MultiIndex`: >>> df.set_index(["Person", "Single"]).count(level="Person") Age Person John 2 Lewis 1 Myla 1 """ axis = self._get_axis_number(axis) if level is not None: return self._count_level(level, axis=axis, numeric_only=numeric_only) if numeric_only: frame = self._get_numeric_data() else: frame = self # GH #423 if len(frame._get_axis(axis)) == 0: result = Series(0, index=frame._get_agg_axis(axis)) else: if frame._is_mixed_type or frame._data.any_extension_types: # the or any_extension_types is really only hit for single- # column frames with an extension array result = notna(frame).sum(axis=axis) else: # GH13407 series_counts = notna(frame).sum(axis=axis) counts = series_counts.values result = Series(counts, index=frame._get_agg_axis(axis)) return result.astype('int64')
def count(self, axis=0, level=None, numeric_only=False): """ Count non-NA cells for each column or row. The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending on `pandas.options.mode.use_inf_as_na`) are considered NA. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 If 0 or 'index' counts are generated for each column. If 1 or 'columns' counts are generated for each **row**. level : int or str, optional If the axis is a `MultiIndex` (hierarchical), count along a particular `level`, collapsing into a `DataFrame`. A `str` specifies the level name. numeric_only : bool, default False Include only `float`, `int` or `boolean` data. Returns ------- Series or DataFrame For each column/row the number of non-NA/null entries. If `level` is specified returns a `DataFrame`. See Also -------- Series.count: Number of non-NA elements in a Series. DataFrame.shape: Number of DataFrame rows and columns (including NA elements). DataFrame.isna: Boolean same-sized DataFrame showing places of NA elements. Examples -------- Constructing DataFrame from a dictionary: >>> df = pd.DataFrame({"Person": ... ["John", "Myla", "Lewis", "John", "Myla"], ... "Age": [24., np.nan, 21., 33, 26], ... "Single": [False, True, True, True, False]}) >>> df Person Age Single 0 John 24.0 False 1 Myla NaN True 2 Lewis 21.0 True 3 John 33.0 True 4 Myla 26.0 False Notice the uncounted NA values: >>> df.count() Person 5 Age 4 Single 5 dtype: int64 Counts for each **row**: >>> df.count(axis='columns') 0 3 1 2 2 3 3 3 4 3 dtype: int64 Counts for one level of a `MultiIndex`: >>> df.set_index(["Person", "Single"]).count(level="Person") Age Person John 2 Lewis 1 Myla 1 """ axis = self._get_axis_number(axis) if level is not None: return self._count_level(level, axis=axis, numeric_only=numeric_only) if numeric_only: frame = self._get_numeric_data() else: frame = self # GH #423 if len(frame._get_axis(axis)) == 0: result = Series(0, index=frame._get_agg_axis(axis)) else: if frame._is_mixed_type or frame._data.any_extension_types: # the or any_extension_types is really only hit for single- # column frames with an extension array result = notna(frame).sum(axis=axis) else: # GH13407 series_counts = notna(frame).sum(axis=axis) counts = series_counts.values result = Series(counts, index=frame._get_agg_axis(axis)) return result.astype('int64')
[ "Count", "non", "-", "NA", "cells", "for", "each", "column", "or", "row", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7319-L7419
[ "def", "count", "(", "self", ",", "axis", "=", "0", ",", "level", "=", "None", ",", "numeric_only", "=", "False", ")", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "if", "level", "is", "not", "None", ":", "return", "self", ".", "_count_level", "(", "level", ",", "axis", "=", "axis", ",", "numeric_only", "=", "numeric_only", ")", "if", "numeric_only", ":", "frame", "=", "self", ".", "_get_numeric_data", "(", ")", "else", ":", "frame", "=", "self", "# GH #423", "if", "len", "(", "frame", ".", "_get_axis", "(", "axis", ")", ")", "==", "0", ":", "result", "=", "Series", "(", "0", ",", "index", "=", "frame", ".", "_get_agg_axis", "(", "axis", ")", ")", "else", ":", "if", "frame", ".", "_is_mixed_type", "or", "frame", ".", "_data", ".", "any_extension_types", ":", "# the or any_extension_types is really only hit for single-", "# column frames with an extension array", "result", "=", "notna", "(", "frame", ")", ".", "sum", "(", "axis", "=", "axis", ")", "else", ":", "# GH13407", "series_counts", "=", "notna", "(", "frame", ")", ".", "sum", "(", "axis", "=", "axis", ")", "counts", "=", "series_counts", ".", "values", "result", "=", "Series", "(", "counts", ",", "index", "=", "frame", ".", "_get_agg_axis", "(", "axis", ")", ")", "return", "result", ".", "astype", "(", "'int64'", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.nunique
Count distinct observations over requested axis. Return Series with number of distinct observations. Can ignore NaN values. .. versionadded:: 0.20.0 Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise. dropna : bool, default True Don't include NaN in the counts. Returns ------- Series See Also -------- Series.nunique: Method nunique for Series. DataFrame.count: Count non-NA cells for each column or row. Examples -------- >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]}) >>> df.nunique() A 3 B 1 dtype: int64 >>> df.nunique(axis=1) 0 1 1 2 2 2 dtype: int64
pandas/core/frame.py
def nunique(self, axis=0, dropna=True): """ Count distinct observations over requested axis. Return Series with number of distinct observations. Can ignore NaN values. .. versionadded:: 0.20.0 Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise. dropna : bool, default True Don't include NaN in the counts. Returns ------- Series See Also -------- Series.nunique: Method nunique for Series. DataFrame.count: Count non-NA cells for each column or row. Examples -------- >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]}) >>> df.nunique() A 3 B 1 dtype: int64 >>> df.nunique(axis=1) 0 1 1 2 2 2 dtype: int64 """ return self.apply(Series.nunique, axis=axis, dropna=dropna)
def nunique(self, axis=0, dropna=True): """ Count distinct observations over requested axis. Return Series with number of distinct observations. Can ignore NaN values. .. versionadded:: 0.20.0 Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise. dropna : bool, default True Don't include NaN in the counts. Returns ------- Series See Also -------- Series.nunique: Method nunique for Series. DataFrame.count: Count non-NA cells for each column or row. Examples -------- >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]}) >>> df.nunique() A 3 B 1 dtype: int64 >>> df.nunique(axis=1) 0 1 1 2 2 2 dtype: int64 """ return self.apply(Series.nunique, axis=axis, dropna=dropna)
[ "Count", "distinct", "observations", "over", "requested", "axis", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7565-L7605
[ "def", "nunique", "(", "self", ",", "axis", "=", "0", ",", "dropna", "=", "True", ")", ":", "return", "self", ".", "apply", "(", "Series", ".", "nunique", ",", "axis", "=", "axis", ",", "dropna", "=", "dropna", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.idxmin
Return index of first occurrence of minimum over requested axis. NA/null values are excluded. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 0 or 'index' for row-wise, 1 or 'columns' for column-wise skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- Series Indexes of minima along the specified axis. Raises ------ ValueError * If the row/column is empty See Also -------- Series.idxmin Notes ----- This method is the DataFrame version of ``ndarray.argmin``.
pandas/core/frame.py
def idxmin(self, axis=0, skipna=True): """ Return index of first occurrence of minimum over requested axis. NA/null values are excluded. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 0 or 'index' for row-wise, 1 or 'columns' for column-wise skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- Series Indexes of minima along the specified axis. Raises ------ ValueError * If the row/column is empty See Also -------- Series.idxmin Notes ----- This method is the DataFrame version of ``ndarray.argmin``. """ axis = self._get_axis_number(axis) indices = nanops.nanargmin(self.values, axis=axis, skipna=skipna) index = self._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return Series(result, index=self._get_agg_axis(axis))
def idxmin(self, axis=0, skipna=True): """ Return index of first occurrence of minimum over requested axis. NA/null values are excluded. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 0 or 'index' for row-wise, 1 or 'columns' for column-wise skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- Series Indexes of minima along the specified axis. Raises ------ ValueError * If the row/column is empty See Also -------- Series.idxmin Notes ----- This method is the DataFrame version of ``ndarray.argmin``. """ axis = self._get_axis_number(axis) indices = nanops.nanargmin(self.values, axis=axis, skipna=skipna) index = self._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return Series(result, index=self._get_agg_axis(axis))
[ "Return", "index", "of", "first", "occurrence", "of", "minimum", "over", "requested", "axis", ".", "NA", "/", "null", "values", "are", "excluded", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7607-L7642
[ "def", "idxmin", "(", "self", ",", "axis", "=", "0", ",", "skipna", "=", "True", ")", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "indices", "=", "nanops", ".", "nanargmin", "(", "self", ".", "values", ",", "axis", "=", "axis", ",", "skipna", "=", "skipna", ")", "index", "=", "self", ".", "_get_axis", "(", "axis", ")", "result", "=", "[", "index", "[", "i", "]", "if", "i", ">=", "0", "else", "np", ".", "nan", "for", "i", "in", "indices", "]", "return", "Series", "(", "result", ",", "index", "=", "self", ".", "_get_agg_axis", "(", "axis", ")", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame._get_agg_axis
Let's be explicit about this.
pandas/core/frame.py
def _get_agg_axis(self, axis_num): """ Let's be explicit about this. """ if axis_num == 0: return self.columns elif axis_num == 1: return self.index else: raise ValueError('Axis must be 0 or 1 (got %r)' % axis_num)
def _get_agg_axis(self, axis_num): """ Let's be explicit about this. """ if axis_num == 0: return self.columns elif axis_num == 1: return self.index else: raise ValueError('Axis must be 0 or 1 (got %r)' % axis_num)
[ "Let", "s", "be", "explicit", "about", "this", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7681-L7690
[ "def", "_get_agg_axis", "(", "self", ",", "axis_num", ")", ":", "if", "axis_num", "==", "0", ":", "return", "self", ".", "columns", "elif", "axis_num", "==", "1", ":", "return", "self", ".", "index", "else", ":", "raise", "ValueError", "(", "'Axis must be 0 or 1 (got %r)'", "%", "axis_num", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.mode
Get the mode(s) of each element along the selected axis. The mode of a set of values is the value that appears most often. It can be multiple values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to iterate over while searching for the mode: * 0 or 'index' : get mode of each column * 1 or 'columns' : get mode of each row numeric_only : bool, default False If True, only apply to numeric columns. dropna : bool, default True Don't consider counts of NaN/NaT. .. versionadded:: 0.24.0 Returns ------- DataFrame The modes of each column or row. See Also -------- Series.mode : Return the highest frequency value in a Series. Series.value_counts : Return the counts of values in a Series. Examples -------- >>> df = pd.DataFrame([('bird', 2, 2), ... ('mammal', 4, np.nan), ... ('arthropod', 8, 0), ... ('bird', 2, np.nan)], ... index=('falcon', 'horse', 'spider', 'ostrich'), ... columns=('species', 'legs', 'wings')) >>> df species legs wings falcon bird 2 2.0 horse mammal 4 NaN spider arthropod 8 0.0 ostrich bird 2 NaN By default, missing values are not considered, and the mode of wings are both 0 and 2. The second row of species and legs contains ``NaN``, because they have only one mode, but the DataFrame has two rows. >>> df.mode() species legs wings 0 bird 2.0 0.0 1 NaN NaN 2.0 Setting ``dropna=False`` ``NaN`` values are considered and they can be the mode (like for wings). >>> df.mode(dropna=False) species legs wings 0 bird 2 NaN Setting ``numeric_only=True``, only the mode of numeric columns is computed, and columns of other types are ignored. >>> df.mode(numeric_only=True) legs wings 0 2.0 0.0 1 NaN 2.0 To compute the mode over columns and not rows, use the axis parameter: >>> df.mode(axis='columns', numeric_only=True) 0 1 falcon 2.0 NaN horse 4.0 NaN spider 0.0 8.0 ostrich 2.0 NaN
pandas/core/frame.py
def mode(self, axis=0, numeric_only=False, dropna=True): """ Get the mode(s) of each element along the selected axis. The mode of a set of values is the value that appears most often. It can be multiple values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to iterate over while searching for the mode: * 0 or 'index' : get mode of each column * 1 or 'columns' : get mode of each row numeric_only : bool, default False If True, only apply to numeric columns. dropna : bool, default True Don't consider counts of NaN/NaT. .. versionadded:: 0.24.0 Returns ------- DataFrame The modes of each column or row. See Also -------- Series.mode : Return the highest frequency value in a Series. Series.value_counts : Return the counts of values in a Series. Examples -------- >>> df = pd.DataFrame([('bird', 2, 2), ... ('mammal', 4, np.nan), ... ('arthropod', 8, 0), ... ('bird', 2, np.nan)], ... index=('falcon', 'horse', 'spider', 'ostrich'), ... columns=('species', 'legs', 'wings')) >>> df species legs wings falcon bird 2 2.0 horse mammal 4 NaN spider arthropod 8 0.0 ostrich bird 2 NaN By default, missing values are not considered, and the mode of wings are both 0 and 2. The second row of species and legs contains ``NaN``, because they have only one mode, but the DataFrame has two rows. >>> df.mode() species legs wings 0 bird 2.0 0.0 1 NaN NaN 2.0 Setting ``dropna=False`` ``NaN`` values are considered and they can be the mode (like for wings). >>> df.mode(dropna=False) species legs wings 0 bird 2 NaN Setting ``numeric_only=True``, only the mode of numeric columns is computed, and columns of other types are ignored. >>> df.mode(numeric_only=True) legs wings 0 2.0 0.0 1 NaN 2.0 To compute the mode over columns and not rows, use the axis parameter: >>> df.mode(axis='columns', numeric_only=True) 0 1 falcon 2.0 NaN horse 4.0 NaN spider 0.0 8.0 ostrich 2.0 NaN """ data = self if not numeric_only else self._get_numeric_data() def f(s): return s.mode(dropna=dropna) return data.apply(f, axis=axis)
def mode(self, axis=0, numeric_only=False, dropna=True): """ Get the mode(s) of each element along the selected axis. The mode of a set of values is the value that appears most often. It can be multiple values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to iterate over while searching for the mode: * 0 or 'index' : get mode of each column * 1 or 'columns' : get mode of each row numeric_only : bool, default False If True, only apply to numeric columns. dropna : bool, default True Don't consider counts of NaN/NaT. .. versionadded:: 0.24.0 Returns ------- DataFrame The modes of each column or row. See Also -------- Series.mode : Return the highest frequency value in a Series. Series.value_counts : Return the counts of values in a Series. Examples -------- >>> df = pd.DataFrame([('bird', 2, 2), ... ('mammal', 4, np.nan), ... ('arthropod', 8, 0), ... ('bird', 2, np.nan)], ... index=('falcon', 'horse', 'spider', 'ostrich'), ... columns=('species', 'legs', 'wings')) >>> df species legs wings falcon bird 2 2.0 horse mammal 4 NaN spider arthropod 8 0.0 ostrich bird 2 NaN By default, missing values are not considered, and the mode of wings are both 0 and 2. The second row of species and legs contains ``NaN``, because they have only one mode, but the DataFrame has two rows. >>> df.mode() species legs wings 0 bird 2.0 0.0 1 NaN NaN 2.0 Setting ``dropna=False`` ``NaN`` values are considered and they can be the mode (like for wings). >>> df.mode(dropna=False) species legs wings 0 bird 2 NaN Setting ``numeric_only=True``, only the mode of numeric columns is computed, and columns of other types are ignored. >>> df.mode(numeric_only=True) legs wings 0 2.0 0.0 1 NaN 2.0 To compute the mode over columns and not rows, use the axis parameter: >>> df.mode(axis='columns', numeric_only=True) 0 1 falcon 2.0 NaN horse 4.0 NaN spider 0.0 8.0 ostrich 2.0 NaN """ data = self if not numeric_only else self._get_numeric_data() def f(s): return s.mode(dropna=dropna) return data.apply(f, axis=axis)
[ "Get", "the", "mode", "(", "s", ")", "of", "each", "element", "along", "the", "selected", "axis", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7692-L7776
[ "def", "mode", "(", "self", ",", "axis", "=", "0", ",", "numeric_only", "=", "False", ",", "dropna", "=", "True", ")", ":", "data", "=", "self", "if", "not", "numeric_only", "else", "self", ".", "_get_numeric_data", "(", ")", "def", "f", "(", "s", ")", ":", "return", "s", ".", "mode", "(", "dropna", "=", "dropna", ")", "return", "data", ".", "apply", "(", "f", ",", "axis", "=", "axis", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.quantile
Return values at the given quantile over requested axis. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value between 0 <= q <= 1, the quantile(s) to compute. axis : {0, 1, 'index', 'columns'} (default 0) Equals 0 or 'index' for row-wise, 1 or 'columns' for column-wise. numeric_only : bool, default True If False, the quantile of datetime and timedelta data will be computed as well. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to use, when the desired quantile lies between two data points `i` and `j`: * linear: `i + (j - i) * fraction`, where `fraction` is the fractional part of the index surrounded by `i` and `j`. * lower: `i`. * higher: `j`. * nearest: `i` or `j` whichever is nearest. * midpoint: (`i` + `j`) / 2. .. versionadded:: 0.18.0 Returns ------- Series or DataFrame If ``q`` is an array, a DataFrame will be returned where the index is ``q``, the columns are the columns of self, and the values are the quantiles. If ``q`` is a float, a Series will be returned where the index is the columns of self and the values are the quantiles. See Also -------- core.window.Rolling.quantile: Rolling quantile. numpy.percentile: Numpy function to compute the percentile. Examples -------- >>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]), ... columns=['a', 'b']) >>> df.quantile(.1) a 1.3 b 3.7 Name: 0.1, dtype: float64 >>> df.quantile([.1, .5]) a b 0.1 1.3 3.7 0.5 2.5 55.0 Specifying `numeric_only=False` will also compute the quantile of datetime and timedelta data. >>> df = pd.DataFrame({'A': [1, 2], ... 'B': [pd.Timestamp('2010'), ... pd.Timestamp('2011')], ... 'C': [pd.Timedelta('1 days'), ... pd.Timedelta('2 days')]}) >>> df.quantile(0.5, numeric_only=False) A 1.5 B 2010-07-02 12:00:00 C 1 days 12:00:00 Name: 0.5, dtype: object
pandas/core/frame.py
def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation='linear'): """ Return values at the given quantile over requested axis. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value between 0 <= q <= 1, the quantile(s) to compute. axis : {0, 1, 'index', 'columns'} (default 0) Equals 0 or 'index' for row-wise, 1 or 'columns' for column-wise. numeric_only : bool, default True If False, the quantile of datetime and timedelta data will be computed as well. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to use, when the desired quantile lies between two data points `i` and `j`: * linear: `i + (j - i) * fraction`, where `fraction` is the fractional part of the index surrounded by `i` and `j`. * lower: `i`. * higher: `j`. * nearest: `i` or `j` whichever is nearest. * midpoint: (`i` + `j`) / 2. .. versionadded:: 0.18.0 Returns ------- Series or DataFrame If ``q`` is an array, a DataFrame will be returned where the index is ``q``, the columns are the columns of self, and the values are the quantiles. If ``q`` is a float, a Series will be returned where the index is the columns of self and the values are the quantiles. See Also -------- core.window.Rolling.quantile: Rolling quantile. numpy.percentile: Numpy function to compute the percentile. Examples -------- >>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]), ... columns=['a', 'b']) >>> df.quantile(.1) a 1.3 b 3.7 Name: 0.1, dtype: float64 >>> df.quantile([.1, .5]) a b 0.1 1.3 3.7 0.5 2.5 55.0 Specifying `numeric_only=False` will also compute the quantile of datetime and timedelta data. >>> df = pd.DataFrame({'A': [1, 2], ... 'B': [pd.Timestamp('2010'), ... pd.Timestamp('2011')], ... 'C': [pd.Timedelta('1 days'), ... pd.Timedelta('2 days')]}) >>> df.quantile(0.5, numeric_only=False) A 1.5 B 2010-07-02 12:00:00 C 1 days 12:00:00 Name: 0.5, dtype: object """ self._check_percentile(q) data = self._get_numeric_data() if numeric_only else self axis = self._get_axis_number(axis) is_transposed = axis == 1 if is_transposed: data = data.T result = data._data.quantile(qs=q, axis=1, interpolation=interpolation, transposed=is_transposed) if result.ndim == 2: result = self._constructor(result) else: result = self._constructor_sliced(result, name=q) if is_transposed: result = result.T return result
def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation='linear'): """ Return values at the given quantile over requested axis. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value between 0 <= q <= 1, the quantile(s) to compute. axis : {0, 1, 'index', 'columns'} (default 0) Equals 0 or 'index' for row-wise, 1 or 'columns' for column-wise. numeric_only : bool, default True If False, the quantile of datetime and timedelta data will be computed as well. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to use, when the desired quantile lies between two data points `i` and `j`: * linear: `i + (j - i) * fraction`, where `fraction` is the fractional part of the index surrounded by `i` and `j`. * lower: `i`. * higher: `j`. * nearest: `i` or `j` whichever is nearest. * midpoint: (`i` + `j`) / 2. .. versionadded:: 0.18.0 Returns ------- Series or DataFrame If ``q`` is an array, a DataFrame will be returned where the index is ``q``, the columns are the columns of self, and the values are the quantiles. If ``q`` is a float, a Series will be returned where the index is the columns of self and the values are the quantiles. See Also -------- core.window.Rolling.quantile: Rolling quantile. numpy.percentile: Numpy function to compute the percentile. Examples -------- >>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]), ... columns=['a', 'b']) >>> df.quantile(.1) a 1.3 b 3.7 Name: 0.1, dtype: float64 >>> df.quantile([.1, .5]) a b 0.1 1.3 3.7 0.5 2.5 55.0 Specifying `numeric_only=False` will also compute the quantile of datetime and timedelta data. >>> df = pd.DataFrame({'A': [1, 2], ... 'B': [pd.Timestamp('2010'), ... pd.Timestamp('2011')], ... 'C': [pd.Timedelta('1 days'), ... pd.Timedelta('2 days')]}) >>> df.quantile(0.5, numeric_only=False) A 1.5 B 2010-07-02 12:00:00 C 1 days 12:00:00 Name: 0.5, dtype: object """ self._check_percentile(q) data = self._get_numeric_data() if numeric_only else self axis = self._get_axis_number(axis) is_transposed = axis == 1 if is_transposed: data = data.T result = data._data.quantile(qs=q, axis=1, interpolation=interpolation, transposed=is_transposed) if result.ndim == 2: result = self._constructor(result) else: result = self._constructor_sliced(result, name=q) if is_transposed: result = result.T return result
[ "Return", "values", "at", "the", "given", "quantile", "over", "requested", "axis", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7778-L7869
[ "def", "quantile", "(", "self", ",", "q", "=", "0.5", ",", "axis", "=", "0", ",", "numeric_only", "=", "True", ",", "interpolation", "=", "'linear'", ")", ":", "self", ".", "_check_percentile", "(", "q", ")", "data", "=", "self", ".", "_get_numeric_data", "(", ")", "if", "numeric_only", "else", "self", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "is_transposed", "=", "axis", "==", "1", "if", "is_transposed", ":", "data", "=", "data", ".", "T", "result", "=", "data", ".", "_data", ".", "quantile", "(", "qs", "=", "q", ",", "axis", "=", "1", ",", "interpolation", "=", "interpolation", ",", "transposed", "=", "is_transposed", ")", "if", "result", ".", "ndim", "==", "2", ":", "result", "=", "self", ".", "_constructor", "(", "result", ")", "else", ":", "result", "=", "self", ".", "_constructor_sliced", "(", "result", ",", "name", "=", "q", ")", "if", "is_transposed", ":", "result", "=", "result", ".", "T", "return", "result" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.to_timestamp
Cast to DatetimeIndex of timestamps, at *beginning* of period. Parameters ---------- freq : str, default frequency of PeriodIndex Desired frequency. how : {'s', 'e', 'start', 'end'} Convention for converting period to timestamp; start of period vs. end. axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to convert (the index by default). copy : bool, default True If False then underlying input data is not copied. Returns ------- DataFrame with DatetimeIndex
pandas/core/frame.py
def to_timestamp(self, freq=None, how='start', axis=0, copy=True): """ Cast to DatetimeIndex of timestamps, at *beginning* of period. Parameters ---------- freq : str, default frequency of PeriodIndex Desired frequency. how : {'s', 'e', 'start', 'end'} Convention for converting period to timestamp; start of period vs. end. axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to convert (the index by default). copy : bool, default True If False then underlying input data is not copied. Returns ------- DataFrame with DatetimeIndex """ new_data = self._data if copy: new_data = new_data.copy() axis = self._get_axis_number(axis) if axis == 0: new_data.set_axis(1, self.index.to_timestamp(freq=freq, how=how)) elif axis == 1: new_data.set_axis(0, self.columns.to_timestamp(freq=freq, how=how)) else: # pragma: no cover raise AssertionError('Axis must be 0 or 1. Got {ax!s}'.format( ax=axis)) return self._constructor(new_data)
def to_timestamp(self, freq=None, how='start', axis=0, copy=True): """ Cast to DatetimeIndex of timestamps, at *beginning* of period. Parameters ---------- freq : str, default frequency of PeriodIndex Desired frequency. how : {'s', 'e', 'start', 'end'} Convention for converting period to timestamp; start of period vs. end. axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to convert (the index by default). copy : bool, default True If False then underlying input data is not copied. Returns ------- DataFrame with DatetimeIndex """ new_data = self._data if copy: new_data = new_data.copy() axis = self._get_axis_number(axis) if axis == 0: new_data.set_axis(1, self.index.to_timestamp(freq=freq, how=how)) elif axis == 1: new_data.set_axis(0, self.columns.to_timestamp(freq=freq, how=how)) else: # pragma: no cover raise AssertionError('Axis must be 0 or 1. Got {ax!s}'.format( ax=axis)) return self._constructor(new_data)
[ "Cast", "to", "DatetimeIndex", "of", "timestamps", "at", "*", "beginning", "*", "of", "period", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7871-L7904
[ "def", "to_timestamp", "(", "self", ",", "freq", "=", "None", ",", "how", "=", "'start'", ",", "axis", "=", "0", ",", "copy", "=", "True", ")", ":", "new_data", "=", "self", ".", "_data", "if", "copy", ":", "new_data", "=", "new_data", ".", "copy", "(", ")", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "if", "axis", "==", "0", ":", "new_data", ".", "set_axis", "(", "1", ",", "self", ".", "index", ".", "to_timestamp", "(", "freq", "=", "freq", ",", "how", "=", "how", ")", ")", "elif", "axis", "==", "1", ":", "new_data", ".", "set_axis", "(", "0", ",", "self", ".", "columns", ".", "to_timestamp", "(", "freq", "=", "freq", ",", "how", "=", "how", ")", ")", "else", ":", "# pragma: no cover", "raise", "AssertionError", "(", "'Axis must be 0 or 1. Got {ax!s}'", ".", "format", "(", "ax", "=", "axis", ")", ")", "return", "self", ".", "_constructor", "(", "new_data", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
DataFrame.isin
Whether each element in the DataFrame is contained in values. Parameters ---------- values : iterable, Series, DataFrame or dict The result will only be true at a location if all the labels match. If `values` is a Series, that's the index. If `values` is a dict, the keys must be the column names, which must match. If `values` is a DataFrame, then both the index and column labels must match. Returns ------- DataFrame DataFrame of booleans showing whether each element in the DataFrame is contained in values. See Also -------- DataFrame.eq: Equality test for DataFrame. Series.isin: Equivalent method on Series. Series.str.contains: Test if pattern or regex is contained within a string of a Series or Index. Examples -------- >>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]}, ... index=['falcon', 'dog']) >>> df num_legs num_wings falcon 2 2 dog 4 0 When ``values`` is a list check whether every value in the DataFrame is present in the list (which animals have 0 or 2 legs or wings) >>> df.isin([0, 2]) num_legs num_wings falcon True True dog False True When ``values`` is a dict, we can pass values to check for each column separately: >>> df.isin({'num_wings': [0, 3]}) num_legs num_wings falcon False False dog False True When ``values`` is a Series or DataFrame the index and column must match. Note that 'falcon' does not match based on the number of legs in df2. >>> other = pd.DataFrame({'num_legs': [8, 2], 'num_wings': [0, 2]}, ... index=['spider', 'falcon']) >>> df.isin(other) num_legs num_wings falcon True True dog False False
pandas/core/frame.py
def isin(self, values): """ Whether each element in the DataFrame is contained in values. Parameters ---------- values : iterable, Series, DataFrame or dict The result will only be true at a location if all the labels match. If `values` is a Series, that's the index. If `values` is a dict, the keys must be the column names, which must match. If `values` is a DataFrame, then both the index and column labels must match. Returns ------- DataFrame DataFrame of booleans showing whether each element in the DataFrame is contained in values. See Also -------- DataFrame.eq: Equality test for DataFrame. Series.isin: Equivalent method on Series. Series.str.contains: Test if pattern or regex is contained within a string of a Series or Index. Examples -------- >>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]}, ... index=['falcon', 'dog']) >>> df num_legs num_wings falcon 2 2 dog 4 0 When ``values`` is a list check whether every value in the DataFrame is present in the list (which animals have 0 or 2 legs or wings) >>> df.isin([0, 2]) num_legs num_wings falcon True True dog False True When ``values`` is a dict, we can pass values to check for each column separately: >>> df.isin({'num_wings': [0, 3]}) num_legs num_wings falcon False False dog False True When ``values`` is a Series or DataFrame the index and column must match. Note that 'falcon' does not match based on the number of legs in df2. >>> other = pd.DataFrame({'num_legs': [8, 2], 'num_wings': [0, 2]}, ... index=['spider', 'falcon']) >>> df.isin(other) num_legs num_wings falcon True True dog False False """ if isinstance(values, dict): from pandas.core.reshape.concat import concat values = collections.defaultdict(list, values) return concat((self.iloc[:, [i]].isin(values[col]) for i, col in enumerate(self.columns)), axis=1) elif isinstance(values, Series): if not values.index.is_unique: raise ValueError("cannot compute isin with " "a duplicate axis.") return self.eq(values.reindex_like(self), axis='index') elif isinstance(values, DataFrame): if not (values.columns.is_unique and values.index.is_unique): raise ValueError("cannot compute isin with " "a duplicate axis.") return self.eq(values.reindex_like(self)) else: if not is_list_like(values): raise TypeError("only list-like or dict-like objects are " "allowed to be passed to DataFrame.isin(), " "you passed a " "{0!r}".format(type(values).__name__)) return DataFrame( algorithms.isin(self.values.ravel(), values).reshape(self.shape), self.index, self.columns)
def isin(self, values): """ Whether each element in the DataFrame is contained in values. Parameters ---------- values : iterable, Series, DataFrame or dict The result will only be true at a location if all the labels match. If `values` is a Series, that's the index. If `values` is a dict, the keys must be the column names, which must match. If `values` is a DataFrame, then both the index and column labels must match. Returns ------- DataFrame DataFrame of booleans showing whether each element in the DataFrame is contained in values. See Also -------- DataFrame.eq: Equality test for DataFrame. Series.isin: Equivalent method on Series. Series.str.contains: Test if pattern or regex is contained within a string of a Series or Index. Examples -------- >>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]}, ... index=['falcon', 'dog']) >>> df num_legs num_wings falcon 2 2 dog 4 0 When ``values`` is a list check whether every value in the DataFrame is present in the list (which animals have 0 or 2 legs or wings) >>> df.isin([0, 2]) num_legs num_wings falcon True True dog False True When ``values`` is a dict, we can pass values to check for each column separately: >>> df.isin({'num_wings': [0, 3]}) num_legs num_wings falcon False False dog False True When ``values`` is a Series or DataFrame the index and column must match. Note that 'falcon' does not match based on the number of legs in df2. >>> other = pd.DataFrame({'num_legs': [8, 2], 'num_wings': [0, 2]}, ... index=['spider', 'falcon']) >>> df.isin(other) num_legs num_wings falcon True True dog False False """ if isinstance(values, dict): from pandas.core.reshape.concat import concat values = collections.defaultdict(list, values) return concat((self.iloc[:, [i]].isin(values[col]) for i, col in enumerate(self.columns)), axis=1) elif isinstance(values, Series): if not values.index.is_unique: raise ValueError("cannot compute isin with " "a duplicate axis.") return self.eq(values.reindex_like(self), axis='index') elif isinstance(values, DataFrame): if not (values.columns.is_unique and values.index.is_unique): raise ValueError("cannot compute isin with " "a duplicate axis.") return self.eq(values.reindex_like(self)) else: if not is_list_like(values): raise TypeError("only list-like or dict-like objects are " "allowed to be passed to DataFrame.isin(), " "you passed a " "{0!r}".format(type(values).__name__)) return DataFrame( algorithms.isin(self.values.ravel(), values).reshape(self.shape), self.index, self.columns)
[ "Whether", "each", "element", "in", "the", "DataFrame", "is", "contained", "in", "values", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L7939-L8026
[ "def", "isin", "(", "self", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "dict", ")", ":", "from", "pandas", ".", "core", ".", "reshape", ".", "concat", "import", "concat", "values", "=", "collections", ".", "defaultdict", "(", "list", ",", "values", ")", "return", "concat", "(", "(", "self", ".", "iloc", "[", ":", ",", "[", "i", "]", "]", ".", "isin", "(", "values", "[", "col", "]", ")", "for", "i", ",", "col", "in", "enumerate", "(", "self", ".", "columns", ")", ")", ",", "axis", "=", "1", ")", "elif", "isinstance", "(", "values", ",", "Series", ")", ":", "if", "not", "values", ".", "index", ".", "is_unique", ":", "raise", "ValueError", "(", "\"cannot compute isin with \"", "\"a duplicate axis.\"", ")", "return", "self", ".", "eq", "(", "values", ".", "reindex_like", "(", "self", ")", ",", "axis", "=", "'index'", ")", "elif", "isinstance", "(", "values", ",", "DataFrame", ")", ":", "if", "not", "(", "values", ".", "columns", ".", "is_unique", "and", "values", ".", "index", ".", "is_unique", ")", ":", "raise", "ValueError", "(", "\"cannot compute isin with \"", "\"a duplicate axis.\"", ")", "return", "self", ".", "eq", "(", "values", ".", "reindex_like", "(", "self", ")", ")", "else", ":", "if", "not", "is_list_like", "(", "values", ")", ":", "raise", "TypeError", "(", "\"only list-like or dict-like objects are \"", "\"allowed to be passed to DataFrame.isin(), \"", "\"you passed a \"", "\"{0!r}\"", ".", "format", "(", "type", "(", "values", ")", ".", "__name__", ")", ")", "return", "DataFrame", "(", "algorithms", ".", "isin", "(", "self", ".", "values", ".", "ravel", "(", ")", ",", "values", ")", ".", "reshape", "(", "self", ".", "shape", ")", ",", "self", ".", "index", ",", "self", ".", "columns", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
integer_array
Infer and return an integer array of the values. Parameters ---------- values : 1D list-like dtype : dtype, optional dtype to coerce copy : boolean, default False Returns ------- IntegerArray Raises ------ TypeError if incompatible types
pandas/core/arrays/integer.py
def integer_array(values, dtype=None, copy=False): """ Infer and return an integer array of the values. Parameters ---------- values : 1D list-like dtype : dtype, optional dtype to coerce copy : boolean, default False Returns ------- IntegerArray Raises ------ TypeError if incompatible types """ values, mask = coerce_to_array(values, dtype=dtype, copy=copy) return IntegerArray(values, mask)
def integer_array(values, dtype=None, copy=False): """ Infer and return an integer array of the values. Parameters ---------- values : 1D list-like dtype : dtype, optional dtype to coerce copy : boolean, default False Returns ------- IntegerArray Raises ------ TypeError if incompatible types """ values, mask = coerce_to_array(values, dtype=dtype, copy=copy) return IntegerArray(values, mask)
[ "Infer", "and", "return", "an", "integer", "array", "of", "the", "values", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L92-L112
[ "def", "integer_array", "(", "values", ",", "dtype", "=", "None", ",", "copy", "=", "False", ")", ":", "values", ",", "mask", "=", "coerce_to_array", "(", "values", ",", "dtype", "=", "dtype", ",", "copy", "=", "copy", ")", "return", "IntegerArray", "(", "values", ",", "mask", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
safe_cast
Safely cast the values to the dtype if they are equivalent, meaning floats must be equivalent to the ints.
pandas/core/arrays/integer.py
def safe_cast(values, dtype, copy): """ Safely cast the values to the dtype if they are equivalent, meaning floats must be equivalent to the ints. """ try: return values.astype(dtype, casting='safe', copy=copy) except TypeError: casted = values.astype(dtype, copy=copy) if (casted == values).all(): return casted raise TypeError("cannot safely cast non-equivalent {} to {}".format( values.dtype, np.dtype(dtype)))
def safe_cast(values, dtype, copy): """ Safely cast the values to the dtype if they are equivalent, meaning floats must be equivalent to the ints. """ try: return values.astype(dtype, casting='safe', copy=copy) except TypeError: casted = values.astype(dtype, copy=copy) if (casted == values).all(): return casted raise TypeError("cannot safely cast non-equivalent {} to {}".format( values.dtype, np.dtype(dtype)))
[ "Safely", "cast", "the", "values", "to", "the", "dtype", "if", "they", "are", "equivalent", "meaning", "floats", "must", "be", "equivalent", "to", "the", "ints", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L115-L132
[ "def", "safe_cast", "(", "values", ",", "dtype", ",", "copy", ")", ":", "try", ":", "return", "values", ".", "astype", "(", "dtype", ",", "casting", "=", "'safe'", ",", "copy", "=", "copy", ")", "except", "TypeError", ":", "casted", "=", "values", ".", "astype", "(", "dtype", ",", "copy", "=", "copy", ")", "if", "(", "casted", "==", "values", ")", ".", "all", "(", ")", ":", "return", "casted", "raise", "TypeError", "(", "\"cannot safely cast non-equivalent {} to {}\"", ".", "format", "(", "values", ".", "dtype", ",", "np", ".", "dtype", "(", "dtype", ")", ")", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
coerce_to_array
Coerce the input values array to numpy arrays with a mask Parameters ---------- values : 1D list-like dtype : integer dtype mask : boolean 1D array, optional copy : boolean, default False if True, copy the input Returns ------- tuple of (values, mask)
pandas/core/arrays/integer.py
def coerce_to_array(values, dtype, mask=None, copy=False): """ Coerce the input values array to numpy arrays with a mask Parameters ---------- values : 1D list-like dtype : integer dtype mask : boolean 1D array, optional copy : boolean, default False if True, copy the input Returns ------- tuple of (values, mask) """ # if values is integer numpy array, preserve it's dtype if dtype is None and hasattr(values, 'dtype'): if is_integer_dtype(values.dtype): dtype = values.dtype if dtype is not None: if (isinstance(dtype, str) and (dtype.startswith("Int") or dtype.startswith("UInt"))): # Avoid DeprecationWarning from NumPy about np.dtype("Int64") # https://github.com/numpy/numpy/pull/7476 dtype = dtype.lower() if not issubclass(type(dtype), _IntegerDtype): try: dtype = _dtypes[str(np.dtype(dtype))] except KeyError: raise ValueError("invalid dtype specified {}".format(dtype)) if isinstance(values, IntegerArray): values, mask = values._data, values._mask if dtype is not None: values = values.astype(dtype.numpy_dtype, copy=False) if copy: values = values.copy() mask = mask.copy() return values, mask values = np.array(values, copy=copy) if is_object_dtype(values): inferred_type = lib.infer_dtype(values, skipna=True) if inferred_type == 'empty': values = np.empty(len(values)) values.fill(np.nan) elif inferred_type not in ['floating', 'integer', 'mixed-integer', 'mixed-integer-float']: raise TypeError("{} cannot be converted to an IntegerDtype".format( values.dtype)) elif not (is_integer_dtype(values) or is_float_dtype(values)): raise TypeError("{} cannot be converted to an IntegerDtype".format( values.dtype)) if mask is None: mask = isna(values) else: assert len(mask) == len(values) if not values.ndim == 1: raise TypeError("values must be a 1D list-like") if not mask.ndim == 1: raise TypeError("mask must be a 1D list-like") # infer dtype if needed if dtype is None: dtype = np.dtype('int64') else: dtype = dtype.type # if we are float, let's make sure that we can # safely cast # we copy as need to coerce here if mask.any(): values = values.copy() values[mask] = 1 values = safe_cast(values, dtype, copy=False) else: values = safe_cast(values, dtype, copy=False) return values, mask
def coerce_to_array(values, dtype, mask=None, copy=False): """ Coerce the input values array to numpy arrays with a mask Parameters ---------- values : 1D list-like dtype : integer dtype mask : boolean 1D array, optional copy : boolean, default False if True, copy the input Returns ------- tuple of (values, mask) """ # if values is integer numpy array, preserve it's dtype if dtype is None and hasattr(values, 'dtype'): if is_integer_dtype(values.dtype): dtype = values.dtype if dtype is not None: if (isinstance(dtype, str) and (dtype.startswith("Int") or dtype.startswith("UInt"))): # Avoid DeprecationWarning from NumPy about np.dtype("Int64") # https://github.com/numpy/numpy/pull/7476 dtype = dtype.lower() if not issubclass(type(dtype), _IntegerDtype): try: dtype = _dtypes[str(np.dtype(dtype))] except KeyError: raise ValueError("invalid dtype specified {}".format(dtype)) if isinstance(values, IntegerArray): values, mask = values._data, values._mask if dtype is not None: values = values.astype(dtype.numpy_dtype, copy=False) if copy: values = values.copy() mask = mask.copy() return values, mask values = np.array(values, copy=copy) if is_object_dtype(values): inferred_type = lib.infer_dtype(values, skipna=True) if inferred_type == 'empty': values = np.empty(len(values)) values.fill(np.nan) elif inferred_type not in ['floating', 'integer', 'mixed-integer', 'mixed-integer-float']: raise TypeError("{} cannot be converted to an IntegerDtype".format( values.dtype)) elif not (is_integer_dtype(values) or is_float_dtype(values)): raise TypeError("{} cannot be converted to an IntegerDtype".format( values.dtype)) if mask is None: mask = isna(values) else: assert len(mask) == len(values) if not values.ndim == 1: raise TypeError("values must be a 1D list-like") if not mask.ndim == 1: raise TypeError("mask must be a 1D list-like") # infer dtype if needed if dtype is None: dtype = np.dtype('int64') else: dtype = dtype.type # if we are float, let's make sure that we can # safely cast # we copy as need to coerce here if mask.any(): values = values.copy() values[mask] = 1 values = safe_cast(values, dtype, copy=False) else: values = safe_cast(values, dtype, copy=False) return values, mask
[ "Coerce", "the", "input", "values", "array", "to", "numpy", "arrays", "with", "a", "mask" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L135-L221
[ "def", "coerce_to_array", "(", "values", ",", "dtype", ",", "mask", "=", "None", ",", "copy", "=", "False", ")", ":", "# if values is integer numpy array, preserve it's dtype", "if", "dtype", "is", "None", "and", "hasattr", "(", "values", ",", "'dtype'", ")", ":", "if", "is_integer_dtype", "(", "values", ".", "dtype", ")", ":", "dtype", "=", "values", ".", "dtype", "if", "dtype", "is", "not", "None", ":", "if", "(", "isinstance", "(", "dtype", ",", "str", ")", "and", "(", "dtype", ".", "startswith", "(", "\"Int\"", ")", "or", "dtype", ".", "startswith", "(", "\"UInt\"", ")", ")", ")", ":", "# Avoid DeprecationWarning from NumPy about np.dtype(\"Int64\")", "# https://github.com/numpy/numpy/pull/7476", "dtype", "=", "dtype", ".", "lower", "(", ")", "if", "not", "issubclass", "(", "type", "(", "dtype", ")", ",", "_IntegerDtype", ")", ":", "try", ":", "dtype", "=", "_dtypes", "[", "str", "(", "np", ".", "dtype", "(", "dtype", ")", ")", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"invalid dtype specified {}\"", ".", "format", "(", "dtype", ")", ")", "if", "isinstance", "(", "values", ",", "IntegerArray", ")", ":", "values", ",", "mask", "=", "values", ".", "_data", ",", "values", ".", "_mask", "if", "dtype", "is", "not", "None", ":", "values", "=", "values", ".", "astype", "(", "dtype", ".", "numpy_dtype", ",", "copy", "=", "False", ")", "if", "copy", ":", "values", "=", "values", ".", "copy", "(", ")", "mask", "=", "mask", ".", "copy", "(", ")", "return", "values", ",", "mask", "values", "=", "np", ".", "array", "(", "values", ",", "copy", "=", "copy", ")", "if", "is_object_dtype", "(", "values", ")", ":", "inferred_type", "=", "lib", ".", "infer_dtype", "(", "values", ",", "skipna", "=", "True", ")", "if", "inferred_type", "==", "'empty'", ":", "values", "=", "np", ".", "empty", "(", "len", "(", "values", ")", ")", "values", ".", "fill", "(", "np", ".", "nan", ")", "elif", "inferred_type", "not", "in", "[", "'floating'", ",", "'integer'", ",", "'mixed-integer'", ",", "'mixed-integer-float'", "]", ":", "raise", "TypeError", "(", "\"{} cannot be converted to an IntegerDtype\"", ".", "format", "(", "values", ".", "dtype", ")", ")", "elif", "not", "(", "is_integer_dtype", "(", "values", ")", "or", "is_float_dtype", "(", "values", ")", ")", ":", "raise", "TypeError", "(", "\"{} cannot be converted to an IntegerDtype\"", ".", "format", "(", "values", ".", "dtype", ")", ")", "if", "mask", "is", "None", ":", "mask", "=", "isna", "(", "values", ")", "else", ":", "assert", "len", "(", "mask", ")", "==", "len", "(", "values", ")", "if", "not", "values", ".", "ndim", "==", "1", ":", "raise", "TypeError", "(", "\"values must be a 1D list-like\"", ")", "if", "not", "mask", ".", "ndim", "==", "1", ":", "raise", "TypeError", "(", "\"mask must be a 1D list-like\"", ")", "# infer dtype if needed", "if", "dtype", "is", "None", ":", "dtype", "=", "np", ".", "dtype", "(", "'int64'", ")", "else", ":", "dtype", "=", "dtype", ".", "type", "# if we are float, let's make sure that we can", "# safely cast", "# we copy as need to coerce here", "if", "mask", ".", "any", "(", ")", ":", "values", "=", "values", ".", "copy", "(", ")", "values", "[", "mask", "]", "=", "1", "values", "=", "safe_cast", "(", "values", ",", "dtype", ",", "copy", "=", "False", ")", "else", ":", "values", "=", "safe_cast", "(", "values", ",", "dtype", ",", "copy", "=", "False", ")", "return", "values", ",", "mask" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_IntegerDtype.construct_from_string
Construction from a string, raise a TypeError if not possible
pandas/core/arrays/integer.py
def construct_from_string(cls, string): """ Construction from a string, raise a TypeError if not possible """ if string == cls.name: return cls() raise TypeError("Cannot construct a '{}' from " "'{}'".format(cls, string))
def construct_from_string(cls, string): """ Construction from a string, raise a TypeError if not possible """ if string == cls.name: return cls() raise TypeError("Cannot construct a '{}' from " "'{}'".format(cls, string))
[ "Construction", "from", "a", "string", "raise", "a", "TypeError", "if", "not", "possible" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L81-L89
[ "def", "construct_from_string", "(", "cls", ",", "string", ")", ":", "if", "string", "==", "cls", ".", "name", ":", "return", "cls", "(", ")", "raise", "TypeError", "(", "\"Cannot construct a '{}' from \"", "\"'{}'\"", ".", "format", "(", "cls", ",", "string", ")", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
IntegerArray._coerce_to_ndarray
coerce to an ndarary of object dtype
pandas/core/arrays/integer.py
def _coerce_to_ndarray(self): """ coerce to an ndarary of object dtype """ # TODO(jreback) make this better data = self._data.astype(object) data[self._mask] = self._na_value return data
def _coerce_to_ndarray(self): """ coerce to an ndarary of object dtype """ # TODO(jreback) make this better data = self._data.astype(object) data[self._mask] = self._na_value return data
[ "coerce", "to", "an", "ndarary", "of", "object", "dtype" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L328-L336
[ "def", "_coerce_to_ndarray", "(", "self", ")", ":", "# TODO(jreback) make this better", "data", "=", "self", ".", "_data", ".", "astype", "(", "object", ")", "data", "[", "self", ".", "_mask", "]", "=", "self", ".", "_na_value", "return", "data" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
IntegerArray.astype
Cast to a NumPy array or IntegerArray with 'dtype'. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. copy : bool, default True Whether to copy the data, even if not necessary. If False, a copy is made only if the old dtype does not match the new dtype. Returns ------- array : ndarray or IntegerArray NumPy ndarray or IntergerArray with 'dtype' for its dtype. Raises ------ TypeError if incompatible type with an IntegerDtype, equivalent of same_kind casting
pandas/core/arrays/integer.py
def astype(self, dtype, copy=True): """ Cast to a NumPy array or IntegerArray with 'dtype'. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. copy : bool, default True Whether to copy the data, even if not necessary. If False, a copy is made only if the old dtype does not match the new dtype. Returns ------- array : ndarray or IntegerArray NumPy ndarray or IntergerArray with 'dtype' for its dtype. Raises ------ TypeError if incompatible type with an IntegerDtype, equivalent of same_kind casting """ # if we are astyping to an existing IntegerDtype we can fastpath if isinstance(dtype, _IntegerDtype): result = self._data.astype(dtype.numpy_dtype, copy=False) return type(self)(result, mask=self._mask, copy=False) # coerce data = self._coerce_to_ndarray() return astype_nansafe(data, dtype, copy=None)
def astype(self, dtype, copy=True): """ Cast to a NumPy array or IntegerArray with 'dtype'. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. copy : bool, default True Whether to copy the data, even if not necessary. If False, a copy is made only if the old dtype does not match the new dtype. Returns ------- array : ndarray or IntegerArray NumPy ndarray or IntergerArray with 'dtype' for its dtype. Raises ------ TypeError if incompatible type with an IntegerDtype, equivalent of same_kind casting """ # if we are astyping to an existing IntegerDtype we can fastpath if isinstance(dtype, _IntegerDtype): result = self._data.astype(dtype.numpy_dtype, copy=False) return type(self)(result, mask=self._mask, copy=False) # coerce data = self._coerce_to_ndarray() return astype_nansafe(data, dtype, copy=None)
[ "Cast", "to", "a", "NumPy", "array", "or", "IntegerArray", "with", "dtype", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L420-L452
[ "def", "astype", "(", "self", ",", "dtype", ",", "copy", "=", "True", ")", ":", "# if we are astyping to an existing IntegerDtype we can fastpath", "if", "isinstance", "(", "dtype", ",", "_IntegerDtype", ")", ":", "result", "=", "self", ".", "_data", ".", "astype", "(", "dtype", ".", "numpy_dtype", ",", "copy", "=", "False", ")", "return", "type", "(", "self", ")", "(", "result", ",", "mask", "=", "self", ".", "_mask", ",", "copy", "=", "False", ")", "# coerce", "data", "=", "self", ".", "_coerce_to_ndarray", "(", ")", "return", "astype_nansafe", "(", "data", ",", "dtype", ",", "copy", "=", "None", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
IntegerArray.value_counts
Returns a Series containing counts of each category. Every category will have an entry, even those with a count of 0. Parameters ---------- dropna : boolean, default True Don't include counts of NaN. Returns ------- counts : Series See Also -------- Series.value_counts
pandas/core/arrays/integer.py
def value_counts(self, dropna=True): """ Returns a Series containing counts of each category. Every category will have an entry, even those with a count of 0. Parameters ---------- dropna : boolean, default True Don't include counts of NaN. Returns ------- counts : Series See Also -------- Series.value_counts """ from pandas import Index, Series # compute counts on the data with no nans data = self._data[~self._mask] value_counts = Index(data).value_counts() array = value_counts.values # TODO(extension) # if we have allow Index to hold an ExtensionArray # this is easier index = value_counts.index.astype(object) # if we want nans, count the mask if not dropna: # TODO(extension) # appending to an Index *always* infers # w/o passing the dtype array = np.append(array, [self._mask.sum()]) index = Index(np.concatenate( [index.values, np.array([np.nan], dtype=object)]), dtype=object) return Series(array, index=index)
def value_counts(self, dropna=True): """ Returns a Series containing counts of each category. Every category will have an entry, even those with a count of 0. Parameters ---------- dropna : boolean, default True Don't include counts of NaN. Returns ------- counts : Series See Also -------- Series.value_counts """ from pandas import Index, Series # compute counts on the data with no nans data = self._data[~self._mask] value_counts = Index(data).value_counts() array = value_counts.values # TODO(extension) # if we have allow Index to hold an ExtensionArray # this is easier index = value_counts.index.astype(object) # if we want nans, count the mask if not dropna: # TODO(extension) # appending to an Index *always* infers # w/o passing the dtype array = np.append(array, [self._mask.sum()]) index = Index(np.concatenate( [index.values, np.array([np.nan], dtype=object)]), dtype=object) return Series(array, index=index)
[ "Returns", "a", "Series", "containing", "counts", "of", "each", "category", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L465-L509
[ "def", "value_counts", "(", "self", ",", "dropna", "=", "True", ")", ":", "from", "pandas", "import", "Index", ",", "Series", "# compute counts on the data with no nans", "data", "=", "self", ".", "_data", "[", "~", "self", ".", "_mask", "]", "value_counts", "=", "Index", "(", "data", ")", ".", "value_counts", "(", ")", "array", "=", "value_counts", ".", "values", "# TODO(extension)", "# if we have allow Index to hold an ExtensionArray", "# this is easier", "index", "=", "value_counts", ".", "index", ".", "astype", "(", "object", ")", "# if we want nans, count the mask", "if", "not", "dropna", ":", "# TODO(extension)", "# appending to an Index *always* infers", "# w/o passing the dtype", "array", "=", "np", ".", "append", "(", "array", ",", "[", "self", ".", "_mask", ".", "sum", "(", ")", "]", ")", "index", "=", "Index", "(", "np", ".", "concatenate", "(", "[", "index", ".", "values", ",", "np", ".", "array", "(", "[", "np", ".", "nan", "]", ",", "dtype", "=", "object", ")", "]", ")", ",", "dtype", "=", "object", ")", "return", "Series", "(", "array", ",", "index", "=", "index", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
IntegerArray._values_for_argsort
Return values for sorting. Returns ------- ndarray The transformed values should maintain the ordering between values within the array. See Also -------- ExtensionArray.argsort
pandas/core/arrays/integer.py
def _values_for_argsort(self) -> np.ndarray: """Return values for sorting. Returns ------- ndarray The transformed values should maintain the ordering between values within the array. See Also -------- ExtensionArray.argsort """ data = self._data.copy() data[self._mask] = data.min() - 1 return data
def _values_for_argsort(self) -> np.ndarray: """Return values for sorting. Returns ------- ndarray The transformed values should maintain the ordering between values within the array. See Also -------- ExtensionArray.argsort """ data = self._data.copy() data[self._mask] = data.min() - 1 return data
[ "Return", "values", "for", "sorting", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L511-L526
[ "def", "_values_for_argsort", "(", "self", ")", "->", "np", ".", "ndarray", ":", "data", "=", "self", ".", "_data", ".", "copy", "(", ")", "data", "[", "self", ".", "_mask", "]", "=", "data", ".", "min", "(", ")", "-", "1", "return", "data" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
IntegerArray._maybe_mask_result
Parameters ---------- result : array-like mask : array-like bool other : scalar or array-like op_name : str
pandas/core/arrays/integer.py
def _maybe_mask_result(self, result, mask, other, op_name): """ Parameters ---------- result : array-like mask : array-like bool other : scalar or array-like op_name : str """ # may need to fill infs # and mask wraparound if is_float_dtype(result): mask |= (result == np.inf) | (result == -np.inf) # if we have a float operand we are by-definition # a float result # or our op is a divide if ((is_float_dtype(other) or is_float(other)) or (op_name in ['rtruediv', 'truediv', 'rdiv', 'div'])): result[mask] = np.nan return result return type(self)(result, mask, copy=False)
def _maybe_mask_result(self, result, mask, other, op_name): """ Parameters ---------- result : array-like mask : array-like bool other : scalar or array-like op_name : str """ # may need to fill infs # and mask wraparound if is_float_dtype(result): mask |= (result == np.inf) | (result == -np.inf) # if we have a float operand we are by-definition # a float result # or our op is a divide if ((is_float_dtype(other) or is_float(other)) or (op_name in ['rtruediv', 'truediv', 'rdiv', 'div'])): result[mask] = np.nan return result return type(self)(result, mask, copy=False)
[ "Parameters", "----------", "result", ":", "array", "-", "like", "mask", ":", "array", "-", "like", "bool", "other", ":", "scalar", "or", "array", "-", "like", "op_name", ":", "str" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/integer.py#L593-L616
[ "def", "_maybe_mask_result", "(", "self", ",", "result", ",", "mask", ",", "other", ",", "op_name", ")", ":", "# may need to fill infs", "# and mask wraparound", "if", "is_float_dtype", "(", "result", ")", ":", "mask", "|=", "(", "result", "==", "np", ".", "inf", ")", "|", "(", "result", "==", "-", "np", ".", "inf", ")", "# if we have a float operand we are by-definition", "# a float result", "# or our op is a divide", "if", "(", "(", "is_float_dtype", "(", "other", ")", "or", "is_float", "(", "other", ")", ")", "or", "(", "op_name", "in", "[", "'rtruediv'", ",", "'truediv'", ",", "'rdiv'", ",", "'div'", "]", ")", ")", ":", "result", "[", "mask", "]", "=", "np", ".", "nan", "return", "result", "return", "type", "(", "self", ")", "(", "result", ",", "mask", ",", "copy", "=", "False", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
length_of_indexer
return the length of a single non-tuple indexer which could be a slice
pandas/core/indexing.py
def length_of_indexer(indexer, target=None): """ return the length of a single non-tuple indexer which could be a slice """ if target is not None and isinstance(indexer, slice): target_len = len(target) start = indexer.start stop = indexer.stop step = indexer.step if start is None: start = 0 elif start < 0: start += target_len if stop is None or stop > target_len: stop = target_len elif stop < 0: stop += target_len if step is None: step = 1 elif step < 0: step = -step return (stop - start + step - 1) // step elif isinstance(indexer, (ABCSeries, Index, np.ndarray, list)): return len(indexer) elif not is_list_like_indexer(indexer): return 1 raise AssertionError("cannot find the length of the indexer")
def length_of_indexer(indexer, target=None): """ return the length of a single non-tuple indexer which could be a slice """ if target is not None and isinstance(indexer, slice): target_len = len(target) start = indexer.start stop = indexer.stop step = indexer.step if start is None: start = 0 elif start < 0: start += target_len if stop is None or stop > target_len: stop = target_len elif stop < 0: stop += target_len if step is None: step = 1 elif step < 0: step = -step return (stop - start + step - 1) // step elif isinstance(indexer, (ABCSeries, Index, np.ndarray, list)): return len(indexer) elif not is_list_like_indexer(indexer): return 1 raise AssertionError("cannot find the length of the indexer")
[ "return", "the", "length", "of", "a", "single", "non", "-", "tuple", "indexer", "which", "could", "be", "a", "slice" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2431-L2457
[ "def", "length_of_indexer", "(", "indexer", ",", "target", "=", "None", ")", ":", "if", "target", "is", "not", "None", "and", "isinstance", "(", "indexer", ",", "slice", ")", ":", "target_len", "=", "len", "(", "target", ")", "start", "=", "indexer", ".", "start", "stop", "=", "indexer", ".", "stop", "step", "=", "indexer", ".", "step", "if", "start", "is", "None", ":", "start", "=", "0", "elif", "start", "<", "0", ":", "start", "+=", "target_len", "if", "stop", "is", "None", "or", "stop", ">", "target_len", ":", "stop", "=", "target_len", "elif", "stop", "<", "0", ":", "stop", "+=", "target_len", "if", "step", "is", "None", ":", "step", "=", "1", "elif", "step", "<", "0", ":", "step", "=", "-", "step", "return", "(", "stop", "-", "start", "+", "step", "-", "1", ")", "//", "step", "elif", "isinstance", "(", "indexer", ",", "(", "ABCSeries", ",", "Index", ",", "np", ".", "ndarray", ",", "list", ")", ")", ":", "return", "len", "(", "indexer", ")", "elif", "not", "is_list_like_indexer", "(", "indexer", ")", ":", "return", "1", "raise", "AssertionError", "(", "\"cannot find the length of the indexer\"", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
convert_to_index_sliceable
if we are index sliceable, then return my slicer, otherwise return None
pandas/core/indexing.py
def convert_to_index_sliceable(obj, key): """ if we are index sliceable, then return my slicer, otherwise return None """ idx = obj.index if isinstance(key, slice): return idx._convert_slice_indexer(key, kind='getitem') elif isinstance(key, str): # we are an actual column if obj._data.items.contains(key): return None # We might have a datetimelike string that we can translate to a # slice here via partial string indexing if idx.is_all_dates: try: return idx._get_string_slice(key) except (KeyError, ValueError, NotImplementedError): return None return None
def convert_to_index_sliceable(obj, key): """ if we are index sliceable, then return my slicer, otherwise return None """ idx = obj.index if isinstance(key, slice): return idx._convert_slice_indexer(key, kind='getitem') elif isinstance(key, str): # we are an actual column if obj._data.items.contains(key): return None # We might have a datetimelike string that we can translate to a # slice here via partial string indexing if idx.is_all_dates: try: return idx._get_string_slice(key) except (KeyError, ValueError, NotImplementedError): return None return None
[ "if", "we", "are", "index", "sliceable", "then", "return", "my", "slicer", "otherwise", "return", "None" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2460-L2482
[ "def", "convert_to_index_sliceable", "(", "obj", ",", "key", ")", ":", "idx", "=", "obj", ".", "index", "if", "isinstance", "(", "key", ",", "slice", ")", ":", "return", "idx", ".", "_convert_slice_indexer", "(", "key", ",", "kind", "=", "'getitem'", ")", "elif", "isinstance", "(", "key", ",", "str", ")", ":", "# we are an actual column", "if", "obj", ".", "_data", ".", "items", ".", "contains", "(", "key", ")", ":", "return", "None", "# We might have a datetimelike string that we can translate to a", "# slice here via partial string indexing", "if", "idx", ".", "is_all_dates", ":", "try", ":", "return", "idx", ".", "_get_string_slice", "(", "key", ")", "except", "(", "KeyError", ",", "ValueError", ",", "NotImplementedError", ")", ":", "return", "None", "return", "None" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
check_setitem_lengths
Validate that value and indexer are the same length. An special-case is allowed for when the indexer is a boolean array and the number of true values equals the length of ``value``. In this case, no exception is raised. Parameters ---------- indexer : sequence The key for the setitem value : array-like The value for the setitem values : array-like The values being set into Returns ------- None Raises ------ ValueError When the indexer is an ndarray or list and the lengths don't match.
pandas/core/indexing.py
def check_setitem_lengths(indexer, value, values): """ Validate that value and indexer are the same length. An special-case is allowed for when the indexer is a boolean array and the number of true values equals the length of ``value``. In this case, no exception is raised. Parameters ---------- indexer : sequence The key for the setitem value : array-like The value for the setitem values : array-like The values being set into Returns ------- None Raises ------ ValueError When the indexer is an ndarray or list and the lengths don't match. """ # boolean with truth values == len of the value is ok too if isinstance(indexer, (np.ndarray, list)): if is_list_like(value) and len(indexer) != len(value): if not (isinstance(indexer, np.ndarray) and indexer.dtype == np.bool_ and len(indexer[indexer]) == len(value)): raise ValueError("cannot set using a list-like indexer " "with a different length than the value") # slice elif isinstance(indexer, slice): if is_list_like(value) and len(values): if len(value) != length_of_indexer(indexer, values): raise ValueError("cannot set using a slice indexer with a " "different length than the value")
def check_setitem_lengths(indexer, value, values): """ Validate that value and indexer are the same length. An special-case is allowed for when the indexer is a boolean array and the number of true values equals the length of ``value``. In this case, no exception is raised. Parameters ---------- indexer : sequence The key for the setitem value : array-like The value for the setitem values : array-like The values being set into Returns ------- None Raises ------ ValueError When the indexer is an ndarray or list and the lengths don't match. """ # boolean with truth values == len of the value is ok too if isinstance(indexer, (np.ndarray, list)): if is_list_like(value) and len(indexer) != len(value): if not (isinstance(indexer, np.ndarray) and indexer.dtype == np.bool_ and len(indexer[indexer]) == len(value)): raise ValueError("cannot set using a list-like indexer " "with a different length than the value") # slice elif isinstance(indexer, slice): if is_list_like(value) and len(values): if len(value) != length_of_indexer(indexer, values): raise ValueError("cannot set using a slice indexer with a " "different length than the value")
[ "Validate", "that", "value", "and", "indexer", "are", "the", "same", "length", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2511-L2552
[ "def", "check_setitem_lengths", "(", "indexer", ",", "value", ",", "values", ")", ":", "# boolean with truth values == len of the value is ok too", "if", "isinstance", "(", "indexer", ",", "(", "np", ".", "ndarray", ",", "list", ")", ")", ":", "if", "is_list_like", "(", "value", ")", "and", "len", "(", "indexer", ")", "!=", "len", "(", "value", ")", ":", "if", "not", "(", "isinstance", "(", "indexer", ",", "np", ".", "ndarray", ")", "and", "indexer", ".", "dtype", "==", "np", ".", "bool_", "and", "len", "(", "indexer", "[", "indexer", "]", ")", "==", "len", "(", "value", ")", ")", ":", "raise", "ValueError", "(", "\"cannot set using a list-like indexer \"", "\"with a different length than the value\"", ")", "# slice", "elif", "isinstance", "(", "indexer", ",", "slice", ")", ":", "if", "is_list_like", "(", "value", ")", "and", "len", "(", "values", ")", ":", "if", "len", "(", "value", ")", "!=", "length_of_indexer", "(", "indexer", ",", "values", ")", ":", "raise", "ValueError", "(", "\"cannot set using a slice indexer with a \"", "\"different length than the value\"", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
convert_missing_indexer
reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted
pandas/core/indexing.py
def convert_missing_indexer(indexer): """ reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted """ if isinstance(indexer, dict): # a missing key (but not a tuple indexer) indexer = indexer['key'] if isinstance(indexer, bool): raise KeyError("cannot use a single bool to index into setitem") return indexer, True return indexer, False
def convert_missing_indexer(indexer): """ reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted """ if isinstance(indexer, dict): # a missing key (but not a tuple indexer) indexer = indexer['key'] if isinstance(indexer, bool): raise KeyError("cannot use a single bool to index into setitem") return indexer, True return indexer, False
[ "reverse", "convert", "a", "missing", "indexer", "which", "is", "a", "dict", "return", "the", "scalar", "indexer", "and", "a", "boolean", "indicating", "if", "we", "converted" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2555-L2570
[ "def", "convert_missing_indexer", "(", "indexer", ")", ":", "if", "isinstance", "(", "indexer", ",", "dict", ")", ":", "# a missing key (but not a tuple indexer)", "indexer", "=", "indexer", "[", "'key'", "]", "if", "isinstance", "(", "indexer", ",", "bool", ")", ":", "raise", "KeyError", "(", "\"cannot use a single bool to index into setitem\"", ")", "return", "indexer", ",", "True", "return", "indexer", ",", "False" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
convert_from_missing_indexer_tuple
create a filtered indexer that doesn't have any missing indexers
pandas/core/indexing.py
def convert_from_missing_indexer_tuple(indexer, axes): """ create a filtered indexer that doesn't have any missing indexers """ def get_indexer(_i, _idx): return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else _idx) return tuple(get_indexer(_i, _idx) for _i, _idx in enumerate(indexer))
def convert_from_missing_indexer_tuple(indexer, axes): """ create a filtered indexer that doesn't have any missing indexers """ def get_indexer(_i, _idx): return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else _idx) return tuple(get_indexer(_i, _idx) for _i, _idx in enumerate(indexer))
[ "create", "a", "filtered", "indexer", "that", "doesn", "t", "have", "any", "missing", "indexers" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2573-L2582
[ "def", "convert_from_missing_indexer_tuple", "(", "indexer", ",", "axes", ")", ":", "def", "get_indexer", "(", "_i", ",", "_idx", ")", ":", "return", "(", "axes", "[", "_i", "]", ".", "get_loc", "(", "_idx", "[", "'key'", "]", ")", "if", "isinstance", "(", "_idx", ",", "dict", ")", "else", "_idx", ")", "return", "tuple", "(", "get_indexer", "(", "_i", ",", "_idx", ")", "for", "_i", ",", "_idx", "in", "enumerate", "(", "indexer", ")", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_convert_indices
Attempt to convert indices into valid, positive indices. If we have negative indices, translate to positive here. If we have indices that are out-of-bounds, raise an IndexError. Parameters ---------- indices : array-like The array of indices that we are to convert. n : int The number of elements in the array that we are indexing. Returns ------- valid_indices : array-like An array-like of positive indices that correspond to the ones that were passed in initially to this function. Raises ------ IndexError : one of the converted indices either exceeded the number of elements (specified by `n`) OR was still negative.
pandas/core/indexing.py
def maybe_convert_indices(indices, n): """ Attempt to convert indices into valid, positive indices. If we have negative indices, translate to positive here. If we have indices that are out-of-bounds, raise an IndexError. Parameters ---------- indices : array-like The array of indices that we are to convert. n : int The number of elements in the array that we are indexing. Returns ------- valid_indices : array-like An array-like of positive indices that correspond to the ones that were passed in initially to this function. Raises ------ IndexError : one of the converted indices either exceeded the number of elements (specified by `n`) OR was still negative. """ if isinstance(indices, list): indices = np.array(indices) if len(indices) == 0: # If list is empty, np.array will return float and cause indexing # errors. return np.empty(0, dtype=np.intp) mask = indices < 0 if mask.any(): indices = indices.copy() indices[mask] += n mask = (indices >= n) | (indices < 0) if mask.any(): raise IndexError("indices are out-of-bounds") return indices
def maybe_convert_indices(indices, n): """ Attempt to convert indices into valid, positive indices. If we have negative indices, translate to positive here. If we have indices that are out-of-bounds, raise an IndexError. Parameters ---------- indices : array-like The array of indices that we are to convert. n : int The number of elements in the array that we are indexing. Returns ------- valid_indices : array-like An array-like of positive indices that correspond to the ones that were passed in initially to this function. Raises ------ IndexError : one of the converted indices either exceeded the number of elements (specified by `n`) OR was still negative. """ if isinstance(indices, list): indices = np.array(indices) if len(indices) == 0: # If list is empty, np.array will return float and cause indexing # errors. return np.empty(0, dtype=np.intp) mask = indices < 0 if mask.any(): indices = indices.copy() indices[mask] += n mask = (indices >= n) | (indices < 0) if mask.any(): raise IndexError("indices are out-of-bounds") return indices
[ "Attempt", "to", "convert", "indices", "into", "valid", "positive", "indices", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2585-L2626
[ "def", "maybe_convert_indices", "(", "indices", ",", "n", ")", ":", "if", "isinstance", "(", "indices", ",", "list", ")", ":", "indices", "=", "np", ".", "array", "(", "indices", ")", "if", "len", "(", "indices", ")", "==", "0", ":", "# If list is empty, np.array will return float and cause indexing", "# errors.", "return", "np", ".", "empty", "(", "0", ",", "dtype", "=", "np", ".", "intp", ")", "mask", "=", "indices", "<", "0", "if", "mask", ".", "any", "(", ")", ":", "indices", "=", "indices", ".", "copy", "(", ")", "indices", "[", "mask", "]", "+=", "n", "mask", "=", "(", "indices", ">=", "n", ")", "|", "(", "indices", "<", "0", ")", "if", "mask", ".", "any", "(", ")", ":", "raise", "IndexError", "(", "\"indices are out-of-bounds\"", ")", "return", "indices" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
validate_indices
Perform bounds-checking for an indexer. -1 is allowed for indicating missing values. Parameters ---------- indices : ndarray n : int length of the array being indexed Raises ------ ValueError Examples -------- >>> validate_indices([1, 2], 3) # OK >>> validate_indices([1, -2], 3) ValueError >>> validate_indices([1, 2, 3], 3) IndexError >>> validate_indices([-1, -1], 0) # OK >>> validate_indices([0, 1], 0) IndexError
pandas/core/indexing.py
def validate_indices(indices, n): """ Perform bounds-checking for an indexer. -1 is allowed for indicating missing values. Parameters ---------- indices : ndarray n : int length of the array being indexed Raises ------ ValueError Examples -------- >>> validate_indices([1, 2], 3) # OK >>> validate_indices([1, -2], 3) ValueError >>> validate_indices([1, 2, 3], 3) IndexError >>> validate_indices([-1, -1], 0) # OK >>> validate_indices([0, 1], 0) IndexError """ if len(indices): min_idx = indices.min() if min_idx < -1: msg = ("'indices' contains values less than allowed ({} < {})" .format(min_idx, -1)) raise ValueError(msg) max_idx = indices.max() if max_idx >= n: raise IndexError("indices are out-of-bounds")
def validate_indices(indices, n): """ Perform bounds-checking for an indexer. -1 is allowed for indicating missing values. Parameters ---------- indices : ndarray n : int length of the array being indexed Raises ------ ValueError Examples -------- >>> validate_indices([1, 2], 3) # OK >>> validate_indices([1, -2], 3) ValueError >>> validate_indices([1, 2, 3], 3) IndexError >>> validate_indices([-1, -1], 0) # OK >>> validate_indices([0, 1], 0) IndexError """ if len(indices): min_idx = indices.min() if min_idx < -1: msg = ("'indices' contains values less than allowed ({} < {})" .format(min_idx, -1)) raise ValueError(msg) max_idx = indices.max() if max_idx >= n: raise IndexError("indices are out-of-bounds")
[ "Perform", "bounds", "-", "checking", "for", "an", "indexer", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2629-L2667
[ "def", "validate_indices", "(", "indices", ",", "n", ")", ":", "if", "len", "(", "indices", ")", ":", "min_idx", "=", "indices", ".", "min", "(", ")", "if", "min_idx", "<", "-", "1", ":", "msg", "=", "(", "\"'indices' contains values less than allowed ({} < {})\"", ".", "format", "(", "min_idx", ",", "-", "1", ")", ")", "raise", "ValueError", "(", "msg", ")", "max_idx", "=", "indices", ".", "max", "(", ")", "if", "max_idx", ">=", "n", ":", "raise", "IndexError", "(", "\"indices are out-of-bounds\"", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_convert_ix
We likely want to take the cross-product
pandas/core/indexing.py
def maybe_convert_ix(*args): """ We likely want to take the cross-product """ ixify = True for arg in args: if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)): ixify = False if ixify: return np.ix_(*args) else: return args
def maybe_convert_ix(*args): """ We likely want to take the cross-product """ ixify = True for arg in args: if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)): ixify = False if ixify: return np.ix_(*args) else: return args
[ "We", "likely", "want", "to", "take", "the", "cross", "-", "product" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2670-L2683
[ "def", "maybe_convert_ix", "(", "*", "args", ")", ":", "ixify", "=", "True", "for", "arg", "in", "args", ":", "if", "not", "isinstance", "(", "arg", ",", "(", "np", ".", "ndarray", ",", "list", ",", "ABCSeries", ",", "Index", ")", ")", ":", "ixify", "=", "False", "if", "ixify", ":", "return", "np", ".", "ix_", "(", "*", "args", ")", "else", ":", "return", "args" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_non_reducing_slice
Ensurse that a slice doesn't reduce to a Series or Scalar. Any user-paseed `subset` should have this called on it to make sure we're always working with DataFrames.
pandas/core/indexing.py
def _non_reducing_slice(slice_): """ Ensurse that a slice doesn't reduce to a Series or Scalar. Any user-paseed `subset` should have this called on it to make sure we're always working with DataFrames. """ # default to column slice, like DataFrame # ['A', 'B'] -> IndexSlices[:, ['A', 'B']] kinds = (ABCSeries, np.ndarray, Index, list, str) if isinstance(slice_, kinds): slice_ = IndexSlice[:, slice_] def pred(part): # true when slice does *not* reduce, False when part is a tuple, # i.e. MultiIndex slice return ((isinstance(part, slice) or is_list_like(part)) and not isinstance(part, tuple)) if not is_list_like(slice_): if not isinstance(slice_, slice): # a 1-d slice, like df.loc[1] slice_ = [[slice_]] else: # slice(a, b, c) slice_ = [slice_] # to tuplize later else: slice_ = [part if pred(part) else [part] for part in slice_] return tuple(slice_)
def _non_reducing_slice(slice_): """ Ensurse that a slice doesn't reduce to a Series or Scalar. Any user-paseed `subset` should have this called on it to make sure we're always working with DataFrames. """ # default to column slice, like DataFrame # ['A', 'B'] -> IndexSlices[:, ['A', 'B']] kinds = (ABCSeries, np.ndarray, Index, list, str) if isinstance(slice_, kinds): slice_ = IndexSlice[:, slice_] def pred(part): # true when slice does *not* reduce, False when part is a tuple, # i.e. MultiIndex slice return ((isinstance(part, slice) or is_list_like(part)) and not isinstance(part, tuple)) if not is_list_like(slice_): if not isinstance(slice_, slice): # a 1-d slice, like df.loc[1] slice_ = [[slice_]] else: # slice(a, b, c) slice_ = [slice_] # to tuplize later else: slice_ = [part if pred(part) else [part] for part in slice_] return tuple(slice_)
[ "Ensurse", "that", "a", "slice", "doesn", "t", "reduce", "to", "a", "Series", "or", "Scalar", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2734-L2762
[ "def", "_non_reducing_slice", "(", "slice_", ")", ":", "# default to column slice, like DataFrame", "# ['A', 'B'] -> IndexSlices[:, ['A', 'B']]", "kinds", "=", "(", "ABCSeries", ",", "np", ".", "ndarray", ",", "Index", ",", "list", ",", "str", ")", "if", "isinstance", "(", "slice_", ",", "kinds", ")", ":", "slice_", "=", "IndexSlice", "[", ":", ",", "slice_", "]", "def", "pred", "(", "part", ")", ":", "# true when slice does *not* reduce, False when part is a tuple,", "# i.e. MultiIndex slice", "return", "(", "(", "isinstance", "(", "part", ",", "slice", ")", "or", "is_list_like", "(", "part", ")", ")", "and", "not", "isinstance", "(", "part", ",", "tuple", ")", ")", "if", "not", "is_list_like", "(", "slice_", ")", ":", "if", "not", "isinstance", "(", "slice_", ",", "slice", ")", ":", "# a 1-d slice, like df.loc[1]", "slice_", "=", "[", "[", "slice_", "]", "]", "else", ":", "# slice(a, b, c)", "slice_", "=", "[", "slice_", "]", "# to tuplize later", "else", ":", "slice_", "=", "[", "part", "if", "pred", "(", "part", ")", "else", "[", "part", "]", "for", "part", "in", "slice_", "]", "return", "tuple", "(", "slice_", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_maybe_numeric_slice
want nice defaults for background_gradient that don't break with non-numeric data. But if slice_ is passed go with that.
pandas/core/indexing.py
def _maybe_numeric_slice(df, slice_, include_bool=False): """ want nice defaults for background_gradient that don't break with non-numeric data. But if slice_ is passed go with that. """ if slice_ is None: dtypes = [np.number] if include_bool: dtypes.append(bool) slice_ = IndexSlice[:, df.select_dtypes(include=dtypes).columns] return slice_
def _maybe_numeric_slice(df, slice_, include_bool=False): """ want nice defaults for background_gradient that don't break with non-numeric data. But if slice_ is passed go with that. """ if slice_ is None: dtypes = [np.number] if include_bool: dtypes.append(bool) slice_ = IndexSlice[:, df.select_dtypes(include=dtypes).columns] return slice_
[ "want", "nice", "defaults", "for", "background_gradient", "that", "don", "t", "break", "with", "non", "-", "numeric", "data", ".", "But", "if", "slice_", "is", "passed", "go", "with", "that", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2765-L2775
[ "def", "_maybe_numeric_slice", "(", "df", ",", "slice_", ",", "include_bool", "=", "False", ")", ":", "if", "slice_", "is", "None", ":", "dtypes", "=", "[", "np", ".", "number", "]", "if", "include_bool", ":", "dtypes", ".", "append", "(", "bool", ")", "slice_", "=", "IndexSlice", "[", ":", ",", "df", ".", "select_dtypes", "(", "include", "=", "dtypes", ")", ".", "columns", "]", "return", "slice_" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._has_valid_tuple
check the key for valid keys across my indexer
pandas/core/indexing.py
def _has_valid_tuple(self, key): """ check the key for valid keys across my indexer """ for i, k in enumerate(key): if i >= self.obj.ndim: raise IndexingError('Too many indexers') try: self._validate_key(k, i) except ValueError: raise ValueError("Location based indexing can only have " "[{types}] types" .format(types=self._valid_types))
def _has_valid_tuple(self, key): """ check the key for valid keys across my indexer """ for i, k in enumerate(key): if i >= self.obj.ndim: raise IndexingError('Too many indexers') try: self._validate_key(k, i) except ValueError: raise ValueError("Location based indexing can only have " "[{types}] types" .format(types=self._valid_types))
[ "check", "the", "key", "for", "valid", "keys", "across", "my", "indexer" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L215-L225
[ "def", "_has_valid_tuple", "(", "self", ",", "key", ")", ":", "for", "i", ",", "k", "in", "enumerate", "(", "key", ")", ":", "if", "i", ">=", "self", ".", "obj", ".", "ndim", ":", "raise", "IndexingError", "(", "'Too many indexers'", ")", "try", ":", "self", ".", "_validate_key", "(", "k", ",", "i", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Location based indexing can only have \"", "\"[{types}] types\"", ".", "format", "(", "types", "=", "self", ".", "_valid_types", ")", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._has_valid_positional_setitem_indexer
validate that an positional indexer cannot enlarge its target will raise if needed, does not modify the indexer externally
pandas/core/indexing.py
def _has_valid_positional_setitem_indexer(self, indexer): """ validate that an positional indexer cannot enlarge its target will raise if needed, does not modify the indexer externally """ if isinstance(indexer, dict): raise IndexError("{0} cannot enlarge its target object" .format(self.name)) else: if not isinstance(indexer, tuple): indexer = self._tuplify(indexer) for ax, i in zip(self.obj.axes, indexer): if isinstance(i, slice): # should check the stop slice? pass elif is_list_like_indexer(i): # should check the elements? pass elif is_integer(i): if i >= len(ax): raise IndexError("{name} cannot enlarge its target " "object".format(name=self.name)) elif isinstance(i, dict): raise IndexError("{name} cannot enlarge its target object" .format(name=self.name)) return True
def _has_valid_positional_setitem_indexer(self, indexer): """ validate that an positional indexer cannot enlarge its target will raise if needed, does not modify the indexer externally """ if isinstance(indexer, dict): raise IndexError("{0} cannot enlarge its target object" .format(self.name)) else: if not isinstance(indexer, tuple): indexer = self._tuplify(indexer) for ax, i in zip(self.obj.axes, indexer): if isinstance(i, slice): # should check the stop slice? pass elif is_list_like_indexer(i): # should check the elements? pass elif is_integer(i): if i >= len(ax): raise IndexError("{name} cannot enlarge its target " "object".format(name=self.name)) elif isinstance(i, dict): raise IndexError("{name} cannot enlarge its target object" .format(name=self.name)) return True
[ "validate", "that", "an", "positional", "indexer", "cannot", "enlarge", "its", "target", "will", "raise", "if", "needed", "does", "not", "modify", "the", "indexer", "externally" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L270-L295
[ "def", "_has_valid_positional_setitem_indexer", "(", "self", ",", "indexer", ")", ":", "if", "isinstance", "(", "indexer", ",", "dict", ")", ":", "raise", "IndexError", "(", "\"{0} cannot enlarge its target object\"", ".", "format", "(", "self", ".", "name", ")", ")", "else", ":", "if", "not", "isinstance", "(", "indexer", ",", "tuple", ")", ":", "indexer", "=", "self", ".", "_tuplify", "(", "indexer", ")", "for", "ax", ",", "i", "in", "zip", "(", "self", ".", "obj", ".", "axes", ",", "indexer", ")", ":", "if", "isinstance", "(", "i", ",", "slice", ")", ":", "# should check the stop slice?", "pass", "elif", "is_list_like_indexer", "(", "i", ")", ":", "# should check the elements?", "pass", "elif", "is_integer", "(", "i", ")", ":", "if", "i", ">=", "len", "(", "ax", ")", ":", "raise", "IndexError", "(", "\"{name} cannot enlarge its target \"", "\"object\"", ".", "format", "(", "name", "=", "self", ".", "name", ")", ")", "elif", "isinstance", "(", "i", ",", "dict", ")", ":", "raise", "IndexError", "(", "\"{name} cannot enlarge its target object\"", ".", "format", "(", "name", "=", "self", ".", "name", ")", ")", "return", "True" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._align_series
Parameters ---------- indexer : tuple, slice, scalar The indexer used to get the locations that will be set to `ser` ser : pd.Series The values to assign to the locations specified by `indexer` multiindex_indexer : boolean, optional Defaults to False. Should be set to True if `indexer` was from a `pd.MultiIndex`, to avoid unnecessary broadcasting. Returns: -------- `np.array` of `ser` broadcast to the appropriate shape for assignment to the locations selected by `indexer`
pandas/core/indexing.py
def _align_series(self, indexer, ser, multiindex_indexer=False): """ Parameters ---------- indexer : tuple, slice, scalar The indexer used to get the locations that will be set to `ser` ser : pd.Series The values to assign to the locations specified by `indexer` multiindex_indexer : boolean, optional Defaults to False. Should be set to True if `indexer` was from a `pd.MultiIndex`, to avoid unnecessary broadcasting. Returns: -------- `np.array` of `ser` broadcast to the appropriate shape for assignment to the locations selected by `indexer` """ if isinstance(indexer, (slice, np.ndarray, list, Index)): indexer = tuple([indexer]) if isinstance(indexer, tuple): # flatten np.ndarray indexers def ravel(i): return i.ravel() if isinstance(i, np.ndarray) else i indexer = tuple(map(ravel, indexer)) aligners = [not com.is_null_slice(idx) for idx in indexer] sum_aligners = sum(aligners) single_aligner = sum_aligners == 1 is_frame = self.obj.ndim == 2 is_panel = self.obj.ndim >= 3 obj = self.obj # are we a single alignable value on a non-primary # dim (e.g. panel: 1,2, or frame: 0) ? # hence need to align to a single axis dimension # rather that find all valid dims # frame if is_frame: single_aligner = single_aligner and aligners[0] # panel elif is_panel: single_aligner = (single_aligner and (aligners[1] or aligners[2])) # we have a frame, with multiple indexers on both axes; and a # series, so need to broadcast (see GH5206) if (sum_aligners == self.ndim and all(is_sequence(_) for _ in indexer)): ser = ser.reindex(obj.axes[0][indexer[0]], copy=True)._values # single indexer if len(indexer) > 1 and not multiindex_indexer: len_indexer = len(indexer[1]) ser = np.tile(ser, len_indexer).reshape(len_indexer, -1).T return ser for i, idx in enumerate(indexer): ax = obj.axes[i] # multiple aligners (or null slices) if is_sequence(idx) or isinstance(idx, slice): if single_aligner and com.is_null_slice(idx): continue new_ix = ax[idx] if not is_list_like_indexer(new_ix): new_ix = Index([new_ix]) else: new_ix = Index(new_ix) if ser.index.equals(new_ix) or not len(new_ix): return ser._values.copy() return ser.reindex(new_ix)._values # 2 dims elif single_aligner and is_frame: # reindex along index ax = self.obj.axes[1] if ser.index.equals(ax) or not len(ax): return ser._values.copy() return ser.reindex(ax)._values # >2 dims elif single_aligner: broadcast = [] for n, labels in enumerate(self.obj._get_plane_axes(i)): # reindex along the matching dimensions if len(labels & ser.index): ser = ser.reindex(labels) else: broadcast.append((n, len(labels))) # broadcast along other dims ser = ser._values.copy() for (axis, l) in broadcast: shape = [-1] * (len(broadcast) + 1) shape[axis] = l ser = np.tile(ser, l).reshape(shape) if self.obj.ndim == 3: ser = ser.T return ser elif is_scalar(indexer): ax = self.obj._get_axis(1) if ser.index.equals(ax): return ser._values.copy() return ser.reindex(ax)._values raise ValueError('Incompatible indexer with Series')
def _align_series(self, indexer, ser, multiindex_indexer=False): """ Parameters ---------- indexer : tuple, slice, scalar The indexer used to get the locations that will be set to `ser` ser : pd.Series The values to assign to the locations specified by `indexer` multiindex_indexer : boolean, optional Defaults to False. Should be set to True if `indexer` was from a `pd.MultiIndex`, to avoid unnecessary broadcasting. Returns: -------- `np.array` of `ser` broadcast to the appropriate shape for assignment to the locations selected by `indexer` """ if isinstance(indexer, (slice, np.ndarray, list, Index)): indexer = tuple([indexer]) if isinstance(indexer, tuple): # flatten np.ndarray indexers def ravel(i): return i.ravel() if isinstance(i, np.ndarray) else i indexer = tuple(map(ravel, indexer)) aligners = [not com.is_null_slice(idx) for idx in indexer] sum_aligners = sum(aligners) single_aligner = sum_aligners == 1 is_frame = self.obj.ndim == 2 is_panel = self.obj.ndim >= 3 obj = self.obj # are we a single alignable value on a non-primary # dim (e.g. panel: 1,2, or frame: 0) ? # hence need to align to a single axis dimension # rather that find all valid dims # frame if is_frame: single_aligner = single_aligner and aligners[0] # panel elif is_panel: single_aligner = (single_aligner and (aligners[1] or aligners[2])) # we have a frame, with multiple indexers on both axes; and a # series, so need to broadcast (see GH5206) if (sum_aligners == self.ndim and all(is_sequence(_) for _ in indexer)): ser = ser.reindex(obj.axes[0][indexer[0]], copy=True)._values # single indexer if len(indexer) > 1 and not multiindex_indexer: len_indexer = len(indexer[1]) ser = np.tile(ser, len_indexer).reshape(len_indexer, -1).T return ser for i, idx in enumerate(indexer): ax = obj.axes[i] # multiple aligners (or null slices) if is_sequence(idx) or isinstance(idx, slice): if single_aligner and com.is_null_slice(idx): continue new_ix = ax[idx] if not is_list_like_indexer(new_ix): new_ix = Index([new_ix]) else: new_ix = Index(new_ix) if ser.index.equals(new_ix) or not len(new_ix): return ser._values.copy() return ser.reindex(new_ix)._values # 2 dims elif single_aligner and is_frame: # reindex along index ax = self.obj.axes[1] if ser.index.equals(ax) or not len(ax): return ser._values.copy() return ser.reindex(ax)._values # >2 dims elif single_aligner: broadcast = [] for n, labels in enumerate(self.obj._get_plane_axes(i)): # reindex along the matching dimensions if len(labels & ser.index): ser = ser.reindex(labels) else: broadcast.append((n, len(labels))) # broadcast along other dims ser = ser._values.copy() for (axis, l) in broadcast: shape = [-1] * (len(broadcast) + 1) shape[axis] = l ser = np.tile(ser, l).reshape(shape) if self.obj.ndim == 3: ser = ser.T return ser elif is_scalar(indexer): ax = self.obj._get_axis(1) if ser.index.equals(ax): return ser._values.copy() return ser.reindex(ax)._values raise ValueError('Incompatible indexer with Series')
[ "Parameters", "----------", "indexer", ":", "tuple", "slice", "scalar", "The", "indexer", "used", "to", "get", "the", "locations", "that", "will", "be", "set", "to", "ser" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L657-L781
[ "def", "_align_series", "(", "self", ",", "indexer", ",", "ser", ",", "multiindex_indexer", "=", "False", ")", ":", "if", "isinstance", "(", "indexer", ",", "(", "slice", ",", "np", ".", "ndarray", ",", "list", ",", "Index", ")", ")", ":", "indexer", "=", "tuple", "(", "[", "indexer", "]", ")", "if", "isinstance", "(", "indexer", ",", "tuple", ")", ":", "# flatten np.ndarray indexers", "def", "ravel", "(", "i", ")", ":", "return", "i", ".", "ravel", "(", ")", "if", "isinstance", "(", "i", ",", "np", ".", "ndarray", ")", "else", "i", "indexer", "=", "tuple", "(", "map", "(", "ravel", ",", "indexer", ")", ")", "aligners", "=", "[", "not", "com", ".", "is_null_slice", "(", "idx", ")", "for", "idx", "in", "indexer", "]", "sum_aligners", "=", "sum", "(", "aligners", ")", "single_aligner", "=", "sum_aligners", "==", "1", "is_frame", "=", "self", ".", "obj", ".", "ndim", "==", "2", "is_panel", "=", "self", ".", "obj", ".", "ndim", ">=", "3", "obj", "=", "self", ".", "obj", "# are we a single alignable value on a non-primary", "# dim (e.g. panel: 1,2, or frame: 0) ?", "# hence need to align to a single axis dimension", "# rather that find all valid dims", "# frame", "if", "is_frame", ":", "single_aligner", "=", "single_aligner", "and", "aligners", "[", "0", "]", "# panel", "elif", "is_panel", ":", "single_aligner", "=", "(", "single_aligner", "and", "(", "aligners", "[", "1", "]", "or", "aligners", "[", "2", "]", ")", ")", "# we have a frame, with multiple indexers on both axes; and a", "# series, so need to broadcast (see GH5206)", "if", "(", "sum_aligners", "==", "self", ".", "ndim", "and", "all", "(", "is_sequence", "(", "_", ")", "for", "_", "in", "indexer", ")", ")", ":", "ser", "=", "ser", ".", "reindex", "(", "obj", ".", "axes", "[", "0", "]", "[", "indexer", "[", "0", "]", "]", ",", "copy", "=", "True", ")", ".", "_values", "# single indexer", "if", "len", "(", "indexer", ")", ">", "1", "and", "not", "multiindex_indexer", ":", "len_indexer", "=", "len", "(", "indexer", "[", "1", "]", ")", "ser", "=", "np", ".", "tile", "(", "ser", ",", "len_indexer", ")", ".", "reshape", "(", "len_indexer", ",", "-", "1", ")", ".", "T", "return", "ser", "for", "i", ",", "idx", "in", "enumerate", "(", "indexer", ")", ":", "ax", "=", "obj", ".", "axes", "[", "i", "]", "# multiple aligners (or null slices)", "if", "is_sequence", "(", "idx", ")", "or", "isinstance", "(", "idx", ",", "slice", ")", ":", "if", "single_aligner", "and", "com", ".", "is_null_slice", "(", "idx", ")", ":", "continue", "new_ix", "=", "ax", "[", "idx", "]", "if", "not", "is_list_like_indexer", "(", "new_ix", ")", ":", "new_ix", "=", "Index", "(", "[", "new_ix", "]", ")", "else", ":", "new_ix", "=", "Index", "(", "new_ix", ")", "if", "ser", ".", "index", ".", "equals", "(", "new_ix", ")", "or", "not", "len", "(", "new_ix", ")", ":", "return", "ser", ".", "_values", ".", "copy", "(", ")", "return", "ser", ".", "reindex", "(", "new_ix", ")", ".", "_values", "# 2 dims", "elif", "single_aligner", "and", "is_frame", ":", "# reindex along index", "ax", "=", "self", ".", "obj", ".", "axes", "[", "1", "]", "if", "ser", ".", "index", ".", "equals", "(", "ax", ")", "or", "not", "len", "(", "ax", ")", ":", "return", "ser", ".", "_values", ".", "copy", "(", ")", "return", "ser", ".", "reindex", "(", "ax", ")", ".", "_values", "# >2 dims", "elif", "single_aligner", ":", "broadcast", "=", "[", "]", "for", "n", ",", "labels", "in", "enumerate", "(", "self", ".", "obj", ".", "_get_plane_axes", "(", "i", ")", ")", ":", "# reindex along the matching dimensions", "if", "len", "(", "labels", "&", "ser", ".", "index", ")", ":", "ser", "=", "ser", ".", "reindex", "(", "labels", ")", "else", ":", "broadcast", ".", "append", "(", "(", "n", ",", "len", "(", "labels", ")", ")", ")", "# broadcast along other dims", "ser", "=", "ser", ".", "_values", ".", "copy", "(", ")", "for", "(", "axis", ",", "l", ")", "in", "broadcast", ":", "shape", "=", "[", "-", "1", "]", "*", "(", "len", "(", "broadcast", ")", "+", "1", ")", "shape", "[", "axis", "]", "=", "l", "ser", "=", "np", ".", "tile", "(", "ser", ",", "l", ")", ".", "reshape", "(", "shape", ")", "if", "self", ".", "obj", ".", "ndim", "==", "3", ":", "ser", "=", "ser", ".", "T", "return", "ser", "elif", "is_scalar", "(", "indexer", ")", ":", "ax", "=", "self", ".", "obj", ".", "_get_axis", "(", "1", ")", "if", "ser", ".", "index", ".", "equals", "(", "ax", ")", ":", "return", "ser", ".", "_values", ".", "copy", "(", ")", "return", "ser", ".", "reindex", "(", "ax", ")", ".", "_values", "raise", "ValueError", "(", "'Incompatible indexer with Series'", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._multi_take_opportunity
Check whether there is the possibility to use ``_multi_take``. Currently the limit is that all axes being indexed must be indexed with list-likes. Parameters ---------- tup : tuple Tuple of indexers, one per axis Returns ------- boolean: Whether the current indexing can be passed through _multi_take
pandas/core/indexing.py
def _multi_take_opportunity(self, tup): """ Check whether there is the possibility to use ``_multi_take``. Currently the limit is that all axes being indexed must be indexed with list-likes. Parameters ---------- tup : tuple Tuple of indexers, one per axis Returns ------- boolean: Whether the current indexing can be passed through _multi_take """ if not all(is_list_like_indexer(x) for x in tup): return False # just too complicated if any(com.is_bool_indexer(x) for x in tup): return False return True
def _multi_take_opportunity(self, tup): """ Check whether there is the possibility to use ``_multi_take``. Currently the limit is that all axes being indexed must be indexed with list-likes. Parameters ---------- tup : tuple Tuple of indexers, one per axis Returns ------- boolean: Whether the current indexing can be passed through _multi_take """ if not all(is_list_like_indexer(x) for x in tup): return False # just too complicated if any(com.is_bool_indexer(x) for x in tup): return False return True
[ "Check", "whether", "there", "is", "the", "possibility", "to", "use", "_multi_take", ".", "Currently", "the", "limit", "is", "that", "all", "axes", "being", "indexed", "must", "be", "indexed", "with", "list", "-", "likes", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L890-L912
[ "def", "_multi_take_opportunity", "(", "self", ",", "tup", ")", ":", "if", "not", "all", "(", "is_list_like_indexer", "(", "x", ")", "for", "x", "in", "tup", ")", ":", "return", "False", "# just too complicated", "if", "any", "(", "com", ".", "is_bool_indexer", "(", "x", ")", "for", "x", "in", "tup", ")", ":", "return", "False", "return", "True" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._multi_take
Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : tuple Tuple of indexers, one per axis Returns ------- values: same type as the object being indexed
pandas/core/indexing.py
def _multi_take(self, tup): """ Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : tuple Tuple of indexers, one per axis Returns ------- values: same type as the object being indexed """ # GH 836 o = self.obj d = {axis: self._get_listlike_indexer(key, axis) for (key, axis) in zip(tup, o._AXIS_ORDERS)} return o._reindex_with_indexers(d, copy=True, allow_dups=True)
def _multi_take(self, tup): """ Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : tuple Tuple of indexers, one per axis Returns ------- values: same type as the object being indexed """ # GH 836 o = self.obj d = {axis: self._get_listlike_indexer(key, axis) for (key, axis) in zip(tup, o._AXIS_ORDERS)} return o._reindex_with_indexers(d, copy=True, allow_dups=True)
[ "Create", "the", "indexers", "for", "the", "passed", "tuple", "of", "keys", "and", "execute", "the", "take", "operation", ".", "This", "allows", "the", "take", "operation", "to", "be", "executed", "all", "at", "once", "-", "rather", "than", "once", "for", "each", "dimension", "-", "improving", "efficiency", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L914-L933
[ "def", "_multi_take", "(", "self", ",", "tup", ")", ":", "# GH 836", "o", "=", "self", ".", "obj", "d", "=", "{", "axis", ":", "self", ".", "_get_listlike_indexer", "(", "key", ",", "axis", ")", "for", "(", "key", ",", "axis", ")", "in", "zip", "(", "tup", ",", "o", ".", "_AXIS_ORDERS", ")", "}", "return", "o", ".", "_reindex_with_indexers", "(", "d", ",", "copy", "=", "True", ",", "allow_dups", "=", "True", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._get_listlike_indexer
Transform a list-like of keys into a new index and an indexer. Parameters ---------- key : list-like Target labels axis: int Dimension on which the indexing is being made raise_missing: bool Whether to raise a KeyError if some labels are not found. Will be removed in the future, and then this method will always behave as if raise_missing=True. Raises ------ KeyError If at least one key was requested but none was found, and raise_missing=True. Returns ------- keyarr: Index New index (coinciding with 'key' if the axis is unique) values : array-like An indexer for the return object; -1 denotes keys not found
pandas/core/indexing.py
def _get_listlike_indexer(self, key, axis, raise_missing=False): """ Transform a list-like of keys into a new index and an indexer. Parameters ---------- key : list-like Target labels axis: int Dimension on which the indexing is being made raise_missing: bool Whether to raise a KeyError if some labels are not found. Will be removed in the future, and then this method will always behave as if raise_missing=True. Raises ------ KeyError If at least one key was requested but none was found, and raise_missing=True. Returns ------- keyarr: Index New index (coinciding with 'key' if the axis is unique) values : array-like An indexer for the return object; -1 denotes keys not found """ o = self.obj ax = o._get_axis(axis) # Have the index compute an indexer or return None # if it cannot handle: indexer, keyarr = ax._convert_listlike_indexer(key, kind=self.name) # We only act on all found values: if indexer is not None and (indexer != -1).all(): self._validate_read_indexer(key, indexer, axis, raise_missing=raise_missing) return ax[indexer], indexer if ax.is_unique: # If we are trying to get actual keys from empty Series, we # patiently wait for a KeyError later on - otherwise, convert if len(ax) or not len(key): key = self._convert_for_reindex(key, axis) indexer = ax.get_indexer_for(key) keyarr = ax.reindex(keyarr)[0] else: keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr) self._validate_read_indexer(keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing) return keyarr, indexer
def _get_listlike_indexer(self, key, axis, raise_missing=False): """ Transform a list-like of keys into a new index and an indexer. Parameters ---------- key : list-like Target labels axis: int Dimension on which the indexing is being made raise_missing: bool Whether to raise a KeyError if some labels are not found. Will be removed in the future, and then this method will always behave as if raise_missing=True. Raises ------ KeyError If at least one key was requested but none was found, and raise_missing=True. Returns ------- keyarr: Index New index (coinciding with 'key' if the axis is unique) values : array-like An indexer for the return object; -1 denotes keys not found """ o = self.obj ax = o._get_axis(axis) # Have the index compute an indexer or return None # if it cannot handle: indexer, keyarr = ax._convert_listlike_indexer(key, kind=self.name) # We only act on all found values: if indexer is not None and (indexer != -1).all(): self._validate_read_indexer(key, indexer, axis, raise_missing=raise_missing) return ax[indexer], indexer if ax.is_unique: # If we are trying to get actual keys from empty Series, we # patiently wait for a KeyError later on - otherwise, convert if len(ax) or not len(key): key = self._convert_for_reindex(key, axis) indexer = ax.get_indexer_for(key) keyarr = ax.reindex(keyarr)[0] else: keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr) self._validate_read_indexer(keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing) return keyarr, indexer
[ "Transform", "a", "list", "-", "like", "of", "keys", "into", "a", "new", "index", "and", "an", "indexer", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L1112-L1166
[ "def", "_get_listlike_indexer", "(", "self", ",", "key", ",", "axis", ",", "raise_missing", "=", "False", ")", ":", "o", "=", "self", ".", "obj", "ax", "=", "o", ".", "_get_axis", "(", "axis", ")", "# Have the index compute an indexer or return None", "# if it cannot handle:", "indexer", ",", "keyarr", "=", "ax", ".", "_convert_listlike_indexer", "(", "key", ",", "kind", "=", "self", ".", "name", ")", "# We only act on all found values:", "if", "indexer", "is", "not", "None", "and", "(", "indexer", "!=", "-", "1", ")", ".", "all", "(", ")", ":", "self", ".", "_validate_read_indexer", "(", "key", ",", "indexer", ",", "axis", ",", "raise_missing", "=", "raise_missing", ")", "return", "ax", "[", "indexer", "]", ",", "indexer", "if", "ax", ".", "is_unique", ":", "# If we are trying to get actual keys from empty Series, we", "# patiently wait for a KeyError later on - otherwise, convert", "if", "len", "(", "ax", ")", "or", "not", "len", "(", "key", ")", ":", "key", "=", "self", ".", "_convert_for_reindex", "(", "key", ",", "axis", ")", "indexer", "=", "ax", ".", "get_indexer_for", "(", "key", ")", "keyarr", "=", "ax", ".", "reindex", "(", "keyarr", ")", "[", "0", "]", "else", ":", "keyarr", ",", "indexer", ",", "new_indexer", "=", "ax", ".", "_reindex_non_unique", "(", "keyarr", ")", "self", ".", "_validate_read_indexer", "(", "keyarr", ",", "indexer", ",", "o", ".", "_get_axis_number", "(", "axis", ")", ",", "raise_missing", "=", "raise_missing", ")", "return", "keyarr", ",", "indexer" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._getitem_iterable
Index current object with an an iterable key (which can be a boolean indexer, or a collection of keys). Parameters ---------- key : iterable Target labels, or boolean indexer axis: int, default None Dimension on which the indexing is being made Raises ------ KeyError If no key was found. Will change in the future to raise if not all keys were found. IndexingError If the boolean indexer is unalignable with the object being indexed. Returns ------- scalar, DataFrame, or Series: indexed value(s),
pandas/core/indexing.py
def _getitem_iterable(self, key, axis=None): """ Index current object with an an iterable key (which can be a boolean indexer, or a collection of keys). Parameters ---------- key : iterable Target labels, or boolean indexer axis: int, default None Dimension on which the indexing is being made Raises ------ KeyError If no key was found. Will change in the future to raise if not all keys were found. IndexingError If the boolean indexer is unalignable with the object being indexed. Returns ------- scalar, DataFrame, or Series: indexed value(s), """ if axis is None: axis = self.axis or 0 self._validate_key(key, axis) labels = self.obj._get_axis(axis) if com.is_bool_indexer(key): # A boolean indexer key = check_bool_indexer(labels, key) inds, = key.nonzero() return self.obj._take(inds, axis=axis) else: # A collection of keys keyarr, indexer = self._get_listlike_indexer(key, axis, raise_missing=False) return self.obj._reindex_with_indexers({axis: [keyarr, indexer]}, copy=True, allow_dups=True)
def _getitem_iterable(self, key, axis=None): """ Index current object with an an iterable key (which can be a boolean indexer, or a collection of keys). Parameters ---------- key : iterable Target labels, or boolean indexer axis: int, default None Dimension on which the indexing is being made Raises ------ KeyError If no key was found. Will change in the future to raise if not all keys were found. IndexingError If the boolean indexer is unalignable with the object being indexed. Returns ------- scalar, DataFrame, or Series: indexed value(s), """ if axis is None: axis = self.axis or 0 self._validate_key(key, axis) labels = self.obj._get_axis(axis) if com.is_bool_indexer(key): # A boolean indexer key = check_bool_indexer(labels, key) inds, = key.nonzero() return self.obj._take(inds, axis=axis) else: # A collection of keys keyarr, indexer = self._get_listlike_indexer(key, axis, raise_missing=False) return self.obj._reindex_with_indexers({axis: [keyarr, indexer]}, copy=True, allow_dups=True)
[ "Index", "current", "object", "with", "an", "an", "iterable", "key", "(", "which", "can", "be", "a", "boolean", "indexer", "or", "a", "collection", "of", "keys", ")", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L1168-L1211
[ "def", "_getitem_iterable", "(", "self", ",", "key", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "axis", "or", "0", "self", ".", "_validate_key", "(", "key", ",", "axis", ")", "labels", "=", "self", ".", "obj", ".", "_get_axis", "(", "axis", ")", "if", "com", ".", "is_bool_indexer", "(", "key", ")", ":", "# A boolean indexer", "key", "=", "check_bool_indexer", "(", "labels", ",", "key", ")", "inds", ",", "=", "key", ".", "nonzero", "(", ")", "return", "self", ".", "obj", ".", "_take", "(", "inds", ",", "axis", "=", "axis", ")", "else", ":", "# A collection of keys", "keyarr", ",", "indexer", "=", "self", ".", "_get_listlike_indexer", "(", "key", ",", "axis", ",", "raise_missing", "=", "False", ")", "return", "self", ".", "obj", ".", "_reindex_with_indexers", "(", "{", "axis", ":", "[", "keyarr", ",", "indexer", "]", "}", ",", "copy", "=", "True", ",", "allow_dups", "=", "True", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._validate_read_indexer
Check that indexer can be used to return a result (e.g. at least one element was found, unless the list of keys was actually empty). Parameters ---------- key : list-like Target labels (only used to show correct error message) indexer: array-like of booleans Indices corresponding to the key (with -1 indicating not found) axis: int Dimension on which the indexing is being made raise_missing: bool Whether to raise a KeyError if some labels are not found. Will be removed in the future, and then this method will always behave as if raise_missing=True. Raises ------ KeyError If at least one key was requested but none was found, and raise_missing=True.
pandas/core/indexing.py
def _validate_read_indexer(self, key, indexer, axis, raise_missing=False): """ Check that indexer can be used to return a result (e.g. at least one element was found, unless the list of keys was actually empty). Parameters ---------- key : list-like Target labels (only used to show correct error message) indexer: array-like of booleans Indices corresponding to the key (with -1 indicating not found) axis: int Dimension on which the indexing is being made raise_missing: bool Whether to raise a KeyError if some labels are not found. Will be removed in the future, and then this method will always behave as if raise_missing=True. Raises ------ KeyError If at least one key was requested but none was found, and raise_missing=True. """ ax = self.obj._get_axis(axis) if len(key) == 0: return # Count missing values: missing = (indexer < 0).sum() if missing: if missing == len(indexer): raise KeyError( "None of [{key}] are in the [{axis}]".format( key=key, axis=self.obj._get_axis_name(axis))) # We (temporarily) allow for some missing keys with .loc, except in # some cases (e.g. setting) in which "raise_missing" will be False if not(self.name == 'loc' and not raise_missing): not_found = list(set(key) - set(ax)) raise KeyError("{} not in index".format(not_found)) # we skip the warning on Categorical/Interval # as this check is actually done (check for # non-missing values), but a bit later in the # code, so we want to avoid warning & then # just raising _missing_key_warning = textwrap.dedent(""" Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. See the documentation here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike""") # noqa if not (ax.is_categorical() or ax.is_interval()): warnings.warn(_missing_key_warning, FutureWarning, stacklevel=6)
def _validate_read_indexer(self, key, indexer, axis, raise_missing=False): """ Check that indexer can be used to return a result (e.g. at least one element was found, unless the list of keys was actually empty). Parameters ---------- key : list-like Target labels (only used to show correct error message) indexer: array-like of booleans Indices corresponding to the key (with -1 indicating not found) axis: int Dimension on which the indexing is being made raise_missing: bool Whether to raise a KeyError if some labels are not found. Will be removed in the future, and then this method will always behave as if raise_missing=True. Raises ------ KeyError If at least one key was requested but none was found, and raise_missing=True. """ ax = self.obj._get_axis(axis) if len(key) == 0: return # Count missing values: missing = (indexer < 0).sum() if missing: if missing == len(indexer): raise KeyError( "None of [{key}] are in the [{axis}]".format( key=key, axis=self.obj._get_axis_name(axis))) # We (temporarily) allow for some missing keys with .loc, except in # some cases (e.g. setting) in which "raise_missing" will be False if not(self.name == 'loc' and not raise_missing): not_found = list(set(key) - set(ax)) raise KeyError("{} not in index".format(not_found)) # we skip the warning on Categorical/Interval # as this check is actually done (check for # non-missing values), but a bit later in the # code, so we want to avoid warning & then # just raising _missing_key_warning = textwrap.dedent(""" Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. See the documentation here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike""") # noqa if not (ax.is_categorical() or ax.is_interval()): warnings.warn(_missing_key_warning, FutureWarning, stacklevel=6)
[ "Check", "that", "indexer", "can", "be", "used", "to", "return", "a", "result", "(", "e", ".", "g", ".", "at", "least", "one", "element", "was", "found", "unless", "the", "list", "of", "keys", "was", "actually", "empty", ")", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L1213-L1273
[ "def", "_validate_read_indexer", "(", "self", ",", "key", ",", "indexer", ",", "axis", ",", "raise_missing", "=", "False", ")", ":", "ax", "=", "self", ".", "obj", ".", "_get_axis", "(", "axis", ")", "if", "len", "(", "key", ")", "==", "0", ":", "return", "# Count missing values:", "missing", "=", "(", "indexer", "<", "0", ")", ".", "sum", "(", ")", "if", "missing", ":", "if", "missing", "==", "len", "(", "indexer", ")", ":", "raise", "KeyError", "(", "\"None of [{key}] are in the [{axis}]\"", ".", "format", "(", "key", "=", "key", ",", "axis", "=", "self", ".", "obj", ".", "_get_axis_name", "(", "axis", ")", ")", ")", "# We (temporarily) allow for some missing keys with .loc, except in", "# some cases (e.g. setting) in which \"raise_missing\" will be False", "if", "not", "(", "self", ".", "name", "==", "'loc'", "and", "not", "raise_missing", ")", ":", "not_found", "=", "list", "(", "set", "(", "key", ")", "-", "set", "(", "ax", ")", ")", "raise", "KeyError", "(", "\"{} not in index\"", ".", "format", "(", "not_found", ")", ")", "# we skip the warning on Categorical/Interval", "# as this check is actually done (check for", "# non-missing values), but a bit later in the", "# code, so we want to avoid warning & then", "# just raising", "_missing_key_warning", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n Passing list-likes to .loc or [] with any missing label will raise\n KeyError in the future, you can use .reindex() as an alternative.\n\n See the documentation here:\n https://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike\"\"\"", ")", "# noqa", "if", "not", "(", "ax", ".", "is_categorical", "(", ")", "or", "ax", ".", "is_interval", "(", ")", ")", ":", "warnings", ".", "warn", "(", "_missing_key_warning", ",", "FutureWarning", ",", "stacklevel", "=", "6", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_NDFrameIndexer._convert_to_indexer
Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) Going by Zen of Python? 'In the face of ambiguity, refuse the temptation to guess.' raise AmbiguousIndexError with integer labels? - No, prefer label-based indexing
pandas/core/indexing.py
def _convert_to_indexer(self, obj, axis=None, is_setter=False, raise_missing=False): """ Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) Going by Zen of Python? 'In the face of ambiguity, refuse the temptation to guess.' raise AmbiguousIndexError with integer labels? - No, prefer label-based indexing """ if axis is None: axis = self.axis or 0 labels = self.obj._get_axis(axis) if isinstance(obj, slice): return self._convert_slice_indexer(obj, axis) # try to find out correct indexer, if not type correct raise try: obj = self._convert_scalar_indexer(obj, axis) except TypeError: # but we will allow setting if is_setter: pass # see if we are positional in nature is_int_index = labels.is_integer() is_int_positional = is_integer(obj) and not is_int_index # if we are a label return me try: return labels.get_loc(obj) except LookupError: if isinstance(obj, tuple) and isinstance(labels, MultiIndex): if is_setter and len(obj) == labels.nlevels: return {'key': obj} raise except TypeError: pass except (ValueError): if not is_int_positional: raise # a positional if is_int_positional: # if we are setting and its not a valid location # its an insert which fails by definition if is_setter: # always valid if self.name == 'loc': return {'key': obj} # a positional if (obj >= self.obj.shape[axis] and not isinstance(labels, MultiIndex)): raise ValueError("cannot set by positional indexing with " "enlargement") return obj if is_nested_tuple(obj, labels): return labels.get_locs(obj) elif is_list_like_indexer(obj): if com.is_bool_indexer(obj): obj = check_bool_indexer(labels, obj) inds, = obj.nonzero() return inds else: # When setting, missing keys are not allowed, even with .loc: kwargs = {'raise_missing': True if is_setter else raise_missing} return self._get_listlike_indexer(obj, axis, **kwargs)[1] else: try: return labels.get_loc(obj) except LookupError: # allow a not found key only if we are a setter if not is_list_like_indexer(obj) and is_setter: return {'key': obj} raise
def _convert_to_indexer(self, obj, axis=None, is_setter=False, raise_missing=False): """ Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) Going by Zen of Python? 'In the face of ambiguity, refuse the temptation to guess.' raise AmbiguousIndexError with integer labels? - No, prefer label-based indexing """ if axis is None: axis = self.axis or 0 labels = self.obj._get_axis(axis) if isinstance(obj, slice): return self._convert_slice_indexer(obj, axis) # try to find out correct indexer, if not type correct raise try: obj = self._convert_scalar_indexer(obj, axis) except TypeError: # but we will allow setting if is_setter: pass # see if we are positional in nature is_int_index = labels.is_integer() is_int_positional = is_integer(obj) and not is_int_index # if we are a label return me try: return labels.get_loc(obj) except LookupError: if isinstance(obj, tuple) and isinstance(labels, MultiIndex): if is_setter and len(obj) == labels.nlevels: return {'key': obj} raise except TypeError: pass except (ValueError): if not is_int_positional: raise # a positional if is_int_positional: # if we are setting and its not a valid location # its an insert which fails by definition if is_setter: # always valid if self.name == 'loc': return {'key': obj} # a positional if (obj >= self.obj.shape[axis] and not isinstance(labels, MultiIndex)): raise ValueError("cannot set by positional indexing with " "enlargement") return obj if is_nested_tuple(obj, labels): return labels.get_locs(obj) elif is_list_like_indexer(obj): if com.is_bool_indexer(obj): obj = check_bool_indexer(labels, obj) inds, = obj.nonzero() return inds else: # When setting, missing keys are not allowed, even with .loc: kwargs = {'raise_missing': True if is_setter else raise_missing} return self._get_listlike_indexer(obj, axis, **kwargs)[1] else: try: return labels.get_loc(obj) except LookupError: # allow a not found key only if we are a setter if not is_list_like_indexer(obj) and is_setter: return {'key': obj} raise
[ "Convert", "indexing", "key", "into", "something", "we", "can", "use", "to", "do", "actual", "fancy", "indexing", "on", "an", "ndarray" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L1275-L1366
[ "def", "_convert_to_indexer", "(", "self", ",", "obj", ",", "axis", "=", "None", ",", "is_setter", "=", "False", ",", "raise_missing", "=", "False", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "axis", "or", "0", "labels", "=", "self", ".", "obj", ".", "_get_axis", "(", "axis", ")", "if", "isinstance", "(", "obj", ",", "slice", ")", ":", "return", "self", ".", "_convert_slice_indexer", "(", "obj", ",", "axis", ")", "# try to find out correct indexer, if not type correct raise", "try", ":", "obj", "=", "self", ".", "_convert_scalar_indexer", "(", "obj", ",", "axis", ")", "except", "TypeError", ":", "# but we will allow setting", "if", "is_setter", ":", "pass", "# see if we are positional in nature", "is_int_index", "=", "labels", ".", "is_integer", "(", ")", "is_int_positional", "=", "is_integer", "(", "obj", ")", "and", "not", "is_int_index", "# if we are a label return me", "try", ":", "return", "labels", ".", "get_loc", "(", "obj", ")", "except", "LookupError", ":", "if", "isinstance", "(", "obj", ",", "tuple", ")", "and", "isinstance", "(", "labels", ",", "MultiIndex", ")", ":", "if", "is_setter", "and", "len", "(", "obj", ")", "==", "labels", ".", "nlevels", ":", "return", "{", "'key'", ":", "obj", "}", "raise", "except", "TypeError", ":", "pass", "except", "(", "ValueError", ")", ":", "if", "not", "is_int_positional", ":", "raise", "# a positional", "if", "is_int_positional", ":", "# if we are setting and its not a valid location", "# its an insert which fails by definition", "if", "is_setter", ":", "# always valid", "if", "self", ".", "name", "==", "'loc'", ":", "return", "{", "'key'", ":", "obj", "}", "# a positional", "if", "(", "obj", ">=", "self", ".", "obj", ".", "shape", "[", "axis", "]", "and", "not", "isinstance", "(", "labels", ",", "MultiIndex", ")", ")", ":", "raise", "ValueError", "(", "\"cannot set by positional indexing with \"", "\"enlargement\"", ")", "return", "obj", "if", "is_nested_tuple", "(", "obj", ",", "labels", ")", ":", "return", "labels", ".", "get_locs", "(", "obj", ")", "elif", "is_list_like_indexer", "(", "obj", ")", ":", "if", "com", ".", "is_bool_indexer", "(", "obj", ")", ":", "obj", "=", "check_bool_indexer", "(", "labels", ",", "obj", ")", "inds", ",", "=", "obj", ".", "nonzero", "(", ")", "return", "inds", "else", ":", "# When setting, missing keys are not allowed, even with .loc:", "kwargs", "=", "{", "'raise_missing'", ":", "True", "if", "is_setter", "else", "raise_missing", "}", "return", "self", ".", "_get_listlike_indexer", "(", "obj", ",", "axis", ",", "*", "*", "kwargs", ")", "[", "1", "]", "else", ":", "try", ":", "return", "labels", ".", "get_loc", "(", "obj", ")", "except", "LookupError", ":", "# allow a not found key only if we are a setter", "if", "not", "is_list_like_indexer", "(", "obj", ")", "and", "is_setter", ":", "return", "{", "'key'", ":", "obj", "}", "raise" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_IXIndexer._convert_for_reindex
Transform a list of keys into a new array ready to be used as axis of the object we return (e.g. including NaNs). Parameters ---------- key : list-like Target labels axis: int Where the indexing is being made Returns ------- list-like of labels
pandas/core/indexing.py
def _convert_for_reindex(self, key, axis=None): """ Transform a list of keys into a new array ready to be used as axis of the object we return (e.g. including NaNs). Parameters ---------- key : list-like Target labels axis: int Where the indexing is being made Returns ------- list-like of labels """ if axis is None: axis = self.axis or 0 labels = self.obj._get_axis(axis) if com.is_bool_indexer(key): key = check_bool_indexer(labels, key) return labels[key] if isinstance(key, Index): keyarr = labels._convert_index_indexer(key) else: # asarray can be unsafe, NumPy strings are weird keyarr = com.asarray_tuplesafe(key) if is_integer_dtype(keyarr): # Cast the indexer to uint64 if possible so # that the values returned from indexing are # also uint64. keyarr = labels._convert_arr_indexer(keyarr) if not labels.is_integer(): keyarr = ensure_platform_int(keyarr) return labels.take(keyarr) return keyarr
def _convert_for_reindex(self, key, axis=None): """ Transform a list of keys into a new array ready to be used as axis of the object we return (e.g. including NaNs). Parameters ---------- key : list-like Target labels axis: int Where the indexing is being made Returns ------- list-like of labels """ if axis is None: axis = self.axis or 0 labels = self.obj._get_axis(axis) if com.is_bool_indexer(key): key = check_bool_indexer(labels, key) return labels[key] if isinstance(key, Index): keyarr = labels._convert_index_indexer(key) else: # asarray can be unsafe, NumPy strings are weird keyarr = com.asarray_tuplesafe(key) if is_integer_dtype(keyarr): # Cast the indexer to uint64 if possible so # that the values returned from indexing are # also uint64. keyarr = labels._convert_arr_indexer(keyarr) if not labels.is_integer(): keyarr = ensure_platform_int(keyarr) return labels.take(keyarr) return keyarr
[ "Transform", "a", "list", "of", "keys", "into", "a", "new", "array", "ready", "to", "be", "used", "as", "axis", "of", "the", "object", "we", "return", "(", "e", ".", "g", ".", "including", "NaNs", ")", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L1442-L1483
[ "def", "_convert_for_reindex", "(", "self", ",", "key", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "axis", "or", "0", "labels", "=", "self", ".", "obj", ".", "_get_axis", "(", "axis", ")", "if", "com", ".", "is_bool_indexer", "(", "key", ")", ":", "key", "=", "check_bool_indexer", "(", "labels", ",", "key", ")", "return", "labels", "[", "key", "]", "if", "isinstance", "(", "key", ",", "Index", ")", ":", "keyarr", "=", "labels", ".", "_convert_index_indexer", "(", "key", ")", "else", ":", "# asarray can be unsafe, NumPy strings are weird", "keyarr", "=", "com", ".", "asarray_tuplesafe", "(", "key", ")", "if", "is_integer_dtype", "(", "keyarr", ")", ":", "# Cast the indexer to uint64 if possible so", "# that the values returned from indexing are", "# also uint64.", "keyarr", "=", "labels", ".", "_convert_arr_indexer", "(", "keyarr", ")", "if", "not", "labels", ".", "is_integer", "(", ")", ":", "keyarr", "=", "ensure_platform_int", "(", "keyarr", ")", "return", "labels", ".", "take", "(", "keyarr", ")", "return", "keyarr" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_LocationIndexer._get_slice_axis
this is pretty simple as we just have to deal with labels
pandas/core/indexing.py
def _get_slice_axis(self, slice_obj, axis=None): """ this is pretty simple as we just have to deal with labels """ if axis is None: axis = self.axis or 0 obj = self.obj if not need_slice(slice_obj): return obj.copy(deep=False) labels = obj._get_axis(axis) indexer = labels.slice_indexer(slice_obj.start, slice_obj.stop, slice_obj.step, kind=self.name) if isinstance(indexer, slice): return self._slice(indexer, axis=axis, kind='iloc') else: return self.obj._take(indexer, axis=axis)
def _get_slice_axis(self, slice_obj, axis=None): """ this is pretty simple as we just have to deal with labels """ if axis is None: axis = self.axis or 0 obj = self.obj if not need_slice(slice_obj): return obj.copy(deep=False) labels = obj._get_axis(axis) indexer = labels.slice_indexer(slice_obj.start, slice_obj.stop, slice_obj.step, kind=self.name) if isinstance(indexer, slice): return self._slice(indexer, axis=axis, kind='iloc') else: return self.obj._take(indexer, axis=axis)
[ "this", "is", "pretty", "simple", "as", "we", "just", "have", "to", "deal", "with", "labels" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L1526-L1542
[ "def", "_get_slice_axis", "(", "self", ",", "slice_obj", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "axis", "or", "0", "obj", "=", "self", ".", "obj", "if", "not", "need_slice", "(", "slice_obj", ")", ":", "return", "obj", ".", "copy", "(", "deep", "=", "False", ")", "labels", "=", "obj", ".", "_get_axis", "(", "axis", ")", "indexer", "=", "labels", ".", "slice_indexer", "(", "slice_obj", ".", "start", ",", "slice_obj", ".", "stop", ",", "slice_obj", ".", "step", ",", "kind", "=", "self", ".", "name", ")", "if", "isinstance", "(", "indexer", ",", "slice", ")", ":", "return", "self", ".", "_slice", "(", "indexer", ",", "axis", "=", "axis", ",", "kind", "=", "'iloc'", ")", "else", ":", "return", "self", ".", "obj", ".", "_take", "(", "indexer", ",", "axis", "=", "axis", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_LocIndexer._get_partial_string_timestamp_match_key
Translate any partial string timestamp matches in key, returning the new key (GH 10331)
pandas/core/indexing.py
def _get_partial_string_timestamp_match_key(self, key, labels): """Translate any partial string timestamp matches in key, returning the new key (GH 10331)""" if isinstance(labels, MultiIndex): if (isinstance(key, str) and labels.levels[0].is_all_dates): # Convert key '2016-01-01' to # ('2016-01-01'[, slice(None, None, None)]+) key = tuple([key] + [slice(None)] * (len(labels.levels) - 1)) if isinstance(key, tuple): # Convert (..., '2016-01-01', ...) in tuple to # (..., slice('2016-01-01', '2016-01-01', None), ...) new_key = [] for i, component in enumerate(key): if (isinstance(component, str) and labels.levels[i].is_all_dates): new_key.append(slice(component, component, None)) else: new_key.append(component) key = tuple(new_key) return key
def _get_partial_string_timestamp_match_key(self, key, labels): """Translate any partial string timestamp matches in key, returning the new key (GH 10331)""" if isinstance(labels, MultiIndex): if (isinstance(key, str) and labels.levels[0].is_all_dates): # Convert key '2016-01-01' to # ('2016-01-01'[, slice(None, None, None)]+) key = tuple([key] + [slice(None)] * (len(labels.levels) - 1)) if isinstance(key, tuple): # Convert (..., '2016-01-01', ...) in tuple to # (..., slice('2016-01-01', '2016-01-01', None), ...) new_key = [] for i, component in enumerate(key): if (isinstance(component, str) and labels.levels[i].is_all_dates): new_key.append(slice(component, component, None)) else: new_key.append(component) key = tuple(new_key) return key
[ "Translate", "any", "partial", "string", "timestamp", "matches", "in", "key", "returning", "the", "new", "key", "(", "GH", "10331", ")" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L1835-L1856
[ "def", "_get_partial_string_timestamp_match_key", "(", "self", ",", "key", ",", "labels", ")", ":", "if", "isinstance", "(", "labels", ",", "MultiIndex", ")", ":", "if", "(", "isinstance", "(", "key", ",", "str", ")", "and", "labels", ".", "levels", "[", "0", "]", ".", "is_all_dates", ")", ":", "# Convert key '2016-01-01' to", "# ('2016-01-01'[, slice(None, None, None)]+)", "key", "=", "tuple", "(", "[", "key", "]", "+", "[", "slice", "(", "None", ")", "]", "*", "(", "len", "(", "labels", ".", "levels", ")", "-", "1", ")", ")", "if", "isinstance", "(", "key", ",", "tuple", ")", ":", "# Convert (..., '2016-01-01', ...) in tuple to", "# (..., slice('2016-01-01', '2016-01-01', None), ...)", "new_key", "=", "[", "]", "for", "i", ",", "component", "in", "enumerate", "(", "key", ")", ":", "if", "(", "isinstance", "(", "component", ",", "str", ")", "and", "labels", ".", "levels", "[", "i", "]", ".", "is_all_dates", ")", ":", "new_key", ".", "append", "(", "slice", "(", "component", ",", "component", ",", "None", ")", ")", "else", ":", "new_key", ".", "append", "(", "component", ")", "key", "=", "tuple", "(", "new_key", ")", "return", "key" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_iLocIndexer._validate_integer
Check that 'key' is a valid position in the desired axis. Parameters ---------- key : int Requested position axis : int Desired axis Returns ------- None Raises ------ IndexError If 'key' is not a valid position in axis 'axis'
pandas/core/indexing.py
def _validate_integer(self, key, axis): """ Check that 'key' is a valid position in the desired axis. Parameters ---------- key : int Requested position axis : int Desired axis Returns ------- None Raises ------ IndexError If 'key' is not a valid position in axis 'axis' """ len_axis = len(self.obj._get_axis(axis)) if key >= len_axis or key < -len_axis: raise IndexError("single positional indexer is out-of-bounds")
def _validate_integer(self, key, axis): """ Check that 'key' is a valid position in the desired axis. Parameters ---------- key : int Requested position axis : int Desired axis Returns ------- None Raises ------ IndexError If 'key' is not a valid position in axis 'axis' """ len_axis = len(self.obj._get_axis(axis)) if key >= len_axis or key < -len_axis: raise IndexError("single positional indexer is out-of-bounds")
[ "Check", "that", "key", "is", "a", "valid", "position", "in", "the", "desired", "axis", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2125-L2148
[ "def", "_validate_integer", "(", "self", ",", "key", ",", "axis", ")", ":", "len_axis", "=", "len", "(", "self", ".", "obj", ".", "_get_axis", "(", "axis", ")", ")", "if", "key", ">=", "len_axis", "or", "key", "<", "-", "len_axis", ":", "raise", "IndexError", "(", "\"single positional indexer is out-of-bounds\"", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_iLocIndexer._get_list_axis
Return Series values by list or array of integers Parameters ---------- key : list-like positional indexer axis : int (can only be zero) Returns ------- Series object
pandas/core/indexing.py
def _get_list_axis(self, key, axis=None): """ Return Series values by list or array of integers Parameters ---------- key : list-like positional indexer axis : int (can only be zero) Returns ------- Series object """ if axis is None: axis = self.axis or 0 try: return self.obj._take(key, axis=axis) except IndexError: # re-raise with different error message raise IndexError("positional indexers are out-of-bounds")
def _get_list_axis(self, key, axis=None): """ Return Series values by list or array of integers Parameters ---------- key : list-like positional indexer axis : int (can only be zero) Returns ------- Series object """ if axis is None: axis = self.axis or 0 try: return self.obj._take(key, axis=axis) except IndexError: # re-raise with different error message raise IndexError("positional indexers are out-of-bounds")
[ "Return", "Series", "values", "by", "list", "or", "array", "of", "integers" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2193-L2212
[ "def", "_get_list_axis", "(", "self", ",", "key", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "axis", "or", "0", "try", ":", "return", "self", ".", "obj", ".", "_take", "(", "key", ",", "axis", "=", "axis", ")", "except", "IndexError", ":", "# re-raise with different error message", "raise", "IndexError", "(", "\"positional indexers are out-of-bounds\"", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_iLocIndexer._convert_to_indexer
much simpler as we only have to deal with our valid types
pandas/core/indexing.py
def _convert_to_indexer(self, obj, axis=None, is_setter=False): """ much simpler as we only have to deal with our valid types """ if axis is None: axis = self.axis or 0 # make need to convert a float key if isinstance(obj, slice): return self._convert_slice_indexer(obj, axis) elif is_float(obj): return self._convert_scalar_indexer(obj, axis) try: self._validate_key(obj, axis) return obj except ValueError: raise ValueError("Can only index by location with " "a [{types}]".format(types=self._valid_types))
def _convert_to_indexer(self, obj, axis=None, is_setter=False): """ much simpler as we only have to deal with our valid types """ if axis is None: axis = self.axis or 0 # make need to convert a float key if isinstance(obj, slice): return self._convert_slice_indexer(obj, axis) elif is_float(obj): return self._convert_scalar_indexer(obj, axis) try: self._validate_key(obj, axis) return obj except ValueError: raise ValueError("Can only index by location with " "a [{types}]".format(types=self._valid_types))
[ "much", "simpler", "as", "we", "only", "have", "to", "deal", "with", "our", "valid", "types" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2244-L2261
[ "def", "_convert_to_indexer", "(", "self", ",", "obj", ",", "axis", "=", "None", ",", "is_setter", "=", "False", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "axis", "or", "0", "# make need to convert a float key", "if", "isinstance", "(", "obj", ",", "slice", ")", ":", "return", "self", ".", "_convert_slice_indexer", "(", "obj", ",", "axis", ")", "elif", "is_float", "(", "obj", ")", ":", "return", "self", ".", "_convert_scalar_indexer", "(", "obj", ",", "axis", ")", "try", ":", "self", ".", "_validate_key", "(", "obj", ",", "axis", ")", "return", "obj", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Can only index by location with \"", "\"a [{types}]\"", ".", "format", "(", "types", "=", "self", ".", "_valid_types", ")", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_AtIndexer._convert_key
require they keys to be the same type as the index (so we don't fallback)
pandas/core/indexing.py
def _convert_key(self, key, is_setter=False): """ require they keys to be the same type as the index (so we don't fallback) """ # allow arbitrary setting if is_setter: return list(key) for ax, i in zip(self.obj.axes, key): if ax.is_integer(): if not is_integer(i): raise ValueError("At based indexing on an integer index " "can only have integer indexers") else: if is_integer(i) and not ax.holds_integer(): raise ValueError("At based indexing on an non-integer " "index can only have non-integer " "indexers") return key
def _convert_key(self, key, is_setter=False): """ require they keys to be the same type as the index (so we don't fallback) """ # allow arbitrary setting if is_setter: return list(key) for ax, i in zip(self.obj.axes, key): if ax.is_integer(): if not is_integer(i): raise ValueError("At based indexing on an integer index " "can only have integer indexers") else: if is_integer(i) and not ax.holds_integer(): raise ValueError("At based indexing on an non-integer " "index can only have non-integer " "indexers") return key
[ "require", "they", "keys", "to", "be", "the", "same", "type", "as", "the", "index", "(", "so", "we", "don", "t", "fallback", ")" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2349-L2368
[ "def", "_convert_key", "(", "self", ",", "key", ",", "is_setter", "=", "False", ")", ":", "# allow arbitrary setting", "if", "is_setter", ":", "return", "list", "(", "key", ")", "for", "ax", ",", "i", "in", "zip", "(", "self", ".", "obj", ".", "axes", ",", "key", ")", ":", "if", "ax", ".", "is_integer", "(", ")", ":", "if", "not", "is_integer", "(", "i", ")", ":", "raise", "ValueError", "(", "\"At based indexing on an integer index \"", "\"can only have integer indexers\"", ")", "else", ":", "if", "is_integer", "(", "i", ")", "and", "not", "ax", ".", "holds_integer", "(", ")", ":", "raise", "ValueError", "(", "\"At based indexing on an non-integer \"", "\"index can only have non-integer \"", "\"indexers\"", ")", "return", "key" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
_iAtIndexer._convert_key
require integer args (and convert to label arguments)
pandas/core/indexing.py
def _convert_key(self, key, is_setter=False): """ require integer args (and convert to label arguments) """ for a, i in zip(self.obj.axes, key): if not is_integer(i): raise ValueError("iAt based indexing can only have integer " "indexers") return key
def _convert_key(self, key, is_setter=False): """ require integer args (and convert to label arguments) """ for a, i in zip(self.obj.axes, key): if not is_integer(i): raise ValueError("iAt based indexing can only have integer " "indexers") return key
[ "require", "integer", "args", "(", "and", "convert", "to", "label", "arguments", ")" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2422-L2428
[ "def", "_convert_key", "(", "self", ",", "key", ",", "is_setter", "=", "False", ")", ":", "for", "a", ",", "i", "in", "zip", "(", "self", ".", "obj", ".", "axes", ",", "key", ")", ":", "if", "not", "is_integer", "(", "i", ")", ":", "raise", "ValueError", "(", "\"iAt based indexing can only have integer \"", "\"indexers\"", ")", "return", "key" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
to_manager
create and return the block manager from a dataframe of series, columns, index
pandas/core/sparse/frame.py
def to_manager(sdf, columns, index): """ create and return the block manager from a dataframe of series, columns, index """ # from BlockManager perspective axes = [ensure_index(columns), ensure_index(index)] return create_block_manager_from_arrays( [sdf[c] for c in columns], columns, axes)
def to_manager(sdf, columns, index): """ create and return the block manager from a dataframe of series, columns, index """ # from BlockManager perspective axes = [ensure_index(columns), ensure_index(index)] return create_block_manager_from_arrays( [sdf[c] for c in columns], columns, axes)
[ "create", "and", "return", "the", "block", "manager", "from", "a", "dataframe", "of", "series", "columns", "index" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L951-L960
[ "def", "to_manager", "(", "sdf", ",", "columns", ",", "index", ")", ":", "# from BlockManager perspective", "axes", "=", "[", "ensure_index", "(", "columns", ")", ",", "ensure_index", "(", "index", ")", "]", "return", "create_block_manager_from_arrays", "(", "[", "sdf", "[", "c", "]", "for", "c", "in", "columns", "]", ",", "columns", ",", "axes", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
stack_sparse_frame
Only makes sense when fill_value is NaN
pandas/core/sparse/frame.py
def stack_sparse_frame(frame): """ Only makes sense when fill_value is NaN """ lengths = [s.sp_index.npoints for _, s in frame.items()] nobs = sum(lengths) # this is pretty fast minor_codes = np.repeat(np.arange(len(frame.columns)), lengths) inds_to_concat = [] vals_to_concat = [] # TODO: Figure out whether this can be reached. # I think this currently can't be reached because you can't build a # SparseDataFrame with a non-np.NaN fill value (fails earlier). for _, series in frame.items(): if not np.isnan(series.fill_value): raise TypeError('This routine assumes NaN fill value') int_index = series.sp_index.to_int_index() inds_to_concat.append(int_index.indices) vals_to_concat.append(series.sp_values) major_codes = np.concatenate(inds_to_concat) stacked_values = np.concatenate(vals_to_concat) index = MultiIndex(levels=[frame.index, frame.columns], codes=[major_codes, minor_codes], verify_integrity=False) lp = DataFrame(stacked_values.reshape((nobs, 1)), index=index, columns=['foo']) return lp.sort_index(level=0)
def stack_sparse_frame(frame): """ Only makes sense when fill_value is NaN """ lengths = [s.sp_index.npoints for _, s in frame.items()] nobs = sum(lengths) # this is pretty fast minor_codes = np.repeat(np.arange(len(frame.columns)), lengths) inds_to_concat = [] vals_to_concat = [] # TODO: Figure out whether this can be reached. # I think this currently can't be reached because you can't build a # SparseDataFrame with a non-np.NaN fill value (fails earlier). for _, series in frame.items(): if not np.isnan(series.fill_value): raise TypeError('This routine assumes NaN fill value') int_index = series.sp_index.to_int_index() inds_to_concat.append(int_index.indices) vals_to_concat.append(series.sp_values) major_codes = np.concatenate(inds_to_concat) stacked_values = np.concatenate(vals_to_concat) index = MultiIndex(levels=[frame.index, frame.columns], codes=[major_codes, minor_codes], verify_integrity=False) lp = DataFrame(stacked_values.reshape((nobs, 1)), index=index, columns=['foo']) return lp.sort_index(level=0)
[ "Only", "makes", "sense", "when", "fill_value", "is", "NaN" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L963-L994
[ "def", "stack_sparse_frame", "(", "frame", ")", ":", "lengths", "=", "[", "s", ".", "sp_index", ".", "npoints", "for", "_", ",", "s", "in", "frame", ".", "items", "(", ")", "]", "nobs", "=", "sum", "(", "lengths", ")", "# this is pretty fast", "minor_codes", "=", "np", ".", "repeat", "(", "np", ".", "arange", "(", "len", "(", "frame", ".", "columns", ")", ")", ",", "lengths", ")", "inds_to_concat", "=", "[", "]", "vals_to_concat", "=", "[", "]", "# TODO: Figure out whether this can be reached.", "# I think this currently can't be reached because you can't build a", "# SparseDataFrame with a non-np.NaN fill value (fails earlier).", "for", "_", ",", "series", "in", "frame", ".", "items", "(", ")", ":", "if", "not", "np", ".", "isnan", "(", "series", ".", "fill_value", ")", ":", "raise", "TypeError", "(", "'This routine assumes NaN fill value'", ")", "int_index", "=", "series", ".", "sp_index", ".", "to_int_index", "(", ")", "inds_to_concat", ".", "append", "(", "int_index", ".", "indices", ")", "vals_to_concat", ".", "append", "(", "series", ".", "sp_values", ")", "major_codes", "=", "np", ".", "concatenate", "(", "inds_to_concat", ")", "stacked_values", "=", "np", ".", "concatenate", "(", "vals_to_concat", ")", "index", "=", "MultiIndex", "(", "levels", "=", "[", "frame", ".", "index", ",", "frame", ".", "columns", "]", ",", "codes", "=", "[", "major_codes", ",", "minor_codes", "]", ",", "verify_integrity", "=", "False", ")", "lp", "=", "DataFrame", "(", "stacked_values", ".", "reshape", "(", "(", "nobs", ",", "1", ")", ")", ",", "index", "=", "index", ",", "columns", "=", "[", "'foo'", "]", ")", "return", "lp", ".", "sort_index", "(", "level", "=", "0", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
homogenize
Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex corresponding to the locations where they all have data Parameters ---------- series_dict : dict or DataFrame Notes ----- Using the dumbest algorithm I could think of. Should put some more thought into this Returns ------- homogenized : dict of SparseSeries
pandas/core/sparse/frame.py
def homogenize(series_dict): """ Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex corresponding to the locations where they all have data Parameters ---------- series_dict : dict or DataFrame Notes ----- Using the dumbest algorithm I could think of. Should put some more thought into this Returns ------- homogenized : dict of SparseSeries """ index = None need_reindex = False for _, series in series_dict.items(): if not np.isnan(series.fill_value): raise TypeError('this method is only valid with NaN fill values') if index is None: index = series.sp_index elif not series.sp_index.equals(index): need_reindex = True index = index.intersect(series.sp_index) if need_reindex: output = {} for name, series in series_dict.items(): if not series.sp_index.equals(index): series = series.sparse_reindex(index) output[name] = series else: output = series_dict return output
def homogenize(series_dict): """ Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex corresponding to the locations where they all have data Parameters ---------- series_dict : dict or DataFrame Notes ----- Using the dumbest algorithm I could think of. Should put some more thought into this Returns ------- homogenized : dict of SparseSeries """ index = None need_reindex = False for _, series in series_dict.items(): if not np.isnan(series.fill_value): raise TypeError('this method is only valid with NaN fill values') if index is None: index = series.sp_index elif not series.sp_index.equals(index): need_reindex = True index = index.intersect(series.sp_index) if need_reindex: output = {} for name, series in series_dict.items(): if not series.sp_index.equals(index): series = series.sparse_reindex(index) output[name] = series else: output = series_dict return output
[ "Conform", "a", "set", "of", "SparseSeries", "(", "with", "NaN", "fill_value", ")", "to", "a", "common", "SparseIndex", "corresponding", "to", "the", "locations", "where", "they", "all", "have", "data" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L997-L1039
[ "def", "homogenize", "(", "series_dict", ")", ":", "index", "=", "None", "need_reindex", "=", "False", "for", "_", ",", "series", "in", "series_dict", ".", "items", "(", ")", ":", "if", "not", "np", ".", "isnan", "(", "series", ".", "fill_value", ")", ":", "raise", "TypeError", "(", "'this method is only valid with NaN fill values'", ")", "if", "index", "is", "None", ":", "index", "=", "series", ".", "sp_index", "elif", "not", "series", ".", "sp_index", ".", "equals", "(", "index", ")", ":", "need_reindex", "=", "True", "index", "=", "index", ".", "intersect", "(", "series", ".", "sp_index", ")", "if", "need_reindex", ":", "output", "=", "{", "}", "for", "name", ",", "series", "in", "series_dict", ".", "items", "(", ")", ":", "if", "not", "series", ".", "sp_index", ".", "equals", "(", "index", ")", ":", "series", "=", "series", ".", "sparse_reindex", "(", "index", ")", "output", "[", "name", "]", "=", "series", "else", ":", "output", "=", "series_dict", "return", "output" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame._init_matrix
Init self from ndarray or list of lists.
pandas/core/sparse/frame.py
def _init_matrix(self, data, index, columns, dtype=None): """ Init self from ndarray or list of lists. """ data = prep_ndarray(data, copy=False) index, columns = self._prep_index(data, index, columns) data = {idx: data[:, i] for i, idx in enumerate(columns)} return self._init_dict(data, index, columns, dtype)
def _init_matrix(self, data, index, columns, dtype=None): """ Init self from ndarray or list of lists. """ data = prep_ndarray(data, copy=False) index, columns = self._prep_index(data, index, columns) data = {idx: data[:, i] for i, idx in enumerate(columns)} return self._init_dict(data, index, columns, dtype)
[ "Init", "self", "from", "ndarray", "or", "list", "of", "lists", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L190-L197
[ "def", "_init_matrix", "(", "self", ",", "data", ",", "index", ",", "columns", ",", "dtype", "=", "None", ")", ":", "data", "=", "prep_ndarray", "(", "data", ",", "copy", "=", "False", ")", "index", ",", "columns", "=", "self", ".", "_prep_index", "(", "data", ",", "index", ",", "columns", ")", "data", "=", "{", "idx", ":", "data", "[", ":", ",", "i", "]", "for", "i", ",", "idx", "in", "enumerate", "(", "columns", ")", "}", "return", "self", ".", "_init_dict", "(", "data", ",", "index", ",", "columns", ",", "dtype", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame._init_spmatrix
Init self from scipy.sparse matrix.
pandas/core/sparse/frame.py
def _init_spmatrix(self, data, index, columns, dtype=None, fill_value=None): """ Init self from scipy.sparse matrix. """ index, columns = self._prep_index(data, index, columns) data = data.tocoo() N = len(index) # Construct a dict of SparseSeries sdict = {} values = Series(data.data, index=data.row, copy=False) for col, rowvals in values.groupby(data.col): # get_blocks expects int32 row indices in sorted order rowvals = rowvals.sort_index() rows = rowvals.index.values.astype(np.int32) blocs, blens = get_blocks(rows) sdict[columns[col]] = SparseSeries( rowvals.values, index=index, fill_value=fill_value, sparse_index=BlockIndex(N, blocs, blens)) # Add any columns that were empty and thus not grouped on above sdict.update({column: SparseSeries(index=index, fill_value=fill_value, sparse_index=BlockIndex(N, [], [])) for column in columns if column not in sdict}) return self._init_dict(sdict, index, columns, dtype)
def _init_spmatrix(self, data, index, columns, dtype=None, fill_value=None): """ Init self from scipy.sparse matrix. """ index, columns = self._prep_index(data, index, columns) data = data.tocoo() N = len(index) # Construct a dict of SparseSeries sdict = {} values = Series(data.data, index=data.row, copy=False) for col, rowvals in values.groupby(data.col): # get_blocks expects int32 row indices in sorted order rowvals = rowvals.sort_index() rows = rowvals.index.values.astype(np.int32) blocs, blens = get_blocks(rows) sdict[columns[col]] = SparseSeries( rowvals.values, index=index, fill_value=fill_value, sparse_index=BlockIndex(N, blocs, blens)) # Add any columns that were empty and thus not grouped on above sdict.update({column: SparseSeries(index=index, fill_value=fill_value, sparse_index=BlockIndex(N, [], [])) for column in columns if column not in sdict}) return self._init_dict(sdict, index, columns, dtype)
[ "Init", "self", "from", "scipy", ".", "sparse", "matrix", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L199-L229
[ "def", "_init_spmatrix", "(", "self", ",", "data", ",", "index", ",", "columns", ",", "dtype", "=", "None", ",", "fill_value", "=", "None", ")", ":", "index", ",", "columns", "=", "self", ".", "_prep_index", "(", "data", ",", "index", ",", "columns", ")", "data", "=", "data", ".", "tocoo", "(", ")", "N", "=", "len", "(", "index", ")", "# Construct a dict of SparseSeries", "sdict", "=", "{", "}", "values", "=", "Series", "(", "data", ".", "data", ",", "index", "=", "data", ".", "row", ",", "copy", "=", "False", ")", "for", "col", ",", "rowvals", "in", "values", ".", "groupby", "(", "data", ".", "col", ")", ":", "# get_blocks expects int32 row indices in sorted order", "rowvals", "=", "rowvals", ".", "sort_index", "(", ")", "rows", "=", "rowvals", ".", "index", ".", "values", ".", "astype", "(", "np", ".", "int32", ")", "blocs", ",", "blens", "=", "get_blocks", "(", "rows", ")", "sdict", "[", "columns", "[", "col", "]", "]", "=", "SparseSeries", "(", "rowvals", ".", "values", ",", "index", "=", "index", ",", "fill_value", "=", "fill_value", ",", "sparse_index", "=", "BlockIndex", "(", "N", ",", "blocs", ",", "blens", ")", ")", "# Add any columns that were empty and thus not grouped on above", "sdict", ".", "update", "(", "{", "column", ":", "SparseSeries", "(", "index", "=", "index", ",", "fill_value", "=", "fill_value", ",", "sparse_index", "=", "BlockIndex", "(", "N", ",", "[", "]", ",", "[", "]", ")", ")", "for", "column", "in", "columns", "if", "column", "not", "in", "sdict", "}", ")", "return", "self", ".", "_init_dict", "(", "sdict", ",", "index", ",", "columns", ",", "dtype", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame.to_coo
Return the contents of the frame as a sparse SciPy COO matrix. .. versionadded:: 0.20.0 Returns ------- coo_matrix : scipy.sparse.spmatrix If the caller is heterogeneous and contains booleans or objects, the result will be of dtype=object. See Notes. Notes ----- The dtype will be the lowest-common-denominator type (implicit upcasting); that is to say if the dtypes (even of numeric types) are mixed, the one that accommodates all will be chosen. e.g. If the dtypes are float16 and float32, dtype will be upcast to float32. By numpy.find_common_type convention, mixing int64 and and uint64 will result in a float64 dtype.
pandas/core/sparse/frame.py
def to_coo(self): """ Return the contents of the frame as a sparse SciPy COO matrix. .. versionadded:: 0.20.0 Returns ------- coo_matrix : scipy.sparse.spmatrix If the caller is heterogeneous and contains booleans or objects, the result will be of dtype=object. See Notes. Notes ----- The dtype will be the lowest-common-denominator type (implicit upcasting); that is to say if the dtypes (even of numeric types) are mixed, the one that accommodates all will be chosen. e.g. If the dtypes are float16 and float32, dtype will be upcast to float32. By numpy.find_common_type convention, mixing int64 and and uint64 will result in a float64 dtype. """ try: from scipy.sparse import coo_matrix except ImportError: raise ImportError('Scipy is not installed') dtype = find_common_type(self.dtypes) if isinstance(dtype, SparseDtype): dtype = dtype.subtype cols, rows, datas = [], [], [] for col, name in enumerate(self): s = self[name] row = s.sp_index.to_int_index().indices cols.append(np.repeat(col, len(row))) rows.append(row) datas.append(s.sp_values.astype(dtype, copy=False)) cols = np.concatenate(cols) rows = np.concatenate(rows) datas = np.concatenate(datas) return coo_matrix((datas, (rows, cols)), shape=self.shape)
def to_coo(self): """ Return the contents of the frame as a sparse SciPy COO matrix. .. versionadded:: 0.20.0 Returns ------- coo_matrix : scipy.sparse.spmatrix If the caller is heterogeneous and contains booleans or objects, the result will be of dtype=object. See Notes. Notes ----- The dtype will be the lowest-common-denominator type (implicit upcasting); that is to say if the dtypes (even of numeric types) are mixed, the one that accommodates all will be chosen. e.g. If the dtypes are float16 and float32, dtype will be upcast to float32. By numpy.find_common_type convention, mixing int64 and and uint64 will result in a float64 dtype. """ try: from scipy.sparse import coo_matrix except ImportError: raise ImportError('Scipy is not installed') dtype = find_common_type(self.dtypes) if isinstance(dtype, SparseDtype): dtype = dtype.subtype cols, rows, datas = [], [], [] for col, name in enumerate(self): s = self[name] row = s.sp_index.to_int_index().indices cols.append(np.repeat(col, len(row))) rows.append(row) datas.append(s.sp_values.astype(dtype, copy=False)) cols = np.concatenate(cols) rows = np.concatenate(rows) datas = np.concatenate(datas) return coo_matrix((datas, (rows, cols)), shape=self.shape)
[ "Return", "the", "contents", "of", "the", "frame", "as", "a", "sparse", "SciPy", "COO", "matrix", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L246-L288
[ "def", "to_coo", "(", "self", ")", ":", "try", ":", "from", "scipy", ".", "sparse", "import", "coo_matrix", "except", "ImportError", ":", "raise", "ImportError", "(", "'Scipy is not installed'", ")", "dtype", "=", "find_common_type", "(", "self", ".", "dtypes", ")", "if", "isinstance", "(", "dtype", ",", "SparseDtype", ")", ":", "dtype", "=", "dtype", ".", "subtype", "cols", ",", "rows", ",", "datas", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "col", ",", "name", "in", "enumerate", "(", "self", ")", ":", "s", "=", "self", "[", "name", "]", "row", "=", "s", ".", "sp_index", ".", "to_int_index", "(", ")", ".", "indices", "cols", ".", "append", "(", "np", ".", "repeat", "(", "col", ",", "len", "(", "row", ")", ")", ")", "rows", ".", "append", "(", "row", ")", "datas", ".", "append", "(", "s", ".", "sp_values", ".", "astype", "(", "dtype", ",", "copy", "=", "False", ")", ")", "cols", "=", "np", ".", "concatenate", "(", "cols", ")", "rows", "=", "np", ".", "concatenate", "(", "rows", ")", "datas", "=", "np", ".", "concatenate", "(", "datas", ")", "return", "coo_matrix", "(", "(", "datas", ",", "(", "rows", ",", "cols", ")", ")", ",", "shape", "=", "self", ".", "shape", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame._unpickle_sparse_frame_compat
Original pickle format
pandas/core/sparse/frame.py
def _unpickle_sparse_frame_compat(self, state): """ Original pickle format """ series, cols, idx, fv, kind = state if not isinstance(cols, Index): # pragma: no cover from pandas.io.pickle import _unpickle_array columns = _unpickle_array(cols) else: columns = cols if not isinstance(idx, Index): # pragma: no cover from pandas.io.pickle import _unpickle_array index = _unpickle_array(idx) else: index = idx series_dict = DataFrame() for col, (sp_index, sp_values) in series.items(): series_dict[col] = SparseSeries(sp_values, sparse_index=sp_index, fill_value=fv) self._data = to_manager(series_dict, columns, index) self._default_fill_value = fv self._default_kind = kind
def _unpickle_sparse_frame_compat(self, state): """ Original pickle format """ series, cols, idx, fv, kind = state if not isinstance(cols, Index): # pragma: no cover from pandas.io.pickle import _unpickle_array columns = _unpickle_array(cols) else: columns = cols if not isinstance(idx, Index): # pragma: no cover from pandas.io.pickle import _unpickle_array index = _unpickle_array(idx) else: index = idx series_dict = DataFrame() for col, (sp_index, sp_values) in series.items(): series_dict[col] = SparseSeries(sp_values, sparse_index=sp_index, fill_value=fv) self._data = to_manager(series_dict, columns, index) self._default_fill_value = fv self._default_kind = kind
[ "Original", "pickle", "format" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L302-L327
[ "def", "_unpickle_sparse_frame_compat", "(", "self", ",", "state", ")", ":", "series", ",", "cols", ",", "idx", ",", "fv", ",", "kind", "=", "state", "if", "not", "isinstance", "(", "cols", ",", "Index", ")", ":", "# pragma: no cover", "from", "pandas", ".", "io", ".", "pickle", "import", "_unpickle_array", "columns", "=", "_unpickle_array", "(", "cols", ")", "else", ":", "columns", "=", "cols", "if", "not", "isinstance", "(", "idx", ",", "Index", ")", ":", "# pragma: no cover", "from", "pandas", ".", "io", ".", "pickle", "import", "_unpickle_array", "index", "=", "_unpickle_array", "(", "idx", ")", "else", ":", "index", "=", "idx", "series_dict", "=", "DataFrame", "(", ")", "for", "col", ",", "(", "sp_index", ",", "sp_values", ")", "in", "series", ".", "items", "(", ")", ":", "series_dict", "[", "col", "]", "=", "SparseSeries", "(", "sp_values", ",", "sparse_index", "=", "sp_index", ",", "fill_value", "=", "fv", ")", "self", ".", "_data", "=", "to_manager", "(", "series_dict", ",", "columns", ",", "index", ")", "self", ".", "_default_fill_value", "=", "fv", "self", ".", "_default_kind", "=", "kind" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame.to_dense
Convert to dense DataFrame Returns ------- df : DataFrame
pandas/core/sparse/frame.py
def to_dense(self): """ Convert to dense DataFrame Returns ------- df : DataFrame """ data = {k: v.to_dense() for k, v in self.items()} return DataFrame(data, index=self.index, columns=self.columns)
def to_dense(self): """ Convert to dense DataFrame Returns ------- df : DataFrame """ data = {k: v.to_dense() for k, v in self.items()} return DataFrame(data, index=self.index, columns=self.columns)
[ "Convert", "to", "dense", "DataFrame" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L329-L338
[ "def", "to_dense", "(", "self", ")", ":", "data", "=", "{", "k", ":", "v", ".", "to_dense", "(", ")", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", "}", "return", "DataFrame", "(", "data", ",", "index", "=", "self", ".", "index", ",", "columns", "=", "self", ".", "columns", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame._apply_columns
Get new SparseDataFrame applying func to each columns
pandas/core/sparse/frame.py
def _apply_columns(self, func): """ Get new SparseDataFrame applying func to each columns """ new_data = {col: func(series) for col, series in self.items()} return self._constructor( data=new_data, index=self.index, columns=self.columns, default_fill_value=self.default_fill_value).__finalize__(self)
def _apply_columns(self, func): """ Get new SparseDataFrame applying func to each columns """ new_data = {col: func(series) for col, series in self.items()} return self._constructor( data=new_data, index=self.index, columns=self.columns, default_fill_value=self.default_fill_value).__finalize__(self)
[ "Get", "new", "SparseDataFrame", "applying", "func", "to", "each", "columns" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L340-L350
[ "def", "_apply_columns", "(", "self", ",", "func", ")", ":", "new_data", "=", "{", "col", ":", "func", "(", "series", ")", "for", "col", ",", "series", "in", "self", ".", "items", "(", ")", "}", "return", "self", ".", "_constructor", "(", "data", "=", "new_data", ",", "index", "=", "self", ".", "index", ",", "columns", "=", "self", ".", "columns", ",", "default_fill_value", "=", "self", ".", "default_fill_value", ")", ".", "__finalize__", "(", "self", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame.copy
Make a copy of this SparseDataFrame
pandas/core/sparse/frame.py
def copy(self, deep=True): """ Make a copy of this SparseDataFrame """ result = super().copy(deep=deep) result._default_fill_value = self._default_fill_value result._default_kind = self._default_kind return result
def copy(self, deep=True): """ Make a copy of this SparseDataFrame """ result = super().copy(deep=deep) result._default_fill_value = self._default_fill_value result._default_kind = self._default_kind return result
[ "Make", "a", "copy", "of", "this", "SparseDataFrame" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L355-L362
[ "def", "copy", "(", "self", ",", "deep", "=", "True", ")", ":", "result", "=", "super", "(", ")", ".", "copy", "(", "deep", "=", "deep", ")", "result", ".", "_default_fill_value", "=", "self", ".", "_default_fill_value", "result", ".", "_default_kind", "=", "self", ".", "_default_kind", "return", "result" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame.density
Ratio of non-sparse points to total (dense) data points represented in the frame
pandas/core/sparse/frame.py
def density(self): """ Ratio of non-sparse points to total (dense) data points represented in the frame """ tot_nonsparse = sum(ser.sp_index.npoints for _, ser in self.items()) tot = len(self.index) * len(self.columns) return tot_nonsparse / float(tot)
def density(self): """ Ratio of non-sparse points to total (dense) data points represented in the frame """ tot_nonsparse = sum(ser.sp_index.npoints for _, ser in self.items()) tot = len(self.index) * len(self.columns) return tot_nonsparse / float(tot)
[ "Ratio", "of", "non", "-", "sparse", "points", "to", "total", "(", "dense", ")", "data", "points", "represented", "in", "the", "frame" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L373-L381
[ "def", "density", "(", "self", ")", ":", "tot_nonsparse", "=", "sum", "(", "ser", ".", "sp_index", ".", "npoints", "for", "_", ",", "ser", "in", "self", ".", "items", "(", ")", ")", "tot", "=", "len", "(", "self", ".", "index", ")", "*", "len", "(", "self", ".", "columns", ")", "return", "tot_nonsparse", "/", "float", "(", "tot", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame._sanitize_column
Creates a new SparseArray from the input value. Parameters ---------- key : object value : scalar, Series, or array-like kwargs : dict Returns ------- sanitized_column : SparseArray
pandas/core/sparse/frame.py
def _sanitize_column(self, key, value, **kwargs): """ Creates a new SparseArray from the input value. Parameters ---------- key : object value : scalar, Series, or array-like kwargs : dict Returns ------- sanitized_column : SparseArray """ def sp_maker(x, index=None): return SparseArray(x, index=index, fill_value=self._default_fill_value, kind=self._default_kind) if isinstance(value, SparseSeries): clean = value.reindex(self.index).as_sparse_array( fill_value=self._default_fill_value, kind=self._default_kind) elif isinstance(value, SparseArray): if len(value) != len(self.index): raise ValueError('Length of values does not match ' 'length of index') clean = value elif hasattr(value, '__iter__'): if isinstance(value, Series): clean = value.reindex(self.index) if not isinstance(value, SparseSeries): clean = sp_maker(clean) else: if len(value) != len(self.index): raise ValueError('Length of values does not match ' 'length of index') clean = sp_maker(value) # Scalar else: clean = sp_maker(value, self.index) # always return a SparseArray! return clean
def _sanitize_column(self, key, value, **kwargs): """ Creates a new SparseArray from the input value. Parameters ---------- key : object value : scalar, Series, or array-like kwargs : dict Returns ------- sanitized_column : SparseArray """ def sp_maker(x, index=None): return SparseArray(x, index=index, fill_value=self._default_fill_value, kind=self._default_kind) if isinstance(value, SparseSeries): clean = value.reindex(self.index).as_sparse_array( fill_value=self._default_fill_value, kind=self._default_kind) elif isinstance(value, SparseArray): if len(value) != len(self.index): raise ValueError('Length of values does not match ' 'length of index') clean = value elif hasattr(value, '__iter__'): if isinstance(value, Series): clean = value.reindex(self.index) if not isinstance(value, SparseSeries): clean = sp_maker(clean) else: if len(value) != len(self.index): raise ValueError('Length of values does not match ' 'length of index') clean = sp_maker(value) # Scalar else: clean = sp_maker(value, self.index) # always return a SparseArray! return clean
[ "Creates", "a", "new", "SparseArray", "from", "the", "input", "value", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L403-L448
[ "def", "_sanitize_column", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "def", "sp_maker", "(", "x", ",", "index", "=", "None", ")", ":", "return", "SparseArray", "(", "x", ",", "index", "=", "index", ",", "fill_value", "=", "self", ".", "_default_fill_value", ",", "kind", "=", "self", ".", "_default_kind", ")", "if", "isinstance", "(", "value", ",", "SparseSeries", ")", ":", "clean", "=", "value", ".", "reindex", "(", "self", ".", "index", ")", ".", "as_sparse_array", "(", "fill_value", "=", "self", ".", "_default_fill_value", ",", "kind", "=", "self", ".", "_default_kind", ")", "elif", "isinstance", "(", "value", ",", "SparseArray", ")", ":", "if", "len", "(", "value", ")", "!=", "len", "(", "self", ".", "index", ")", ":", "raise", "ValueError", "(", "'Length of values does not match '", "'length of index'", ")", "clean", "=", "value", "elif", "hasattr", "(", "value", ",", "'__iter__'", ")", ":", "if", "isinstance", "(", "value", ",", "Series", ")", ":", "clean", "=", "value", ".", "reindex", "(", "self", ".", "index", ")", "if", "not", "isinstance", "(", "value", ",", "SparseSeries", ")", ":", "clean", "=", "sp_maker", "(", "clean", ")", "else", ":", "if", "len", "(", "value", ")", "!=", "len", "(", "self", ".", "index", ")", ":", "raise", "ValueError", "(", "'Length of values does not match '", "'length of index'", ")", "clean", "=", "sp_maker", "(", "value", ")", "# Scalar", "else", ":", "clean", "=", "sp_maker", "(", "value", ",", "self", ".", "index", ")", "# always return a SparseArray!", "return", "clean" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame.xs
Returns a row (cross-section) from the SparseDataFrame as a Series object. Parameters ---------- key : some index contained in the index Returns ------- xs : Series
pandas/core/sparse/frame.py
def xs(self, key, axis=0, copy=False): """ Returns a row (cross-section) from the SparseDataFrame as a Series object. Parameters ---------- key : some index contained in the index Returns ------- xs : Series """ if axis == 1: data = self[key] return data i = self.index.get_loc(key) data = self.take([i]).get_values()[0] return Series(data, index=self.columns)
def xs(self, key, axis=0, copy=False): """ Returns a row (cross-section) from the SparseDataFrame as a Series object. Parameters ---------- key : some index contained in the index Returns ------- xs : Series """ if axis == 1: data = self[key] return data i = self.index.get_loc(key) data = self.take([i]).get_values()[0] return Series(data, index=self.columns)
[ "Returns", "a", "row", "(", "cross", "-", "section", ")", "from", "the", "SparseDataFrame", "as", "a", "Series", "object", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L531-L550
[ "def", "xs", "(", "self", ",", "key", ",", "axis", "=", "0", ",", "copy", "=", "False", ")", ":", "if", "axis", "==", "1", ":", "data", "=", "self", "[", "key", "]", "return", "data", "i", "=", "self", ".", "index", ".", "get_loc", "(", "key", ")", "data", "=", "self", ".", "take", "(", "[", "i", "]", ")", ".", "get_values", "(", ")", "[", "0", "]", "return", "Series", "(", "data", ",", "index", "=", "self", ".", "columns", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame.transpose
Returns a DataFrame with the rows/columns switched.
pandas/core/sparse/frame.py
def transpose(self, *args, **kwargs): """ Returns a DataFrame with the rows/columns switched. """ nv.validate_transpose(args, kwargs) return self._constructor( self.values.T, index=self.columns, columns=self.index, default_fill_value=self._default_fill_value, default_kind=self._default_kind).__finalize__(self)
def transpose(self, *args, **kwargs): """ Returns a DataFrame with the rows/columns switched. """ nv.validate_transpose(args, kwargs) return self._constructor( self.values.T, index=self.columns, columns=self.index, default_fill_value=self._default_fill_value, default_kind=self._default_kind).__finalize__(self)
[ "Returns", "a", "DataFrame", "with", "the", "rows", "/", "columns", "switched", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L809-L817
[ "def", "transpose", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "nv", ".", "validate_transpose", "(", "args", ",", "kwargs", ")", "return", "self", ".", "_constructor", "(", "self", ".", "values", ".", "T", ",", "index", "=", "self", ".", "columns", ",", "columns", "=", "self", ".", "index", ",", "default_fill_value", "=", "self", ".", "_default_fill_value", ",", "default_kind", "=", "self", ".", "_default_kind", ")", ".", "__finalize__", "(", "self", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame.cumsum
Return SparseDataFrame of cumulative sums over requested axis. Parameters ---------- axis : {0, 1} 0 for row-wise, 1 for column-wise Returns ------- y : SparseDataFrame
pandas/core/sparse/frame.py
def cumsum(self, axis=0, *args, **kwargs): """ Return SparseDataFrame of cumulative sums over requested axis. Parameters ---------- axis : {0, 1} 0 for row-wise, 1 for column-wise Returns ------- y : SparseDataFrame """ nv.validate_cumsum(args, kwargs) if axis is None: axis = self._stat_axis_number return self.apply(lambda x: x.cumsum(), axis=axis)
def cumsum(self, axis=0, *args, **kwargs): """ Return SparseDataFrame of cumulative sums over requested axis. Parameters ---------- axis : {0, 1} 0 for row-wise, 1 for column-wise Returns ------- y : SparseDataFrame """ nv.validate_cumsum(args, kwargs) if axis is None: axis = self._stat_axis_number return self.apply(lambda x: x.cumsum(), axis=axis)
[ "Return", "SparseDataFrame", "of", "cumulative", "sums", "over", "requested", "axis", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L828-L846
[ "def", "cumsum", "(", "self", ",", "axis", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "nv", ".", "validate_cumsum", "(", "args", ",", "kwargs", ")", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "_stat_axis_number", "return", "self", ".", "apply", "(", "lambda", "x", ":", "x", ".", "cumsum", "(", ")", ",", "axis", "=", "axis", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
SparseDataFrame.apply
Analogous to DataFrame.apply, for SparseDataFrame Parameters ---------- func : function Function to apply to each column axis : {0, 1, 'index', 'columns'} broadcast : bool, default False For aggregation functions, return object of same size with values propagated .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='broadcast'. reduce : boolean or None, default None Try to apply reduction procedures. If the DataFrame is empty, apply will use reduce to determine whether the result should be a Series or a DataFrame. If reduce is None (the default), apply's return value will be guessed by calling func an empty Series (note: while guessing, exceptions raised by func will be ignored). If reduce is True a Series will always be returned, and if False a DataFrame will always be returned. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='reduce'. result_type : {'expand', 'reduce', 'broadcast, None} These only act when axis=1 {columns}: * 'expand' : list-like results will be turned into columns. * 'reduce' : return a Series if possible rather than expanding list-like results. This is the opposite to 'expand'. * 'broadcast' : results will be broadcast to the original shape of the frame, the original index & columns will be retained. The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns. .. versionadded:: 0.23.0 Returns ------- applied : Series or SparseDataFrame
pandas/core/sparse/frame.py
def apply(self, func, axis=0, broadcast=None, reduce=None, result_type=None): """ Analogous to DataFrame.apply, for SparseDataFrame Parameters ---------- func : function Function to apply to each column axis : {0, 1, 'index', 'columns'} broadcast : bool, default False For aggregation functions, return object of same size with values propagated .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='broadcast'. reduce : boolean or None, default None Try to apply reduction procedures. If the DataFrame is empty, apply will use reduce to determine whether the result should be a Series or a DataFrame. If reduce is None (the default), apply's return value will be guessed by calling func an empty Series (note: while guessing, exceptions raised by func will be ignored). If reduce is True a Series will always be returned, and if False a DataFrame will always be returned. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='reduce'. result_type : {'expand', 'reduce', 'broadcast, None} These only act when axis=1 {columns}: * 'expand' : list-like results will be turned into columns. * 'reduce' : return a Series if possible rather than expanding list-like results. This is the opposite to 'expand'. * 'broadcast' : results will be broadcast to the original shape of the frame, the original index & columns will be retained. The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns. .. versionadded:: 0.23.0 Returns ------- applied : Series or SparseDataFrame """ if not len(self.columns): return self axis = self._get_axis_number(axis) if isinstance(func, np.ufunc): new_series = {} for k, v in self.items(): applied = func(v) applied.fill_value = func(v.fill_value) new_series[k] = applied return self._constructor( new_series, index=self.index, columns=self.columns, default_fill_value=self._default_fill_value, default_kind=self._default_kind).__finalize__(self) from pandas.core.apply import frame_apply op = frame_apply(self, func=func, axis=axis, reduce=reduce, broadcast=broadcast, result_type=result_type) return op.get_result()
def apply(self, func, axis=0, broadcast=None, reduce=None, result_type=None): """ Analogous to DataFrame.apply, for SparseDataFrame Parameters ---------- func : function Function to apply to each column axis : {0, 1, 'index', 'columns'} broadcast : bool, default False For aggregation functions, return object of same size with values propagated .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='broadcast'. reduce : boolean or None, default None Try to apply reduction procedures. If the DataFrame is empty, apply will use reduce to determine whether the result should be a Series or a DataFrame. If reduce is None (the default), apply's return value will be guessed by calling func an empty Series (note: while guessing, exceptions raised by func will be ignored). If reduce is True a Series will always be returned, and if False a DataFrame will always be returned. .. deprecated:: 0.23.0 This argument will be removed in a future version, replaced by result_type='reduce'. result_type : {'expand', 'reduce', 'broadcast, None} These only act when axis=1 {columns}: * 'expand' : list-like results will be turned into columns. * 'reduce' : return a Series if possible rather than expanding list-like results. This is the opposite to 'expand'. * 'broadcast' : results will be broadcast to the original shape of the frame, the original index & columns will be retained. The default behaviour (None) depends on the return value of the applied function: list-like results will be returned as a Series of those. However if the apply function returns a Series these are expanded to columns. .. versionadded:: 0.23.0 Returns ------- applied : Series or SparseDataFrame """ if not len(self.columns): return self axis = self._get_axis_number(axis) if isinstance(func, np.ufunc): new_series = {} for k, v in self.items(): applied = func(v) applied.fill_value = func(v.fill_value) new_series[k] = applied return self._constructor( new_series, index=self.index, columns=self.columns, default_fill_value=self._default_fill_value, default_kind=self._default_kind).__finalize__(self) from pandas.core.apply import frame_apply op = frame_apply(self, func=func, axis=axis, reduce=reduce, broadcast=broadcast, result_type=result_type) return op.get_result()
[ "Analogous", "to", "DataFrame", ".", "apply", "for", "SparseDataFrame" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L858-L931
[ "def", "apply", "(", "self", ",", "func", ",", "axis", "=", "0", ",", "broadcast", "=", "None", ",", "reduce", "=", "None", ",", "result_type", "=", "None", ")", ":", "if", "not", "len", "(", "self", ".", "columns", ")", ":", "return", "self", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "if", "isinstance", "(", "func", ",", "np", ".", "ufunc", ")", ":", "new_series", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ":", "applied", "=", "func", "(", "v", ")", "applied", ".", "fill_value", "=", "func", "(", "v", ".", "fill_value", ")", "new_series", "[", "k", "]", "=", "applied", "return", "self", ".", "_constructor", "(", "new_series", ",", "index", "=", "self", ".", "index", ",", "columns", "=", "self", ".", "columns", ",", "default_fill_value", "=", "self", ".", "_default_fill_value", ",", "default_kind", "=", "self", ".", "_default_kind", ")", ".", "__finalize__", "(", "self", ")", "from", "pandas", ".", "core", ".", "apply", "import", "frame_apply", "op", "=", "frame_apply", "(", "self", ",", "func", "=", "func", ",", "axis", "=", "axis", ",", "reduce", "=", "reduce", ",", "broadcast", "=", "broadcast", ",", "result_type", "=", "result_type", ")", "return", "op", ".", "get_result", "(", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
conda_package_to_pip
Convert a conda package to its pip equivalent. In most cases they are the same, those are the exceptions: - Packages that should be excluded (in `EXCLUDE`) - Packages that should be renamed (in `RENAME`) - A package requiring a specific version, in conda is defined with a single equal (e.g. ``pandas=1.0``) and in pip with two (e.g. ``pandas==1.0``)
scripts/generate_pip_deps_from_conda.py
def conda_package_to_pip(package): """ Convert a conda package to its pip equivalent. In most cases they are the same, those are the exceptions: - Packages that should be excluded (in `EXCLUDE`) - Packages that should be renamed (in `RENAME`) - A package requiring a specific version, in conda is defined with a single equal (e.g. ``pandas=1.0``) and in pip with two (e.g. ``pandas==1.0``) """ if package in EXCLUDE: return package = re.sub('(?<=[^<>])=', '==', package).strip() for compare in ('<=', '>=', '=='): if compare not in package: continue pkg, version = package.split(compare) if pkg in RENAME: return ''.join((RENAME[pkg], compare, version)) break return package
def conda_package_to_pip(package): """ Convert a conda package to its pip equivalent. In most cases they are the same, those are the exceptions: - Packages that should be excluded (in `EXCLUDE`) - Packages that should be renamed (in `RENAME`) - A package requiring a specific version, in conda is defined with a single equal (e.g. ``pandas=1.0``) and in pip with two (e.g. ``pandas==1.0``) """ if package in EXCLUDE: return package = re.sub('(?<=[^<>])=', '==', package).strip() for compare in ('<=', '>=', '=='): if compare not in package: continue pkg, version = package.split(compare) if pkg in RENAME: return ''.join((RENAME[pkg], compare, version)) break return package
[ "Convert", "a", "conda", "package", "to", "its", "pip", "equivalent", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/scripts/generate_pip_deps_from_conda.py#L26-L51
[ "def", "conda_package_to_pip", "(", "package", ")", ":", "if", "package", "in", "EXCLUDE", ":", "return", "package", "=", "re", ".", "sub", "(", "'(?<=[^<>])='", ",", "'=='", ",", "package", ")", ".", "strip", "(", ")", "for", "compare", "in", "(", "'<='", ",", "'>='", ",", "'=='", ")", ":", "if", "compare", "not", "in", "package", ":", "continue", "pkg", ",", "version", "=", "package", ".", "split", "(", "compare", ")", "if", "pkg", "in", "RENAME", ":", "return", "''", ".", "join", "(", "(", "RENAME", "[", "pkg", "]", ",", "compare", ",", "version", ")", ")", "break", "return", "package" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
main
Generate the pip dependencies file from the conda file, or compare that they are synchronized (``compare=True``). Parameters ---------- conda_fname : str Path to the conda file with dependencies (e.g. `environment.yml`). pip_fname : str Path to the pip file with dependencies (e.g. `requirements-dev.txt`). compare : bool, default False Whether to generate the pip file (``False``) or to compare if the pip file has been generated with this script and the last version of the conda file (``True``). Returns ------- bool True if the comparison fails, False otherwise
scripts/generate_pip_deps_from_conda.py
def main(conda_fname, pip_fname, compare=False): """ Generate the pip dependencies file from the conda file, or compare that they are synchronized (``compare=True``). Parameters ---------- conda_fname : str Path to the conda file with dependencies (e.g. `environment.yml`). pip_fname : str Path to the pip file with dependencies (e.g. `requirements-dev.txt`). compare : bool, default False Whether to generate the pip file (``False``) or to compare if the pip file has been generated with this script and the last version of the conda file (``True``). Returns ------- bool True if the comparison fails, False otherwise """ with open(conda_fname) as conda_fd: deps = yaml.safe_load(conda_fd)['dependencies'] pip_deps = [] for dep in deps: if isinstance(dep, str): conda_dep = conda_package_to_pip(dep) if conda_dep: pip_deps.append(conda_dep) elif isinstance(dep, dict) and len(dep) == 1 and 'pip' in dep: pip_deps += dep['pip'] else: raise ValueError('Unexpected dependency {}'.format(dep)) pip_content = '\n'.join(pip_deps) if compare: with open(pip_fname) as pip_fd: return pip_content != pip_fd.read() else: with open(pip_fname, 'w') as pip_fd: pip_fd.write(pip_content) return False
def main(conda_fname, pip_fname, compare=False): """ Generate the pip dependencies file from the conda file, or compare that they are synchronized (``compare=True``). Parameters ---------- conda_fname : str Path to the conda file with dependencies (e.g. `environment.yml`). pip_fname : str Path to the pip file with dependencies (e.g. `requirements-dev.txt`). compare : bool, default False Whether to generate the pip file (``False``) or to compare if the pip file has been generated with this script and the last version of the conda file (``True``). Returns ------- bool True if the comparison fails, False otherwise """ with open(conda_fname) as conda_fd: deps = yaml.safe_load(conda_fd)['dependencies'] pip_deps = [] for dep in deps: if isinstance(dep, str): conda_dep = conda_package_to_pip(dep) if conda_dep: pip_deps.append(conda_dep) elif isinstance(dep, dict) and len(dep) == 1 and 'pip' in dep: pip_deps += dep['pip'] else: raise ValueError('Unexpected dependency {}'.format(dep)) pip_content = '\n'.join(pip_deps) if compare: with open(pip_fname) as pip_fd: return pip_content != pip_fd.read() else: with open(pip_fname, 'w') as pip_fd: pip_fd.write(pip_content) return False
[ "Generate", "the", "pip", "dependencies", "file", "from", "the", "conda", "file", "or", "compare", "that", "they", "are", "synchronized", "(", "compare", "=", "True", ")", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/scripts/generate_pip_deps_from_conda.py#L54-L97
[ "def", "main", "(", "conda_fname", ",", "pip_fname", ",", "compare", "=", "False", ")", ":", "with", "open", "(", "conda_fname", ")", "as", "conda_fd", ":", "deps", "=", "yaml", ".", "safe_load", "(", "conda_fd", ")", "[", "'dependencies'", "]", "pip_deps", "=", "[", "]", "for", "dep", "in", "deps", ":", "if", "isinstance", "(", "dep", ",", "str", ")", ":", "conda_dep", "=", "conda_package_to_pip", "(", "dep", ")", "if", "conda_dep", ":", "pip_deps", ".", "append", "(", "conda_dep", ")", "elif", "isinstance", "(", "dep", ",", "dict", ")", "and", "len", "(", "dep", ")", "==", "1", "and", "'pip'", "in", "dep", ":", "pip_deps", "+=", "dep", "[", "'pip'", "]", "else", ":", "raise", "ValueError", "(", "'Unexpected dependency {}'", ".", "format", "(", "dep", ")", ")", "pip_content", "=", "'\\n'", ".", "join", "(", "pip_deps", ")", "if", "compare", ":", "with", "open", "(", "pip_fname", ")", "as", "pip_fd", ":", "return", "pip_content", "!=", "pip_fd", ".", "read", "(", ")", "else", ":", "with", "open", "(", "pip_fname", ",", "'w'", ")", "as", "pip_fd", ":", "pip_fd", ".", "write", "(", "pip_content", ")", "return", "False" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_convert_platform
try to do platform conversion, allow ndarray or list here
pandas/core/dtypes/cast.py
def maybe_convert_platform(values): """ try to do platform conversion, allow ndarray or list here """ if isinstance(values, (list, tuple)): values = construct_1d_object_array_from_listlike(list(values)) if getattr(values, 'dtype', None) == np.object_: if hasattr(values, '_values'): values = values._values values = lib.maybe_convert_objects(values) return values
def maybe_convert_platform(values): """ try to do platform conversion, allow ndarray or list here """ if isinstance(values, (list, tuple)): values = construct_1d_object_array_from_listlike(list(values)) if getattr(values, 'dtype', None) == np.object_: if hasattr(values, '_values'): values = values._values values = lib.maybe_convert_objects(values) return values
[ "try", "to", "do", "platform", "conversion", "allow", "ndarray", "or", "list", "here" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L35-L45
[ "def", "maybe_convert_platform", "(", "values", ")", ":", "if", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", ":", "values", "=", "construct_1d_object_array_from_listlike", "(", "list", "(", "values", ")", ")", "if", "getattr", "(", "values", ",", "'dtype'", ",", "None", ")", "==", "np", ".", "object_", ":", "if", "hasattr", "(", "values", ",", "'_values'", ")", ":", "values", "=", "values", ".", "_values", "values", "=", "lib", ".", "maybe_convert_objects", "(", "values", ")", "return", "values" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
is_nested_object
return a boolean if we have a nested object, e.g. a Series with 1 or more Series elements This may not be necessarily be performant.
pandas/core/dtypes/cast.py
def is_nested_object(obj): """ return a boolean if we have a nested object, e.g. a Series with 1 or more Series elements This may not be necessarily be performant. """ if isinstance(obj, ABCSeries) and is_object_dtype(obj): if any(isinstance(v, ABCSeries) for v in obj.values): return True return False
def is_nested_object(obj): """ return a boolean if we have a nested object, e.g. a Series with 1 or more Series elements This may not be necessarily be performant. """ if isinstance(obj, ABCSeries) and is_object_dtype(obj): if any(isinstance(v, ABCSeries) for v in obj.values): return True return False
[ "return", "a", "boolean", "if", "we", "have", "a", "nested", "object", "e", ".", "g", ".", "a", "Series", "with", "1", "or", "more", "Series", "elements" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L48-L62
[ "def", "is_nested_object", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "ABCSeries", ")", "and", "is_object_dtype", "(", "obj", ")", ":", "if", "any", "(", "isinstance", "(", "v", ",", "ABCSeries", ")", "for", "v", "in", "obj", ".", "values", ")", ":", "return", "True", "return", "False" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_downcast_to_dtype
try to cast to the specified dtype (e.g. convert back to bool/int or could be an astype of float64->float32
pandas/core/dtypes/cast.py
def maybe_downcast_to_dtype(result, dtype): """ try to cast to the specified dtype (e.g. convert back to bool/int or could be an astype of float64->float32 """ if is_scalar(result): return result def trans(x): return x if isinstance(dtype, str): if dtype == 'infer': inferred_type = lib.infer_dtype(ensure_object(result.ravel()), skipna=False) if inferred_type == 'boolean': dtype = 'bool' elif inferred_type == 'integer': dtype = 'int64' elif inferred_type == 'datetime64': dtype = 'datetime64[ns]' elif inferred_type == 'timedelta64': dtype = 'timedelta64[ns]' # try to upcast here elif inferred_type == 'floating': dtype = 'int64' if issubclass(result.dtype.type, np.number): def trans(x): # noqa return x.round() else: dtype = 'object' if isinstance(dtype, str): dtype = np.dtype(dtype) try: # don't allow upcasts here (except if empty) if dtype.kind == result.dtype.kind: if (result.dtype.itemsize <= dtype.itemsize and np.prod(result.shape)): return result if is_bool_dtype(dtype) or is_integer_dtype(dtype): # if we don't have any elements, just astype it if not np.prod(result.shape): return trans(result).astype(dtype) # do a test on the first element, if it fails then we are done r = result.ravel() arr = np.array([r[0]]) # if we have any nulls, then we are done if (isna(arr).any() or not np.allclose(arr, trans(arr).astype(dtype), rtol=0)): return result # a comparable, e.g. a Decimal may slip in here elif not isinstance(r[0], (np.integer, np.floating, np.bool, int, float, bool)): return result if (issubclass(result.dtype.type, (np.object_, np.number)) and notna(result).all()): new_result = trans(result).astype(dtype) try: if np.allclose(new_result, result, rtol=0): return new_result except Exception: # comparison of an object dtype with a number type could # hit here if (new_result == result).all(): return new_result elif (issubclass(dtype.type, np.floating) and not is_bool_dtype(result.dtype)): return result.astype(dtype) # a datetimelike # GH12821, iNaT is casted to float elif dtype.kind in ['M', 'm'] and result.dtype.kind in ['i', 'f']: try: result = result.astype(dtype) except Exception: if dtype.tz: # convert to datetime and change timezone from pandas import to_datetime result = to_datetime(result).tz_localize('utc') result = result.tz_convert(dtype.tz) elif dtype.type == Period: # TODO(DatetimeArray): merge with previous elif from pandas.core.arrays import PeriodArray return PeriodArray(result, freq=dtype.freq) except Exception: pass return result
def maybe_downcast_to_dtype(result, dtype): """ try to cast to the specified dtype (e.g. convert back to bool/int or could be an astype of float64->float32 """ if is_scalar(result): return result def trans(x): return x if isinstance(dtype, str): if dtype == 'infer': inferred_type = lib.infer_dtype(ensure_object(result.ravel()), skipna=False) if inferred_type == 'boolean': dtype = 'bool' elif inferred_type == 'integer': dtype = 'int64' elif inferred_type == 'datetime64': dtype = 'datetime64[ns]' elif inferred_type == 'timedelta64': dtype = 'timedelta64[ns]' # try to upcast here elif inferred_type == 'floating': dtype = 'int64' if issubclass(result.dtype.type, np.number): def trans(x): # noqa return x.round() else: dtype = 'object' if isinstance(dtype, str): dtype = np.dtype(dtype) try: # don't allow upcasts here (except if empty) if dtype.kind == result.dtype.kind: if (result.dtype.itemsize <= dtype.itemsize and np.prod(result.shape)): return result if is_bool_dtype(dtype) or is_integer_dtype(dtype): # if we don't have any elements, just astype it if not np.prod(result.shape): return trans(result).astype(dtype) # do a test on the first element, if it fails then we are done r = result.ravel() arr = np.array([r[0]]) # if we have any nulls, then we are done if (isna(arr).any() or not np.allclose(arr, trans(arr).astype(dtype), rtol=0)): return result # a comparable, e.g. a Decimal may slip in here elif not isinstance(r[0], (np.integer, np.floating, np.bool, int, float, bool)): return result if (issubclass(result.dtype.type, (np.object_, np.number)) and notna(result).all()): new_result = trans(result).astype(dtype) try: if np.allclose(new_result, result, rtol=0): return new_result except Exception: # comparison of an object dtype with a number type could # hit here if (new_result == result).all(): return new_result elif (issubclass(dtype.type, np.floating) and not is_bool_dtype(result.dtype)): return result.astype(dtype) # a datetimelike # GH12821, iNaT is casted to float elif dtype.kind in ['M', 'm'] and result.dtype.kind in ['i', 'f']: try: result = result.astype(dtype) except Exception: if dtype.tz: # convert to datetime and change timezone from pandas import to_datetime result = to_datetime(result).tz_localize('utc') result = result.tz_convert(dtype.tz) elif dtype.type == Period: # TODO(DatetimeArray): merge with previous elif from pandas.core.arrays import PeriodArray return PeriodArray(result, freq=dtype.freq) except Exception: pass return result
[ "try", "to", "cast", "to", "the", "specified", "dtype", "(", "e", ".", "g", ".", "convert", "back", "to", "bool", "/", "int", "or", "could", "be", "an", "astype", "of", "float64", "-", ">", "float32" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L65-L167
[ "def", "maybe_downcast_to_dtype", "(", "result", ",", "dtype", ")", ":", "if", "is_scalar", "(", "result", ")", ":", "return", "result", "def", "trans", "(", "x", ")", ":", "return", "x", "if", "isinstance", "(", "dtype", ",", "str", ")", ":", "if", "dtype", "==", "'infer'", ":", "inferred_type", "=", "lib", ".", "infer_dtype", "(", "ensure_object", "(", "result", ".", "ravel", "(", ")", ")", ",", "skipna", "=", "False", ")", "if", "inferred_type", "==", "'boolean'", ":", "dtype", "=", "'bool'", "elif", "inferred_type", "==", "'integer'", ":", "dtype", "=", "'int64'", "elif", "inferred_type", "==", "'datetime64'", ":", "dtype", "=", "'datetime64[ns]'", "elif", "inferred_type", "==", "'timedelta64'", ":", "dtype", "=", "'timedelta64[ns]'", "# try to upcast here", "elif", "inferred_type", "==", "'floating'", ":", "dtype", "=", "'int64'", "if", "issubclass", "(", "result", ".", "dtype", ".", "type", ",", "np", ".", "number", ")", ":", "def", "trans", "(", "x", ")", ":", "# noqa", "return", "x", ".", "round", "(", ")", "else", ":", "dtype", "=", "'object'", "if", "isinstance", "(", "dtype", ",", "str", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "dtype", ")", "try", ":", "# don't allow upcasts here (except if empty)", "if", "dtype", ".", "kind", "==", "result", ".", "dtype", ".", "kind", ":", "if", "(", "result", ".", "dtype", ".", "itemsize", "<=", "dtype", ".", "itemsize", "and", "np", ".", "prod", "(", "result", ".", "shape", ")", ")", ":", "return", "result", "if", "is_bool_dtype", "(", "dtype", ")", "or", "is_integer_dtype", "(", "dtype", ")", ":", "# if we don't have any elements, just astype it", "if", "not", "np", ".", "prod", "(", "result", ".", "shape", ")", ":", "return", "trans", "(", "result", ")", ".", "astype", "(", "dtype", ")", "# do a test on the first element, if it fails then we are done", "r", "=", "result", ".", "ravel", "(", ")", "arr", "=", "np", ".", "array", "(", "[", "r", "[", "0", "]", "]", ")", "# if we have any nulls, then we are done", "if", "(", "isna", "(", "arr", ")", ".", "any", "(", ")", "or", "not", "np", ".", "allclose", "(", "arr", ",", "trans", "(", "arr", ")", ".", "astype", "(", "dtype", ")", ",", "rtol", "=", "0", ")", ")", ":", "return", "result", "# a comparable, e.g. a Decimal may slip in here", "elif", "not", "isinstance", "(", "r", "[", "0", "]", ",", "(", "np", ".", "integer", ",", "np", ".", "floating", ",", "np", ".", "bool", ",", "int", ",", "float", ",", "bool", ")", ")", ":", "return", "result", "if", "(", "issubclass", "(", "result", ".", "dtype", ".", "type", ",", "(", "np", ".", "object_", ",", "np", ".", "number", ")", ")", "and", "notna", "(", "result", ")", ".", "all", "(", ")", ")", ":", "new_result", "=", "trans", "(", "result", ")", ".", "astype", "(", "dtype", ")", "try", ":", "if", "np", ".", "allclose", "(", "new_result", ",", "result", ",", "rtol", "=", "0", ")", ":", "return", "new_result", "except", "Exception", ":", "# comparison of an object dtype with a number type could", "# hit here", "if", "(", "new_result", "==", "result", ")", ".", "all", "(", ")", ":", "return", "new_result", "elif", "(", "issubclass", "(", "dtype", ".", "type", ",", "np", ".", "floating", ")", "and", "not", "is_bool_dtype", "(", "result", ".", "dtype", ")", ")", ":", "return", "result", ".", "astype", "(", "dtype", ")", "# a datetimelike", "# GH12821, iNaT is casted to float", "elif", "dtype", ".", "kind", "in", "[", "'M'", ",", "'m'", "]", "and", "result", ".", "dtype", ".", "kind", "in", "[", "'i'", ",", "'f'", "]", ":", "try", ":", "result", "=", "result", ".", "astype", "(", "dtype", ")", "except", "Exception", ":", "if", "dtype", ".", "tz", ":", "# convert to datetime and change timezone", "from", "pandas", "import", "to_datetime", "result", "=", "to_datetime", "(", "result", ")", ".", "tz_localize", "(", "'utc'", ")", "result", "=", "result", ".", "tz_convert", "(", "dtype", ".", "tz", ")", "elif", "dtype", ".", "type", "==", "Period", ":", "# TODO(DatetimeArray): merge with previous elif", "from", "pandas", ".", "core", ".", "arrays", "import", "PeriodArray", "return", "PeriodArray", "(", "result", ",", "freq", "=", "dtype", ".", "freq", ")", "except", "Exception", ":", "pass", "return", "result" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_upcast_putmask
A safe version of putmask that potentially upcasts the result. The result is replaced with the first N elements of other, where N is the number of True values in mask. If the length of other is shorter than N, other will be repeated. Parameters ---------- result : ndarray The destination array. This will be mutated in-place if no upcasting is necessary. mask : boolean ndarray other : ndarray or scalar The source array or value Returns ------- result : ndarray changed : boolean Set to true if the result array was upcasted Examples -------- >>> result, _ = maybe_upcast_putmask(np.arange(1,6), np.array([False, True, False, True, True]), np.arange(21,23)) >>> result array([1, 21, 3, 22, 21])
pandas/core/dtypes/cast.py
def maybe_upcast_putmask(result, mask, other): """ A safe version of putmask that potentially upcasts the result. The result is replaced with the first N elements of other, where N is the number of True values in mask. If the length of other is shorter than N, other will be repeated. Parameters ---------- result : ndarray The destination array. This will be mutated in-place if no upcasting is necessary. mask : boolean ndarray other : ndarray or scalar The source array or value Returns ------- result : ndarray changed : boolean Set to true if the result array was upcasted Examples -------- >>> result, _ = maybe_upcast_putmask(np.arange(1,6), np.array([False, True, False, True, True]), np.arange(21,23)) >>> result array([1, 21, 3, 22, 21]) """ if not isinstance(result, np.ndarray): raise ValueError("The result input must be a ndarray.") if mask.any(): # Two conversions for date-like dtypes that can't be done automatically # in np.place: # NaN -> NaT # integer or integer array -> date-like array if is_datetimelike(result.dtype): if is_scalar(other): if isna(other): other = result.dtype.type('nat') elif is_integer(other): other = np.array(other, dtype=result.dtype) elif is_integer_dtype(other): other = np.array(other, dtype=result.dtype) def changeit(): # try to directly set by expanding our array to full # length of the boolean try: om = other[mask] om_at = om.astype(result.dtype) if (om == om_at).all(): new_result = result.values.copy() new_result[mask] = om_at result[:] = new_result return result, False except Exception: pass # we are forced to change the dtype of the result as the input # isn't compatible r, _ = maybe_upcast(result, fill_value=other, copy=True) np.place(r, mask, other) return r, True # we want to decide whether place will work # if we have nans in the False portion of our mask then we need to # upcast (possibly), otherwise we DON't want to upcast (e.g. if we # have values, say integers, in the success portion then it's ok to not # upcast) new_dtype, _ = maybe_promote(result.dtype, other) if new_dtype != result.dtype: # we have a scalar or len 0 ndarray # and its nan and we are changing some values if (is_scalar(other) or (isinstance(other, np.ndarray) and other.ndim < 1)): if isna(other): return changeit() # we have an ndarray and the masking has nans in it else: if isna(other).any(): return changeit() try: np.place(result, mask, other) except Exception: return changeit() return result, False
def maybe_upcast_putmask(result, mask, other): """ A safe version of putmask that potentially upcasts the result. The result is replaced with the first N elements of other, where N is the number of True values in mask. If the length of other is shorter than N, other will be repeated. Parameters ---------- result : ndarray The destination array. This will be mutated in-place if no upcasting is necessary. mask : boolean ndarray other : ndarray or scalar The source array or value Returns ------- result : ndarray changed : boolean Set to true if the result array was upcasted Examples -------- >>> result, _ = maybe_upcast_putmask(np.arange(1,6), np.array([False, True, False, True, True]), np.arange(21,23)) >>> result array([1, 21, 3, 22, 21]) """ if not isinstance(result, np.ndarray): raise ValueError("The result input must be a ndarray.") if mask.any(): # Two conversions for date-like dtypes that can't be done automatically # in np.place: # NaN -> NaT # integer or integer array -> date-like array if is_datetimelike(result.dtype): if is_scalar(other): if isna(other): other = result.dtype.type('nat') elif is_integer(other): other = np.array(other, dtype=result.dtype) elif is_integer_dtype(other): other = np.array(other, dtype=result.dtype) def changeit(): # try to directly set by expanding our array to full # length of the boolean try: om = other[mask] om_at = om.astype(result.dtype) if (om == om_at).all(): new_result = result.values.copy() new_result[mask] = om_at result[:] = new_result return result, False except Exception: pass # we are forced to change the dtype of the result as the input # isn't compatible r, _ = maybe_upcast(result, fill_value=other, copy=True) np.place(r, mask, other) return r, True # we want to decide whether place will work # if we have nans in the False portion of our mask then we need to # upcast (possibly), otherwise we DON't want to upcast (e.g. if we # have values, say integers, in the success portion then it's ok to not # upcast) new_dtype, _ = maybe_promote(result.dtype, other) if new_dtype != result.dtype: # we have a scalar or len 0 ndarray # and its nan and we are changing some values if (is_scalar(other) or (isinstance(other, np.ndarray) and other.ndim < 1)): if isna(other): return changeit() # we have an ndarray and the masking has nans in it else: if isna(other).any(): return changeit() try: np.place(result, mask, other) except Exception: return changeit() return result, False
[ "A", "safe", "version", "of", "putmask", "that", "potentially", "upcasts", "the", "result", ".", "The", "result", "is", "replaced", "with", "the", "first", "N", "elements", "of", "other", "where", "N", "is", "the", "number", "of", "True", "values", "in", "mask", ".", "If", "the", "length", "of", "other", "is", "shorter", "than", "N", "other", "will", "be", "repeated", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L170-L265
[ "def", "maybe_upcast_putmask", "(", "result", ",", "mask", ",", "other", ")", ":", "if", "not", "isinstance", "(", "result", ",", "np", ".", "ndarray", ")", ":", "raise", "ValueError", "(", "\"The result input must be a ndarray.\"", ")", "if", "mask", ".", "any", "(", ")", ":", "# Two conversions for date-like dtypes that can't be done automatically", "# in np.place:", "# NaN -> NaT", "# integer or integer array -> date-like array", "if", "is_datetimelike", "(", "result", ".", "dtype", ")", ":", "if", "is_scalar", "(", "other", ")", ":", "if", "isna", "(", "other", ")", ":", "other", "=", "result", ".", "dtype", ".", "type", "(", "'nat'", ")", "elif", "is_integer", "(", "other", ")", ":", "other", "=", "np", ".", "array", "(", "other", ",", "dtype", "=", "result", ".", "dtype", ")", "elif", "is_integer_dtype", "(", "other", ")", ":", "other", "=", "np", ".", "array", "(", "other", ",", "dtype", "=", "result", ".", "dtype", ")", "def", "changeit", "(", ")", ":", "# try to directly set by expanding our array to full", "# length of the boolean", "try", ":", "om", "=", "other", "[", "mask", "]", "om_at", "=", "om", ".", "astype", "(", "result", ".", "dtype", ")", "if", "(", "om", "==", "om_at", ")", ".", "all", "(", ")", ":", "new_result", "=", "result", ".", "values", ".", "copy", "(", ")", "new_result", "[", "mask", "]", "=", "om_at", "result", "[", ":", "]", "=", "new_result", "return", "result", ",", "False", "except", "Exception", ":", "pass", "# we are forced to change the dtype of the result as the input", "# isn't compatible", "r", ",", "_", "=", "maybe_upcast", "(", "result", ",", "fill_value", "=", "other", ",", "copy", "=", "True", ")", "np", ".", "place", "(", "r", ",", "mask", ",", "other", ")", "return", "r", ",", "True", "# we want to decide whether place will work", "# if we have nans in the False portion of our mask then we need to", "# upcast (possibly), otherwise we DON't want to upcast (e.g. if we", "# have values, say integers, in the success portion then it's ok to not", "# upcast)", "new_dtype", ",", "_", "=", "maybe_promote", "(", "result", ".", "dtype", ",", "other", ")", "if", "new_dtype", "!=", "result", ".", "dtype", ":", "# we have a scalar or len 0 ndarray", "# and its nan and we are changing some values", "if", "(", "is_scalar", "(", "other", ")", "or", "(", "isinstance", "(", "other", ",", "np", ".", "ndarray", ")", "and", "other", ".", "ndim", "<", "1", ")", ")", ":", "if", "isna", "(", "other", ")", ":", "return", "changeit", "(", ")", "# we have an ndarray and the masking has nans in it", "else", ":", "if", "isna", "(", "other", ")", ".", "any", "(", ")", ":", "return", "changeit", "(", ")", "try", ":", "np", ".", "place", "(", "result", ",", "mask", ",", "other", ")", "except", "Exception", ":", "return", "changeit", "(", ")", "return", "result", ",", "False" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
infer_dtype_from
interpret the dtype from a scalar or array. This is a convenience routines to infer dtype from a scalar or an array Parameters ---------- pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, scalar/array belongs to pandas extension types is inferred as object
pandas/core/dtypes/cast.py
def infer_dtype_from(val, pandas_dtype=False): """ interpret the dtype from a scalar or array. This is a convenience routines to infer dtype from a scalar or an array Parameters ---------- pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, scalar/array belongs to pandas extension types is inferred as object """ if is_scalar(val): return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype) return infer_dtype_from_array(val, pandas_dtype=pandas_dtype)
def infer_dtype_from(val, pandas_dtype=False): """ interpret the dtype from a scalar or array. This is a convenience routines to infer dtype from a scalar or an array Parameters ---------- pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, scalar/array belongs to pandas extension types is inferred as object """ if is_scalar(val): return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype) return infer_dtype_from_array(val, pandas_dtype=pandas_dtype)
[ "interpret", "the", "dtype", "from", "a", "scalar", "or", "array", ".", "This", "is", "a", "convenience", "routines", "to", "infer", "dtype", "from", "a", "scalar", "or", "an", "array" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L337-L351
[ "def", "infer_dtype_from", "(", "val", ",", "pandas_dtype", "=", "False", ")", ":", "if", "is_scalar", "(", "val", ")", ":", "return", "infer_dtype_from_scalar", "(", "val", ",", "pandas_dtype", "=", "pandas_dtype", ")", "return", "infer_dtype_from_array", "(", "val", ",", "pandas_dtype", "=", "pandas_dtype", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
infer_dtype_from_scalar
interpret the dtype from a scalar Parameters ---------- pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, scalar belongs to pandas extension types is inferred as object
pandas/core/dtypes/cast.py
def infer_dtype_from_scalar(val, pandas_dtype=False): """ interpret the dtype from a scalar Parameters ---------- pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, scalar belongs to pandas extension types is inferred as object """ dtype = np.object_ # a 1-element ndarray if isinstance(val, np.ndarray): msg = "invalid ndarray passed to infer_dtype_from_scalar" if val.ndim != 0: raise ValueError(msg) dtype = val.dtype val = val.item() elif isinstance(val, str): # If we create an empty array using a string to infer # the dtype, NumPy will only allocate one character per entry # so this is kind of bad. Alternately we could use np.repeat # instead of np.empty (but then you still don't want things # coming out as np.str_! dtype = np.object_ elif isinstance(val, (np.datetime64, datetime)): val = tslibs.Timestamp(val) if val is tslibs.NaT or val.tz is None: dtype = np.dtype('M8[ns]') else: if pandas_dtype: dtype = DatetimeTZDtype(unit='ns', tz=val.tz) else: # return datetimetz as object return np.object_, val val = val.value elif isinstance(val, (np.timedelta64, timedelta)): val = tslibs.Timedelta(val).value dtype = np.dtype('m8[ns]') elif is_bool(val): dtype = np.bool_ elif is_integer(val): if isinstance(val, np.integer): dtype = type(val) else: dtype = np.int64 elif is_float(val): if isinstance(val, np.floating): dtype = type(val) else: dtype = np.float64 elif is_complex(val): dtype = np.complex_ elif pandas_dtype: if lib.is_period(val): dtype = PeriodDtype(freq=val.freq) val = val.ordinal return dtype, val
def infer_dtype_from_scalar(val, pandas_dtype=False): """ interpret the dtype from a scalar Parameters ---------- pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, scalar belongs to pandas extension types is inferred as object """ dtype = np.object_ # a 1-element ndarray if isinstance(val, np.ndarray): msg = "invalid ndarray passed to infer_dtype_from_scalar" if val.ndim != 0: raise ValueError(msg) dtype = val.dtype val = val.item() elif isinstance(val, str): # If we create an empty array using a string to infer # the dtype, NumPy will only allocate one character per entry # so this is kind of bad. Alternately we could use np.repeat # instead of np.empty (but then you still don't want things # coming out as np.str_! dtype = np.object_ elif isinstance(val, (np.datetime64, datetime)): val = tslibs.Timestamp(val) if val is tslibs.NaT or val.tz is None: dtype = np.dtype('M8[ns]') else: if pandas_dtype: dtype = DatetimeTZDtype(unit='ns', tz=val.tz) else: # return datetimetz as object return np.object_, val val = val.value elif isinstance(val, (np.timedelta64, timedelta)): val = tslibs.Timedelta(val).value dtype = np.dtype('m8[ns]') elif is_bool(val): dtype = np.bool_ elif is_integer(val): if isinstance(val, np.integer): dtype = type(val) else: dtype = np.int64 elif is_float(val): if isinstance(val, np.floating): dtype = type(val) else: dtype = np.float64 elif is_complex(val): dtype = np.complex_ elif pandas_dtype: if lib.is_period(val): dtype = PeriodDtype(freq=val.freq) val = val.ordinal return dtype, val
[ "interpret", "the", "dtype", "from", "a", "scalar" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L354-L426
[ "def", "infer_dtype_from_scalar", "(", "val", ",", "pandas_dtype", "=", "False", ")", ":", "dtype", "=", "np", ".", "object_", "# a 1-element ndarray", "if", "isinstance", "(", "val", ",", "np", ".", "ndarray", ")", ":", "msg", "=", "\"invalid ndarray passed to infer_dtype_from_scalar\"", "if", "val", ".", "ndim", "!=", "0", ":", "raise", "ValueError", "(", "msg", ")", "dtype", "=", "val", ".", "dtype", "val", "=", "val", ".", "item", "(", ")", "elif", "isinstance", "(", "val", ",", "str", ")", ":", "# If we create an empty array using a string to infer", "# the dtype, NumPy will only allocate one character per entry", "# so this is kind of bad. Alternately we could use np.repeat", "# instead of np.empty (but then you still don't want things", "# coming out as np.str_!", "dtype", "=", "np", ".", "object_", "elif", "isinstance", "(", "val", ",", "(", "np", ".", "datetime64", ",", "datetime", ")", ")", ":", "val", "=", "tslibs", ".", "Timestamp", "(", "val", ")", "if", "val", "is", "tslibs", ".", "NaT", "or", "val", ".", "tz", "is", "None", ":", "dtype", "=", "np", ".", "dtype", "(", "'M8[ns]'", ")", "else", ":", "if", "pandas_dtype", ":", "dtype", "=", "DatetimeTZDtype", "(", "unit", "=", "'ns'", ",", "tz", "=", "val", ".", "tz", ")", "else", ":", "# return datetimetz as object", "return", "np", ".", "object_", ",", "val", "val", "=", "val", ".", "value", "elif", "isinstance", "(", "val", ",", "(", "np", ".", "timedelta64", ",", "timedelta", ")", ")", ":", "val", "=", "tslibs", ".", "Timedelta", "(", "val", ")", ".", "value", "dtype", "=", "np", ".", "dtype", "(", "'m8[ns]'", ")", "elif", "is_bool", "(", "val", ")", ":", "dtype", "=", "np", ".", "bool_", "elif", "is_integer", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "np", ".", "integer", ")", ":", "dtype", "=", "type", "(", "val", ")", "else", ":", "dtype", "=", "np", ".", "int64", "elif", "is_float", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "np", ".", "floating", ")", ":", "dtype", "=", "type", "(", "val", ")", "else", ":", "dtype", "=", "np", ".", "float64", "elif", "is_complex", "(", "val", ")", ":", "dtype", "=", "np", ".", "complex_", "elif", "pandas_dtype", ":", "if", "lib", ".", "is_period", "(", "val", ")", ":", "dtype", "=", "PeriodDtype", "(", "freq", "=", "val", ".", "freq", ")", "val", "=", "val", ".", "ordinal", "return", "dtype", ",", "val" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
infer_dtype_from_array
infer the dtype from a scalar or array Parameters ---------- arr : scalar or array pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, array belongs to pandas extension types is inferred as object Returns ------- tuple (numpy-compat/pandas-compat dtype, array) Notes ----- if pandas_dtype=False. these infer to numpy dtypes exactly with the exception that mixed / object dtypes are not coerced by stringifying or conversion if pandas_dtype=True. datetime64tz-aware/categorical types will retain there character. Examples -------- >>> np.asarray([1, '1']) array(['1', '1'], dtype='<U21') >>> infer_dtype_from_array([1, '1']) (numpy.object_, [1, '1'])
pandas/core/dtypes/cast.py
def infer_dtype_from_array(arr, pandas_dtype=False): """ infer the dtype from a scalar or array Parameters ---------- arr : scalar or array pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, array belongs to pandas extension types is inferred as object Returns ------- tuple (numpy-compat/pandas-compat dtype, array) Notes ----- if pandas_dtype=False. these infer to numpy dtypes exactly with the exception that mixed / object dtypes are not coerced by stringifying or conversion if pandas_dtype=True. datetime64tz-aware/categorical types will retain there character. Examples -------- >>> np.asarray([1, '1']) array(['1', '1'], dtype='<U21') >>> infer_dtype_from_array([1, '1']) (numpy.object_, [1, '1']) """ if isinstance(arr, np.ndarray): return arr.dtype, arr if not is_list_like(arr): arr = [arr] if pandas_dtype and is_extension_type(arr): return arr.dtype, arr elif isinstance(arr, ABCSeries): return arr.dtype, np.asarray(arr) # don't force numpy coerce with nan's inferred = lib.infer_dtype(arr, skipna=False) if inferred in ['string', 'bytes', 'unicode', 'mixed', 'mixed-integer']: return (np.object_, arr) arr = np.asarray(arr) return arr.dtype, arr
def infer_dtype_from_array(arr, pandas_dtype=False): """ infer the dtype from a scalar or array Parameters ---------- arr : scalar or array pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, array belongs to pandas extension types is inferred as object Returns ------- tuple (numpy-compat/pandas-compat dtype, array) Notes ----- if pandas_dtype=False. these infer to numpy dtypes exactly with the exception that mixed / object dtypes are not coerced by stringifying or conversion if pandas_dtype=True. datetime64tz-aware/categorical types will retain there character. Examples -------- >>> np.asarray([1, '1']) array(['1', '1'], dtype='<U21') >>> infer_dtype_from_array([1, '1']) (numpy.object_, [1, '1']) """ if isinstance(arr, np.ndarray): return arr.dtype, arr if not is_list_like(arr): arr = [arr] if pandas_dtype and is_extension_type(arr): return arr.dtype, arr elif isinstance(arr, ABCSeries): return arr.dtype, np.asarray(arr) # don't force numpy coerce with nan's inferred = lib.infer_dtype(arr, skipna=False) if inferred in ['string', 'bytes', 'unicode', 'mixed', 'mixed-integer']: return (np.object_, arr) arr = np.asarray(arr) return arr.dtype, arr
[ "infer", "the", "dtype", "from", "a", "scalar", "or", "array" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L429-L483
[ "def", "infer_dtype_from_array", "(", "arr", ",", "pandas_dtype", "=", "False", ")", ":", "if", "isinstance", "(", "arr", ",", "np", ".", "ndarray", ")", ":", "return", "arr", ".", "dtype", ",", "arr", "if", "not", "is_list_like", "(", "arr", ")", ":", "arr", "=", "[", "arr", "]", "if", "pandas_dtype", "and", "is_extension_type", "(", "arr", ")", ":", "return", "arr", ".", "dtype", ",", "arr", "elif", "isinstance", "(", "arr", ",", "ABCSeries", ")", ":", "return", "arr", ".", "dtype", ",", "np", ".", "asarray", "(", "arr", ")", "# don't force numpy coerce with nan's", "inferred", "=", "lib", ".", "infer_dtype", "(", "arr", ",", "skipna", "=", "False", ")", "if", "inferred", "in", "[", "'string'", ",", "'bytes'", ",", "'unicode'", ",", "'mixed'", ",", "'mixed-integer'", "]", ":", "return", "(", "np", ".", "object_", ",", "arr", ")", "arr", "=", "np", ".", "asarray", "(", "arr", ")", "return", "arr", ".", "dtype", ",", "arr" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_infer_dtype_type
Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object Possibly has a `.dtype` attribute, and possibly the iterator protocol. Returns ------- tipo : type Examples -------- >>> from collections import namedtuple >>> Foo = namedtuple("Foo", "dtype") >>> maybe_infer_dtype_type(Foo(np.dtype("i8"))) numpy.int64
pandas/core/dtypes/cast.py
def maybe_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object Possibly has a `.dtype` attribute, and possibly the iterator protocol. Returns ------- tipo : type Examples -------- >>> from collections import namedtuple >>> Foo = namedtuple("Foo", "dtype") >>> maybe_infer_dtype_type(Foo(np.dtype("i8"))) numpy.int64 """ tipo = None if hasattr(element, 'dtype'): tipo = element.dtype elif is_list_like(element): element = np.asarray(element) tipo = element.dtype return tipo
def maybe_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object Possibly has a `.dtype` attribute, and possibly the iterator protocol. Returns ------- tipo : type Examples -------- >>> from collections import namedtuple >>> Foo = namedtuple("Foo", "dtype") >>> maybe_infer_dtype_type(Foo(np.dtype("i8"))) numpy.int64 """ tipo = None if hasattr(element, 'dtype'): tipo = element.dtype elif is_list_like(element): element = np.asarray(element) tipo = element.dtype return tipo
[ "Try", "to", "infer", "an", "object", "s", "dtype", "for", "use", "in", "arithmetic", "ops" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L486-L516
[ "def", "maybe_infer_dtype_type", "(", "element", ")", ":", "tipo", "=", "None", "if", "hasattr", "(", "element", ",", "'dtype'", ")", ":", "tipo", "=", "element", ".", "dtype", "elif", "is_list_like", "(", "element", ")", ":", "element", "=", "np", ".", "asarray", "(", "element", ")", "tipo", "=", "element", ".", "dtype", "return", "tipo" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_upcast
provide explicit type promotion and coercion Parameters ---------- values : the ndarray that we want to maybe upcast fill_value : what we want to fill with dtype : if None, then use the dtype of the values, else coerce to this type copy : if True always make a copy even if no upcast is required
pandas/core/dtypes/cast.py
def maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False): """ provide explicit type promotion and coercion Parameters ---------- values : the ndarray that we want to maybe upcast fill_value : what we want to fill with dtype : if None, then use the dtype of the values, else coerce to this type copy : if True always make a copy even if no upcast is required """ if is_extension_type(values): if copy: values = values.copy() else: if dtype is None: dtype = values.dtype new_dtype, fill_value = maybe_promote(dtype, fill_value) if new_dtype != values.dtype: values = values.astype(new_dtype) elif copy: values = values.copy() return values, fill_value
def maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False): """ provide explicit type promotion and coercion Parameters ---------- values : the ndarray that we want to maybe upcast fill_value : what we want to fill with dtype : if None, then use the dtype of the values, else coerce to this type copy : if True always make a copy even if no upcast is required """ if is_extension_type(values): if copy: values = values.copy() else: if dtype is None: dtype = values.dtype new_dtype, fill_value = maybe_promote(dtype, fill_value) if new_dtype != values.dtype: values = values.astype(new_dtype) elif copy: values = values.copy() return values, fill_value
[ "provide", "explicit", "type", "promotion", "and", "coercion" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L519-L542
[ "def", "maybe_upcast", "(", "values", ",", "fill_value", "=", "np", ".", "nan", ",", "dtype", "=", "None", ",", "copy", "=", "False", ")", ":", "if", "is_extension_type", "(", "values", ")", ":", "if", "copy", ":", "values", "=", "values", ".", "copy", "(", ")", "else", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "values", ".", "dtype", "new_dtype", ",", "fill_value", "=", "maybe_promote", "(", "dtype", ",", "fill_value", ")", "if", "new_dtype", "!=", "values", ".", "dtype", ":", "values", "=", "values", ".", "astype", "(", "new_dtype", ")", "elif", "copy", ":", "values", "=", "values", ".", "copy", "(", ")", "return", "values", ",", "fill_value" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
invalidate_string_dtypes
Change string like dtypes to object for ``DataFrame.select_dtypes()``.
pandas/core/dtypes/cast.py
def invalidate_string_dtypes(dtype_set): """Change string like dtypes to object for ``DataFrame.select_dtypes()``. """ non_string_dtypes = dtype_set - {np.dtype('S').type, np.dtype('<U').type} if non_string_dtypes != dtype_set: raise TypeError("string dtypes are not allowed, use 'object' instead")
def invalidate_string_dtypes(dtype_set): """Change string like dtypes to object for ``DataFrame.select_dtypes()``. """ non_string_dtypes = dtype_set - {np.dtype('S').type, np.dtype('<U').type} if non_string_dtypes != dtype_set: raise TypeError("string dtypes are not allowed, use 'object' instead")
[ "Change", "string", "like", "dtypes", "to", "object", "for", "DataFrame", ".", "select_dtypes", "()", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L556-L562
[ "def", "invalidate_string_dtypes", "(", "dtype_set", ")", ":", "non_string_dtypes", "=", "dtype_set", "-", "{", "np", ".", "dtype", "(", "'S'", ")", ".", "type", ",", "np", ".", "dtype", "(", "'<U'", ")", ".", "type", "}", "if", "non_string_dtypes", "!=", "dtype_set", ":", "raise", "TypeError", "(", "\"string dtypes are not allowed, use 'object' instead\"", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
coerce_indexer_dtype
coerce the indexer input array to the smallest dtype possible
pandas/core/dtypes/cast.py
def coerce_indexer_dtype(indexer, categories): """ coerce the indexer input array to the smallest dtype possible """ length = len(categories) if length < _int8_max: return ensure_int8(indexer) elif length < _int16_max: return ensure_int16(indexer) elif length < _int32_max: return ensure_int32(indexer) return ensure_int64(indexer)
def coerce_indexer_dtype(indexer, categories): """ coerce the indexer input array to the smallest dtype possible """ length = len(categories) if length < _int8_max: return ensure_int8(indexer) elif length < _int16_max: return ensure_int16(indexer) elif length < _int32_max: return ensure_int32(indexer) return ensure_int64(indexer)
[ "coerce", "the", "indexer", "input", "array", "to", "the", "smallest", "dtype", "possible" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L565-L574
[ "def", "coerce_indexer_dtype", "(", "indexer", ",", "categories", ")", ":", "length", "=", "len", "(", "categories", ")", "if", "length", "<", "_int8_max", ":", "return", "ensure_int8", "(", "indexer", ")", "elif", "length", "<", "_int16_max", ":", "return", "ensure_int16", "(", "indexer", ")", "elif", "length", "<", "_int32_max", ":", "return", "ensure_int32", "(", "indexer", ")", "return", "ensure_int64", "(", "indexer", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
coerce_to_dtypes
given a dtypes and a result set, coerce the result elements to the dtypes
pandas/core/dtypes/cast.py
def coerce_to_dtypes(result, dtypes): """ given a dtypes and a result set, coerce the result elements to the dtypes """ if len(result) != len(dtypes): raise AssertionError("_coerce_to_dtypes requires equal len arrays") def conv(r, dtype): try: if isna(r): pass elif dtype == _NS_DTYPE: r = tslibs.Timestamp(r) elif dtype == _TD_DTYPE: r = tslibs.Timedelta(r) elif dtype == np.bool_: # messy. non 0/1 integers do not get converted. if is_integer(r) and r not in [0, 1]: return int(r) r = bool(r) elif dtype.kind == 'f': r = float(r) elif dtype.kind == 'i': r = int(r) except Exception: pass return r return [conv(r, dtype) for r, dtype in zip(result, dtypes)]
def coerce_to_dtypes(result, dtypes): """ given a dtypes and a result set, coerce the result elements to the dtypes """ if len(result) != len(dtypes): raise AssertionError("_coerce_to_dtypes requires equal len arrays") def conv(r, dtype): try: if isna(r): pass elif dtype == _NS_DTYPE: r = tslibs.Timestamp(r) elif dtype == _TD_DTYPE: r = tslibs.Timedelta(r) elif dtype == np.bool_: # messy. non 0/1 integers do not get converted. if is_integer(r) and r not in [0, 1]: return int(r) r = bool(r) elif dtype.kind == 'f': r = float(r) elif dtype.kind == 'i': r = int(r) except Exception: pass return r return [conv(r, dtype) for r, dtype in zip(result, dtypes)]
[ "given", "a", "dtypes", "and", "a", "result", "set", "coerce", "the", "result", "elements", "to", "the", "dtypes" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L577-L607
[ "def", "coerce_to_dtypes", "(", "result", ",", "dtypes", ")", ":", "if", "len", "(", "result", ")", "!=", "len", "(", "dtypes", ")", ":", "raise", "AssertionError", "(", "\"_coerce_to_dtypes requires equal len arrays\"", ")", "def", "conv", "(", "r", ",", "dtype", ")", ":", "try", ":", "if", "isna", "(", "r", ")", ":", "pass", "elif", "dtype", "==", "_NS_DTYPE", ":", "r", "=", "tslibs", ".", "Timestamp", "(", "r", ")", "elif", "dtype", "==", "_TD_DTYPE", ":", "r", "=", "tslibs", ".", "Timedelta", "(", "r", ")", "elif", "dtype", "==", "np", ".", "bool_", ":", "# messy. non 0/1 integers do not get converted.", "if", "is_integer", "(", "r", ")", "and", "r", "not", "in", "[", "0", ",", "1", "]", ":", "return", "int", "(", "r", ")", "r", "=", "bool", "(", "r", ")", "elif", "dtype", ".", "kind", "==", "'f'", ":", "r", "=", "float", "(", "r", ")", "elif", "dtype", ".", "kind", "==", "'i'", ":", "r", "=", "int", "(", "r", ")", "except", "Exception", ":", "pass", "return", "r", "return", "[", "conv", "(", "r", ",", "dtype", ")", "for", "r", ",", "dtype", "in", "zip", "(", "result", ",", "dtypes", ")", "]" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
astype_nansafe
Cast the elements of an array to a given dtype a nan-safe manner. Parameters ---------- arr : ndarray dtype : np.dtype copy : bool, default True If False, a view will be attempted but may fail, if e.g. the item sizes don't align. skipna: bool, default False Whether or not we should skip NaN when casting as a string-type. Raises ------ ValueError The dtype was a datetime64/timedelta64 dtype, but it had no unit.
pandas/core/dtypes/cast.py
def astype_nansafe(arr, dtype, copy=True, skipna=False): """ Cast the elements of an array to a given dtype a nan-safe manner. Parameters ---------- arr : ndarray dtype : np.dtype copy : bool, default True If False, a view will be attempted but may fail, if e.g. the item sizes don't align. skipna: bool, default False Whether or not we should skip NaN when casting as a string-type. Raises ------ ValueError The dtype was a datetime64/timedelta64 dtype, but it had no unit. """ # dispatch on extension dtype if needed if is_extension_array_dtype(dtype): return dtype.construct_array_type()._from_sequence( arr, dtype=dtype, copy=copy) if not isinstance(dtype, np.dtype): dtype = pandas_dtype(dtype) if issubclass(dtype.type, str): return lib.astype_str(arr.ravel(), skipna=skipna).reshape(arr.shape) elif is_datetime64_dtype(arr): if is_object_dtype(dtype): return tslib.ints_to_pydatetime(arr.view(np.int64)) elif dtype == np.int64: return arr.view(dtype) # allow frequency conversions if dtype.kind == 'M': return arr.astype(dtype) raise TypeError("cannot astype a datetimelike from [{from_dtype}] " "to [{to_dtype}]".format(from_dtype=arr.dtype, to_dtype=dtype)) elif is_timedelta64_dtype(arr): if is_object_dtype(dtype): return tslibs.ints_to_pytimedelta(arr.view(np.int64)) elif dtype == np.int64: return arr.view(dtype) if dtype not in [_INT64_DTYPE, _TD_DTYPE]: # allow frequency conversions # we return a float here! if dtype.kind == 'm': mask = isna(arr) result = arr.astype(dtype).astype(np.float64) result[mask] = np.nan return result elif dtype == _TD_DTYPE: return arr.astype(_TD_DTYPE, copy=copy) raise TypeError("cannot astype a timedelta from [{from_dtype}] " "to [{to_dtype}]".format(from_dtype=arr.dtype, to_dtype=dtype)) elif (np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer)): if not np.isfinite(arr).all(): raise ValueError('Cannot convert non-finite values (NA or inf) to ' 'integer') elif is_object_dtype(arr): # work around NumPy brokenness, #1987 if np.issubdtype(dtype.type, np.integer): return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape) # if we have a datetime/timedelta array of objects # then coerce to a proper dtype and recall astype_nansafe elif is_datetime64_dtype(dtype): from pandas import to_datetime return astype_nansafe(to_datetime(arr).values, dtype, copy=copy) elif is_timedelta64_dtype(dtype): from pandas import to_timedelta return astype_nansafe(to_timedelta(arr).values, dtype, copy=copy) if dtype.name in ("datetime64", "timedelta64"): msg = ("The '{dtype}' dtype has no unit. " "Please pass in '{dtype}[ns]' instead.") raise ValueError(msg.format(dtype=dtype.name)) if copy or is_object_dtype(arr) or is_object_dtype(dtype): # Explicit copy, or required since NumPy can't view from / to object. return arr.astype(dtype, copy=True) return arr.view(dtype)
def astype_nansafe(arr, dtype, copy=True, skipna=False): """ Cast the elements of an array to a given dtype a nan-safe manner. Parameters ---------- arr : ndarray dtype : np.dtype copy : bool, default True If False, a view will be attempted but may fail, if e.g. the item sizes don't align. skipna: bool, default False Whether or not we should skip NaN when casting as a string-type. Raises ------ ValueError The dtype was a datetime64/timedelta64 dtype, but it had no unit. """ # dispatch on extension dtype if needed if is_extension_array_dtype(dtype): return dtype.construct_array_type()._from_sequence( arr, dtype=dtype, copy=copy) if not isinstance(dtype, np.dtype): dtype = pandas_dtype(dtype) if issubclass(dtype.type, str): return lib.astype_str(arr.ravel(), skipna=skipna).reshape(arr.shape) elif is_datetime64_dtype(arr): if is_object_dtype(dtype): return tslib.ints_to_pydatetime(arr.view(np.int64)) elif dtype == np.int64: return arr.view(dtype) # allow frequency conversions if dtype.kind == 'M': return arr.astype(dtype) raise TypeError("cannot astype a datetimelike from [{from_dtype}] " "to [{to_dtype}]".format(from_dtype=arr.dtype, to_dtype=dtype)) elif is_timedelta64_dtype(arr): if is_object_dtype(dtype): return tslibs.ints_to_pytimedelta(arr.view(np.int64)) elif dtype == np.int64: return arr.view(dtype) if dtype not in [_INT64_DTYPE, _TD_DTYPE]: # allow frequency conversions # we return a float here! if dtype.kind == 'm': mask = isna(arr) result = arr.astype(dtype).astype(np.float64) result[mask] = np.nan return result elif dtype == _TD_DTYPE: return arr.astype(_TD_DTYPE, copy=copy) raise TypeError("cannot astype a timedelta from [{from_dtype}] " "to [{to_dtype}]".format(from_dtype=arr.dtype, to_dtype=dtype)) elif (np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer)): if not np.isfinite(arr).all(): raise ValueError('Cannot convert non-finite values (NA or inf) to ' 'integer') elif is_object_dtype(arr): # work around NumPy brokenness, #1987 if np.issubdtype(dtype.type, np.integer): return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape) # if we have a datetime/timedelta array of objects # then coerce to a proper dtype and recall astype_nansafe elif is_datetime64_dtype(dtype): from pandas import to_datetime return astype_nansafe(to_datetime(arr).values, dtype, copy=copy) elif is_timedelta64_dtype(dtype): from pandas import to_timedelta return astype_nansafe(to_timedelta(arr).values, dtype, copy=copy) if dtype.name in ("datetime64", "timedelta64"): msg = ("The '{dtype}' dtype has no unit. " "Please pass in '{dtype}[ns]' instead.") raise ValueError(msg.format(dtype=dtype.name)) if copy or is_object_dtype(arr) or is_object_dtype(dtype): # Explicit copy, or required since NumPy can't view from / to object. return arr.astype(dtype, copy=True) return arr.view(dtype)
[ "Cast", "the", "elements", "of", "an", "array", "to", "a", "given", "dtype", "a", "nan", "-", "safe", "manner", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L610-L710
[ "def", "astype_nansafe", "(", "arr", ",", "dtype", ",", "copy", "=", "True", ",", "skipna", "=", "False", ")", ":", "# dispatch on extension dtype if needed", "if", "is_extension_array_dtype", "(", "dtype", ")", ":", "return", "dtype", ".", "construct_array_type", "(", ")", ".", "_from_sequence", "(", "arr", ",", "dtype", "=", "dtype", ",", "copy", "=", "copy", ")", "if", "not", "isinstance", "(", "dtype", ",", "np", ".", "dtype", ")", ":", "dtype", "=", "pandas_dtype", "(", "dtype", ")", "if", "issubclass", "(", "dtype", ".", "type", ",", "str", ")", ":", "return", "lib", ".", "astype_str", "(", "arr", ".", "ravel", "(", ")", ",", "skipna", "=", "skipna", ")", ".", "reshape", "(", "arr", ".", "shape", ")", "elif", "is_datetime64_dtype", "(", "arr", ")", ":", "if", "is_object_dtype", "(", "dtype", ")", ":", "return", "tslib", ".", "ints_to_pydatetime", "(", "arr", ".", "view", "(", "np", ".", "int64", ")", ")", "elif", "dtype", "==", "np", ".", "int64", ":", "return", "arr", ".", "view", "(", "dtype", ")", "# allow frequency conversions", "if", "dtype", ".", "kind", "==", "'M'", ":", "return", "arr", ".", "astype", "(", "dtype", ")", "raise", "TypeError", "(", "\"cannot astype a datetimelike from [{from_dtype}] \"", "\"to [{to_dtype}]\"", ".", "format", "(", "from_dtype", "=", "arr", ".", "dtype", ",", "to_dtype", "=", "dtype", ")", ")", "elif", "is_timedelta64_dtype", "(", "arr", ")", ":", "if", "is_object_dtype", "(", "dtype", ")", ":", "return", "tslibs", ".", "ints_to_pytimedelta", "(", "arr", ".", "view", "(", "np", ".", "int64", ")", ")", "elif", "dtype", "==", "np", ".", "int64", ":", "return", "arr", ".", "view", "(", "dtype", ")", "if", "dtype", "not", "in", "[", "_INT64_DTYPE", ",", "_TD_DTYPE", "]", ":", "# allow frequency conversions", "# we return a float here!", "if", "dtype", ".", "kind", "==", "'m'", ":", "mask", "=", "isna", "(", "arr", ")", "result", "=", "arr", ".", "astype", "(", "dtype", ")", ".", "astype", "(", "np", ".", "float64", ")", "result", "[", "mask", "]", "=", "np", ".", "nan", "return", "result", "elif", "dtype", "==", "_TD_DTYPE", ":", "return", "arr", ".", "astype", "(", "_TD_DTYPE", ",", "copy", "=", "copy", ")", "raise", "TypeError", "(", "\"cannot astype a timedelta from [{from_dtype}] \"", "\"to [{to_dtype}]\"", ".", "format", "(", "from_dtype", "=", "arr", ".", "dtype", ",", "to_dtype", "=", "dtype", ")", ")", "elif", "(", "np", ".", "issubdtype", "(", "arr", ".", "dtype", ",", "np", ".", "floating", ")", "and", "np", ".", "issubdtype", "(", "dtype", ",", "np", ".", "integer", ")", ")", ":", "if", "not", "np", ".", "isfinite", "(", "arr", ")", ".", "all", "(", ")", ":", "raise", "ValueError", "(", "'Cannot convert non-finite values (NA or inf) to '", "'integer'", ")", "elif", "is_object_dtype", "(", "arr", ")", ":", "# work around NumPy brokenness, #1987", "if", "np", ".", "issubdtype", "(", "dtype", ".", "type", ",", "np", ".", "integer", ")", ":", "return", "lib", ".", "astype_intsafe", "(", "arr", ".", "ravel", "(", ")", ",", "dtype", ")", ".", "reshape", "(", "arr", ".", "shape", ")", "# if we have a datetime/timedelta array of objects", "# then coerce to a proper dtype and recall astype_nansafe", "elif", "is_datetime64_dtype", "(", "dtype", ")", ":", "from", "pandas", "import", "to_datetime", "return", "astype_nansafe", "(", "to_datetime", "(", "arr", ")", ".", "values", ",", "dtype", ",", "copy", "=", "copy", ")", "elif", "is_timedelta64_dtype", "(", "dtype", ")", ":", "from", "pandas", "import", "to_timedelta", "return", "astype_nansafe", "(", "to_timedelta", "(", "arr", ")", ".", "values", ",", "dtype", ",", "copy", "=", "copy", ")", "if", "dtype", ".", "name", "in", "(", "\"datetime64\"", ",", "\"timedelta64\"", ")", ":", "msg", "=", "(", "\"The '{dtype}' dtype has no unit. \"", "\"Please pass in '{dtype}[ns]' instead.\"", ")", "raise", "ValueError", "(", "msg", ".", "format", "(", "dtype", "=", "dtype", ".", "name", ")", ")", "if", "copy", "or", "is_object_dtype", "(", "arr", ")", "or", "is_object_dtype", "(", "dtype", ")", ":", "# Explicit copy, or required since NumPy can't view from / to object.", "return", "arr", ".", "astype", "(", "dtype", ",", "copy", "=", "True", ")", "return", "arr", ".", "view", "(", "dtype", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_convert_objects
if we have an object dtype, try to coerce dates and/or numbers
pandas/core/dtypes/cast.py
def maybe_convert_objects(values, convert_dates=True, convert_numeric=True, convert_timedeltas=True, copy=True): """ if we have an object dtype, try to coerce dates and/or numbers """ # if we have passed in a list or scalar if isinstance(values, (list, tuple)): values = np.array(values, dtype=np.object_) if not hasattr(values, 'dtype'): values = np.array([values], dtype=np.object_) # convert dates if convert_dates and values.dtype == np.object_: # we take an aggressive stance and convert to datetime64[ns] if convert_dates == 'coerce': new_values = maybe_cast_to_datetime( values, 'M8[ns]', errors='coerce') # if we are all nans then leave me alone if not isna(new_values).all(): values = new_values else: values = lib.maybe_convert_objects(values, convert_datetime=convert_dates) # convert timedeltas if convert_timedeltas and values.dtype == np.object_: if convert_timedeltas == 'coerce': from pandas.core.tools.timedeltas import to_timedelta new_values = to_timedelta(values, errors='coerce') # if we are all nans then leave me alone if not isna(new_values).all(): values = new_values else: values = lib.maybe_convert_objects( values, convert_timedelta=convert_timedeltas) # convert to numeric if values.dtype == np.object_: if convert_numeric: try: new_values = lib.maybe_convert_numeric(values, set(), coerce_numeric=True) # if we are all nans then leave me alone if not isna(new_values).all(): values = new_values except Exception: pass else: # soft-conversion values = lib.maybe_convert_objects(values) values = values.copy() if copy else values return values
def maybe_convert_objects(values, convert_dates=True, convert_numeric=True, convert_timedeltas=True, copy=True): """ if we have an object dtype, try to coerce dates and/or numbers """ # if we have passed in a list or scalar if isinstance(values, (list, tuple)): values = np.array(values, dtype=np.object_) if not hasattr(values, 'dtype'): values = np.array([values], dtype=np.object_) # convert dates if convert_dates and values.dtype == np.object_: # we take an aggressive stance and convert to datetime64[ns] if convert_dates == 'coerce': new_values = maybe_cast_to_datetime( values, 'M8[ns]', errors='coerce') # if we are all nans then leave me alone if not isna(new_values).all(): values = new_values else: values = lib.maybe_convert_objects(values, convert_datetime=convert_dates) # convert timedeltas if convert_timedeltas and values.dtype == np.object_: if convert_timedeltas == 'coerce': from pandas.core.tools.timedeltas import to_timedelta new_values = to_timedelta(values, errors='coerce') # if we are all nans then leave me alone if not isna(new_values).all(): values = new_values else: values = lib.maybe_convert_objects( values, convert_timedelta=convert_timedeltas) # convert to numeric if values.dtype == np.object_: if convert_numeric: try: new_values = lib.maybe_convert_numeric(values, set(), coerce_numeric=True) # if we are all nans then leave me alone if not isna(new_values).all(): values = new_values except Exception: pass else: # soft-conversion values = lib.maybe_convert_objects(values) values = values.copy() if copy else values return values
[ "if", "we", "have", "an", "object", "dtype", "try", "to", "coerce", "dates", "and", "/", "or", "numbers" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L713-L773
[ "def", "maybe_convert_objects", "(", "values", ",", "convert_dates", "=", "True", ",", "convert_numeric", "=", "True", ",", "convert_timedeltas", "=", "True", ",", "copy", "=", "True", ")", ":", "# if we have passed in a list or scalar", "if", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", ":", "values", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "np", ".", "object_", ")", "if", "not", "hasattr", "(", "values", ",", "'dtype'", ")", ":", "values", "=", "np", ".", "array", "(", "[", "values", "]", ",", "dtype", "=", "np", ".", "object_", ")", "# convert dates", "if", "convert_dates", "and", "values", ".", "dtype", "==", "np", ".", "object_", ":", "# we take an aggressive stance and convert to datetime64[ns]", "if", "convert_dates", "==", "'coerce'", ":", "new_values", "=", "maybe_cast_to_datetime", "(", "values", ",", "'M8[ns]'", ",", "errors", "=", "'coerce'", ")", "# if we are all nans then leave me alone", "if", "not", "isna", "(", "new_values", ")", ".", "all", "(", ")", ":", "values", "=", "new_values", "else", ":", "values", "=", "lib", ".", "maybe_convert_objects", "(", "values", ",", "convert_datetime", "=", "convert_dates", ")", "# convert timedeltas", "if", "convert_timedeltas", "and", "values", ".", "dtype", "==", "np", ".", "object_", ":", "if", "convert_timedeltas", "==", "'coerce'", ":", "from", "pandas", ".", "core", ".", "tools", ".", "timedeltas", "import", "to_timedelta", "new_values", "=", "to_timedelta", "(", "values", ",", "errors", "=", "'coerce'", ")", "# if we are all nans then leave me alone", "if", "not", "isna", "(", "new_values", ")", ".", "all", "(", ")", ":", "values", "=", "new_values", "else", ":", "values", "=", "lib", ".", "maybe_convert_objects", "(", "values", ",", "convert_timedelta", "=", "convert_timedeltas", ")", "# convert to numeric", "if", "values", ".", "dtype", "==", "np", ".", "object_", ":", "if", "convert_numeric", ":", "try", ":", "new_values", "=", "lib", ".", "maybe_convert_numeric", "(", "values", ",", "set", "(", ")", ",", "coerce_numeric", "=", "True", ")", "# if we are all nans then leave me alone", "if", "not", "isna", "(", "new_values", ")", ".", "all", "(", ")", ":", "values", "=", "new_values", "except", "Exception", ":", "pass", "else", ":", "# soft-conversion", "values", "=", "lib", ".", "maybe_convert_objects", "(", "values", ")", "values", "=", "values", ".", "copy", "(", ")", "if", "copy", "else", "values", "return", "values" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
soft_convert_objects
if we have an object dtype, try to coerce dates and/or numbers
pandas/core/dtypes/cast.py
def soft_convert_objects(values, datetime=True, numeric=True, timedelta=True, coerce=False, copy=True): """ if we have an object dtype, try to coerce dates and/or numbers """ conversion_count = sum((datetime, numeric, timedelta)) if conversion_count == 0: raise ValueError('At least one of datetime, numeric or timedelta must ' 'be True.') elif conversion_count > 1 and coerce: raise ValueError("Only one of 'datetime', 'numeric' or " "'timedelta' can be True when when coerce=True.") if isinstance(values, (list, tuple)): # List or scalar values = np.array(values, dtype=np.object_) elif not hasattr(values, 'dtype'): values = np.array([values], dtype=np.object_) elif not is_object_dtype(values.dtype): # If not object, do not attempt conversion values = values.copy() if copy else values return values # If 1 flag is coerce, ensure 2 others are False if coerce: # Immediate return if coerce if datetime: from pandas import to_datetime return to_datetime(values, errors='coerce').to_numpy() elif timedelta: from pandas import to_timedelta return to_timedelta(values, errors='coerce').to_numpy() elif numeric: from pandas import to_numeric return to_numeric(values, errors='coerce') # Soft conversions if datetime: # GH 20380, when datetime is beyond year 2262, hence outside # bound of nanosecond-resolution 64-bit integers. try: values = lib.maybe_convert_objects(values, convert_datetime=datetime) except OutOfBoundsDatetime: pass if timedelta and is_object_dtype(values.dtype): # Object check to ensure only run if previous did not convert values = lib.maybe_convert_objects(values, convert_timedelta=timedelta) if numeric and is_object_dtype(values.dtype): try: converted = lib.maybe_convert_numeric(values, set(), coerce_numeric=True) # If all NaNs, then do not-alter values = converted if not isna(converted).all() else values values = values.copy() if copy else values except Exception: pass return values
def soft_convert_objects(values, datetime=True, numeric=True, timedelta=True, coerce=False, copy=True): """ if we have an object dtype, try to coerce dates and/or numbers """ conversion_count = sum((datetime, numeric, timedelta)) if conversion_count == 0: raise ValueError('At least one of datetime, numeric or timedelta must ' 'be True.') elif conversion_count > 1 and coerce: raise ValueError("Only one of 'datetime', 'numeric' or " "'timedelta' can be True when when coerce=True.") if isinstance(values, (list, tuple)): # List or scalar values = np.array(values, dtype=np.object_) elif not hasattr(values, 'dtype'): values = np.array([values], dtype=np.object_) elif not is_object_dtype(values.dtype): # If not object, do not attempt conversion values = values.copy() if copy else values return values # If 1 flag is coerce, ensure 2 others are False if coerce: # Immediate return if coerce if datetime: from pandas import to_datetime return to_datetime(values, errors='coerce').to_numpy() elif timedelta: from pandas import to_timedelta return to_timedelta(values, errors='coerce').to_numpy() elif numeric: from pandas import to_numeric return to_numeric(values, errors='coerce') # Soft conversions if datetime: # GH 20380, when datetime is beyond year 2262, hence outside # bound of nanosecond-resolution 64-bit integers. try: values = lib.maybe_convert_objects(values, convert_datetime=datetime) except OutOfBoundsDatetime: pass if timedelta and is_object_dtype(values.dtype): # Object check to ensure only run if previous did not convert values = lib.maybe_convert_objects(values, convert_timedelta=timedelta) if numeric and is_object_dtype(values.dtype): try: converted = lib.maybe_convert_numeric(values, set(), coerce_numeric=True) # If all NaNs, then do not-alter values = converted if not isna(converted).all() else values values = values.copy() if copy else values except Exception: pass return values
[ "if", "we", "have", "an", "object", "dtype", "try", "to", "coerce", "dates", "and", "/", "or", "numbers" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L776-L835
[ "def", "soft_convert_objects", "(", "values", ",", "datetime", "=", "True", ",", "numeric", "=", "True", ",", "timedelta", "=", "True", ",", "coerce", "=", "False", ",", "copy", "=", "True", ")", ":", "conversion_count", "=", "sum", "(", "(", "datetime", ",", "numeric", ",", "timedelta", ")", ")", "if", "conversion_count", "==", "0", ":", "raise", "ValueError", "(", "'At least one of datetime, numeric or timedelta must '", "'be True.'", ")", "elif", "conversion_count", ">", "1", "and", "coerce", ":", "raise", "ValueError", "(", "\"Only one of 'datetime', 'numeric' or \"", "\"'timedelta' can be True when when coerce=True.\"", ")", "if", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", ":", "# List or scalar", "values", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "np", ".", "object_", ")", "elif", "not", "hasattr", "(", "values", ",", "'dtype'", ")", ":", "values", "=", "np", ".", "array", "(", "[", "values", "]", ",", "dtype", "=", "np", ".", "object_", ")", "elif", "not", "is_object_dtype", "(", "values", ".", "dtype", ")", ":", "# If not object, do not attempt conversion", "values", "=", "values", ".", "copy", "(", ")", "if", "copy", "else", "values", "return", "values", "# If 1 flag is coerce, ensure 2 others are False", "if", "coerce", ":", "# Immediate return if coerce", "if", "datetime", ":", "from", "pandas", "import", "to_datetime", "return", "to_datetime", "(", "values", ",", "errors", "=", "'coerce'", ")", ".", "to_numpy", "(", ")", "elif", "timedelta", ":", "from", "pandas", "import", "to_timedelta", "return", "to_timedelta", "(", "values", ",", "errors", "=", "'coerce'", ")", ".", "to_numpy", "(", ")", "elif", "numeric", ":", "from", "pandas", "import", "to_numeric", "return", "to_numeric", "(", "values", ",", "errors", "=", "'coerce'", ")", "# Soft conversions", "if", "datetime", ":", "# GH 20380, when datetime is beyond year 2262, hence outside", "# bound of nanosecond-resolution 64-bit integers.", "try", ":", "values", "=", "lib", ".", "maybe_convert_objects", "(", "values", ",", "convert_datetime", "=", "datetime", ")", "except", "OutOfBoundsDatetime", ":", "pass", "if", "timedelta", "and", "is_object_dtype", "(", "values", ".", "dtype", ")", ":", "# Object check to ensure only run if previous did not convert", "values", "=", "lib", ".", "maybe_convert_objects", "(", "values", ",", "convert_timedelta", "=", "timedelta", ")", "if", "numeric", "and", "is_object_dtype", "(", "values", ".", "dtype", ")", ":", "try", ":", "converted", "=", "lib", ".", "maybe_convert_numeric", "(", "values", ",", "set", "(", ")", ",", "coerce_numeric", "=", "True", ")", "# If all NaNs, then do not-alter", "values", "=", "converted", "if", "not", "isna", "(", "converted", ")", ".", "all", "(", ")", "else", "values", "values", "=", "values", ".", "copy", "(", ")", "if", "copy", "else", "values", "except", "Exception", ":", "pass", "return", "values" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_infer_to_datetimelike
we might have a array (or single object) that is datetime like, and no dtype is passed don't change the value unless we find a datetime/timedelta set this is pretty strict in that a datetime/timedelta is REQUIRED in addition to possible nulls/string likes Parameters ---------- value : np.array / Series / Index / list-like convert_dates : boolean, default False if True try really hard to convert dates (such as datetime.date), other leave inferred dtype 'date' alone
pandas/core/dtypes/cast.py
def maybe_infer_to_datetimelike(value, convert_dates=False): """ we might have a array (or single object) that is datetime like, and no dtype is passed don't change the value unless we find a datetime/timedelta set this is pretty strict in that a datetime/timedelta is REQUIRED in addition to possible nulls/string likes Parameters ---------- value : np.array / Series / Index / list-like convert_dates : boolean, default False if True try really hard to convert dates (such as datetime.date), other leave inferred dtype 'date' alone """ # TODO: why not timedelta? if isinstance(value, (ABCDatetimeIndex, ABCPeriodIndex, ABCDatetimeArray, ABCPeriodArray)): return value elif isinstance(value, ABCSeries): if isinstance(value._values, ABCDatetimeIndex): return value._values v = value if not is_list_like(v): v = [v] v = np.array(v, copy=False) # we only care about object dtypes if not is_object_dtype(v): return value shape = v.shape if not v.ndim == 1: v = v.ravel() if not len(v): return value def try_datetime(v): # safe coerce to datetime64 try: # GH19671 v = tslib.array_to_datetime(v, require_iso8601=True, errors='raise')[0] except ValueError: # we might have a sequence of the same-datetimes with tz's # if so coerce to a DatetimeIndex; if they are not the same, # then these stay as object dtype, xref GH19671 try: from pandas._libs.tslibs import conversion from pandas import DatetimeIndex values, tz = conversion.datetime_to_datetime64(v) return DatetimeIndex(values).tz_localize( 'UTC').tz_convert(tz=tz) except (ValueError, TypeError): pass except Exception: pass return v.reshape(shape) def try_timedelta(v): # safe coerce to timedelta64 # will try first with a string & object conversion from pandas import to_timedelta try: return to_timedelta(v)._ndarray_values.reshape(shape) except Exception: return v.reshape(shape) inferred_type = lib.infer_datetimelike_array(ensure_object(v)) if inferred_type == 'date' and convert_dates: value = try_datetime(v) elif inferred_type == 'datetime': value = try_datetime(v) elif inferred_type == 'timedelta': value = try_timedelta(v) elif inferred_type == 'nat': # if all NaT, return as datetime if isna(v).all(): value = try_datetime(v) else: # We have at least a NaT and a string # try timedelta first to avoid spurious datetime conversions # e.g. '00:00:01' is a timedelta but technically is also a datetime value = try_timedelta(v) if lib.infer_dtype(value, skipna=False) in ['mixed']: # cannot skip missing values, as NaT implies that the string # is actually a datetime value = try_datetime(v) return value
def maybe_infer_to_datetimelike(value, convert_dates=False): """ we might have a array (or single object) that is datetime like, and no dtype is passed don't change the value unless we find a datetime/timedelta set this is pretty strict in that a datetime/timedelta is REQUIRED in addition to possible nulls/string likes Parameters ---------- value : np.array / Series / Index / list-like convert_dates : boolean, default False if True try really hard to convert dates (such as datetime.date), other leave inferred dtype 'date' alone """ # TODO: why not timedelta? if isinstance(value, (ABCDatetimeIndex, ABCPeriodIndex, ABCDatetimeArray, ABCPeriodArray)): return value elif isinstance(value, ABCSeries): if isinstance(value._values, ABCDatetimeIndex): return value._values v = value if not is_list_like(v): v = [v] v = np.array(v, copy=False) # we only care about object dtypes if not is_object_dtype(v): return value shape = v.shape if not v.ndim == 1: v = v.ravel() if not len(v): return value def try_datetime(v): # safe coerce to datetime64 try: # GH19671 v = tslib.array_to_datetime(v, require_iso8601=True, errors='raise')[0] except ValueError: # we might have a sequence of the same-datetimes with tz's # if so coerce to a DatetimeIndex; if they are not the same, # then these stay as object dtype, xref GH19671 try: from pandas._libs.tslibs import conversion from pandas import DatetimeIndex values, tz = conversion.datetime_to_datetime64(v) return DatetimeIndex(values).tz_localize( 'UTC').tz_convert(tz=tz) except (ValueError, TypeError): pass except Exception: pass return v.reshape(shape) def try_timedelta(v): # safe coerce to timedelta64 # will try first with a string & object conversion from pandas import to_timedelta try: return to_timedelta(v)._ndarray_values.reshape(shape) except Exception: return v.reshape(shape) inferred_type = lib.infer_datetimelike_array(ensure_object(v)) if inferred_type == 'date' and convert_dates: value = try_datetime(v) elif inferred_type == 'datetime': value = try_datetime(v) elif inferred_type == 'timedelta': value = try_timedelta(v) elif inferred_type == 'nat': # if all NaT, return as datetime if isna(v).all(): value = try_datetime(v) else: # We have at least a NaT and a string # try timedelta first to avoid spurious datetime conversions # e.g. '00:00:01' is a timedelta but technically is also a datetime value = try_timedelta(v) if lib.infer_dtype(value, skipna=False) in ['mixed']: # cannot skip missing values, as NaT implies that the string # is actually a datetime value = try_datetime(v) return value
[ "we", "might", "have", "a", "array", "(", "or", "single", "object", ")", "that", "is", "datetime", "like", "and", "no", "dtype", "is", "passed", "don", "t", "change", "the", "value", "unless", "we", "find", "a", "datetime", "/", "timedelta", "set" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L852-L956
[ "def", "maybe_infer_to_datetimelike", "(", "value", ",", "convert_dates", "=", "False", ")", ":", "# TODO: why not timedelta?", "if", "isinstance", "(", "value", ",", "(", "ABCDatetimeIndex", ",", "ABCPeriodIndex", ",", "ABCDatetimeArray", ",", "ABCPeriodArray", ")", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "ABCSeries", ")", ":", "if", "isinstance", "(", "value", ".", "_values", ",", "ABCDatetimeIndex", ")", ":", "return", "value", ".", "_values", "v", "=", "value", "if", "not", "is_list_like", "(", "v", ")", ":", "v", "=", "[", "v", "]", "v", "=", "np", ".", "array", "(", "v", ",", "copy", "=", "False", ")", "# we only care about object dtypes", "if", "not", "is_object_dtype", "(", "v", ")", ":", "return", "value", "shape", "=", "v", ".", "shape", "if", "not", "v", ".", "ndim", "==", "1", ":", "v", "=", "v", ".", "ravel", "(", ")", "if", "not", "len", "(", "v", ")", ":", "return", "value", "def", "try_datetime", "(", "v", ")", ":", "# safe coerce to datetime64", "try", ":", "# GH19671", "v", "=", "tslib", ".", "array_to_datetime", "(", "v", ",", "require_iso8601", "=", "True", ",", "errors", "=", "'raise'", ")", "[", "0", "]", "except", "ValueError", ":", "# we might have a sequence of the same-datetimes with tz's", "# if so coerce to a DatetimeIndex; if they are not the same,", "# then these stay as object dtype, xref GH19671", "try", ":", "from", "pandas", ".", "_libs", ".", "tslibs", "import", "conversion", "from", "pandas", "import", "DatetimeIndex", "values", ",", "tz", "=", "conversion", ".", "datetime_to_datetime64", "(", "v", ")", "return", "DatetimeIndex", "(", "values", ")", ".", "tz_localize", "(", "'UTC'", ")", ".", "tz_convert", "(", "tz", "=", "tz", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", "except", "Exception", ":", "pass", "return", "v", ".", "reshape", "(", "shape", ")", "def", "try_timedelta", "(", "v", ")", ":", "# safe coerce to timedelta64", "# will try first with a string & object conversion", "from", "pandas", "import", "to_timedelta", "try", ":", "return", "to_timedelta", "(", "v", ")", ".", "_ndarray_values", ".", "reshape", "(", "shape", ")", "except", "Exception", ":", "return", "v", ".", "reshape", "(", "shape", ")", "inferred_type", "=", "lib", ".", "infer_datetimelike_array", "(", "ensure_object", "(", "v", ")", ")", "if", "inferred_type", "==", "'date'", "and", "convert_dates", ":", "value", "=", "try_datetime", "(", "v", ")", "elif", "inferred_type", "==", "'datetime'", ":", "value", "=", "try_datetime", "(", "v", ")", "elif", "inferred_type", "==", "'timedelta'", ":", "value", "=", "try_timedelta", "(", "v", ")", "elif", "inferred_type", "==", "'nat'", ":", "# if all NaT, return as datetime", "if", "isna", "(", "v", ")", ".", "all", "(", ")", ":", "value", "=", "try_datetime", "(", "v", ")", "else", ":", "# We have at least a NaT and a string", "# try timedelta first to avoid spurious datetime conversions", "# e.g. '00:00:01' is a timedelta but technically is also a datetime", "value", "=", "try_timedelta", "(", "v", ")", "if", "lib", ".", "infer_dtype", "(", "value", ",", "skipna", "=", "False", ")", "in", "[", "'mixed'", "]", ":", "# cannot skip missing values, as NaT implies that the string", "# is actually a datetime", "value", "=", "try_datetime", "(", "v", ")", "return", "value" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_cast_to_datetime
try to cast the array/value to a datetimelike dtype, converting float nan to iNaT
pandas/core/dtypes/cast.py
def maybe_cast_to_datetime(value, dtype, errors='raise'): """ try to cast the array/value to a datetimelike dtype, converting float nan to iNaT """ from pandas.core.tools.timedeltas import to_timedelta from pandas.core.tools.datetimes import to_datetime if dtype is not None: if isinstance(dtype, str): dtype = np.dtype(dtype) is_datetime64 = is_datetime64_dtype(dtype) is_datetime64tz = is_datetime64tz_dtype(dtype) is_timedelta64 = is_timedelta64_dtype(dtype) if is_datetime64 or is_datetime64tz or is_timedelta64: # Force the dtype if needed. msg = ("The '{dtype}' dtype has no unit. " "Please pass in '{dtype}[ns]' instead.") if is_datetime64 and not is_dtype_equal(dtype, _NS_DTYPE): if dtype.name in ('datetime64', 'datetime64[ns]'): if dtype.name == 'datetime64': raise ValueError(msg.format(dtype=dtype.name)) dtype = _NS_DTYPE else: raise TypeError("cannot convert datetimelike to " "dtype [{dtype}]".format(dtype=dtype)) elif is_datetime64tz: # our NaT doesn't support tz's # this will coerce to DatetimeIndex with # a matching dtype below if is_scalar(value) and isna(value): value = [value] elif is_timedelta64 and not is_dtype_equal(dtype, _TD_DTYPE): if dtype.name in ('timedelta64', 'timedelta64[ns]'): if dtype.name == 'timedelta64': raise ValueError(msg.format(dtype=dtype.name)) dtype = _TD_DTYPE else: raise TypeError("cannot convert timedeltalike to " "dtype [{dtype}]".format(dtype=dtype)) if is_scalar(value): if value == iNaT or isna(value): value = iNaT else: value = np.array(value, copy=False) # have a scalar array-like (e.g. NaT) if value.ndim == 0: value = iNaT # we have an array of datetime or timedeltas & nulls elif np.prod(value.shape) or not is_dtype_equal(value.dtype, dtype): try: if is_datetime64: value = to_datetime(value, errors=errors) # GH 25843: Remove tz information since the dtype # didn't specify one if value.tz is not None: value = value.tz_localize(None) value = value._values elif is_datetime64tz: # The string check can be removed once issue #13712 # is solved. String data that is passed with a # datetime64tz is assumed to be naive which should # be localized to the timezone. is_dt_string = is_string_dtype(value) value = to_datetime(value, errors=errors).array if is_dt_string: # Strings here are naive, so directly localize value = value.tz_localize(dtype.tz) else: # Numeric values are UTC at this point, # so localize and convert value = (value.tz_localize('UTC') .tz_convert(dtype.tz)) elif is_timedelta64: value = to_timedelta(value, errors=errors)._values except (AttributeError, ValueError, TypeError): pass # coerce datetimelike to object elif is_datetime64_dtype(value) and not is_datetime64_dtype(dtype): if is_object_dtype(dtype): if value.dtype != _NS_DTYPE: value = value.astype(_NS_DTYPE) ints = np.asarray(value).view('i8') return tslib.ints_to_pydatetime(ints) # we have a non-castable dtype that was passed raise TypeError('Cannot cast datetime64 to {dtype}' .format(dtype=dtype)) else: is_array = isinstance(value, np.ndarray) # catch a datetime/timedelta that is not of ns variety # and no coercion specified if is_array and value.dtype.kind in ['M', 'm']: dtype = value.dtype if dtype.kind == 'M' and dtype != _NS_DTYPE: value = value.astype(_NS_DTYPE) elif dtype.kind == 'm' and dtype != _TD_DTYPE: value = to_timedelta(value) # only do this if we have an array and the dtype of the array is not # setup already we are not an integer/object, so don't bother with this # conversion elif not (is_array and not (issubclass(value.dtype.type, np.integer) or value.dtype == np.object_)): value = maybe_infer_to_datetimelike(value) return value
def maybe_cast_to_datetime(value, dtype, errors='raise'): """ try to cast the array/value to a datetimelike dtype, converting float nan to iNaT """ from pandas.core.tools.timedeltas import to_timedelta from pandas.core.tools.datetimes import to_datetime if dtype is not None: if isinstance(dtype, str): dtype = np.dtype(dtype) is_datetime64 = is_datetime64_dtype(dtype) is_datetime64tz = is_datetime64tz_dtype(dtype) is_timedelta64 = is_timedelta64_dtype(dtype) if is_datetime64 or is_datetime64tz or is_timedelta64: # Force the dtype if needed. msg = ("The '{dtype}' dtype has no unit. " "Please pass in '{dtype}[ns]' instead.") if is_datetime64 and not is_dtype_equal(dtype, _NS_DTYPE): if dtype.name in ('datetime64', 'datetime64[ns]'): if dtype.name == 'datetime64': raise ValueError(msg.format(dtype=dtype.name)) dtype = _NS_DTYPE else: raise TypeError("cannot convert datetimelike to " "dtype [{dtype}]".format(dtype=dtype)) elif is_datetime64tz: # our NaT doesn't support tz's # this will coerce to DatetimeIndex with # a matching dtype below if is_scalar(value) and isna(value): value = [value] elif is_timedelta64 and not is_dtype_equal(dtype, _TD_DTYPE): if dtype.name in ('timedelta64', 'timedelta64[ns]'): if dtype.name == 'timedelta64': raise ValueError(msg.format(dtype=dtype.name)) dtype = _TD_DTYPE else: raise TypeError("cannot convert timedeltalike to " "dtype [{dtype}]".format(dtype=dtype)) if is_scalar(value): if value == iNaT or isna(value): value = iNaT else: value = np.array(value, copy=False) # have a scalar array-like (e.g. NaT) if value.ndim == 0: value = iNaT # we have an array of datetime or timedeltas & nulls elif np.prod(value.shape) or not is_dtype_equal(value.dtype, dtype): try: if is_datetime64: value = to_datetime(value, errors=errors) # GH 25843: Remove tz information since the dtype # didn't specify one if value.tz is not None: value = value.tz_localize(None) value = value._values elif is_datetime64tz: # The string check can be removed once issue #13712 # is solved. String data that is passed with a # datetime64tz is assumed to be naive which should # be localized to the timezone. is_dt_string = is_string_dtype(value) value = to_datetime(value, errors=errors).array if is_dt_string: # Strings here are naive, so directly localize value = value.tz_localize(dtype.tz) else: # Numeric values are UTC at this point, # so localize and convert value = (value.tz_localize('UTC') .tz_convert(dtype.tz)) elif is_timedelta64: value = to_timedelta(value, errors=errors)._values except (AttributeError, ValueError, TypeError): pass # coerce datetimelike to object elif is_datetime64_dtype(value) and not is_datetime64_dtype(dtype): if is_object_dtype(dtype): if value.dtype != _NS_DTYPE: value = value.astype(_NS_DTYPE) ints = np.asarray(value).view('i8') return tslib.ints_to_pydatetime(ints) # we have a non-castable dtype that was passed raise TypeError('Cannot cast datetime64 to {dtype}' .format(dtype=dtype)) else: is_array = isinstance(value, np.ndarray) # catch a datetime/timedelta that is not of ns variety # and no coercion specified if is_array and value.dtype.kind in ['M', 'm']: dtype = value.dtype if dtype.kind == 'M' and dtype != _NS_DTYPE: value = value.astype(_NS_DTYPE) elif dtype.kind == 'm' and dtype != _TD_DTYPE: value = to_timedelta(value) # only do this if we have an array and the dtype of the array is not # setup already we are not an integer/object, so don't bother with this # conversion elif not (is_array and not (issubclass(value.dtype.type, np.integer) or value.dtype == np.object_)): value = maybe_infer_to_datetimelike(value) return value
[ "try", "to", "cast", "the", "array", "/", "value", "to", "a", "datetimelike", "dtype", "converting", "float", "nan", "to", "iNaT" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L959-L1080
[ "def", "maybe_cast_to_datetime", "(", "value", ",", "dtype", ",", "errors", "=", "'raise'", ")", ":", "from", "pandas", ".", "core", ".", "tools", ".", "timedeltas", "import", "to_timedelta", "from", "pandas", ".", "core", ".", "tools", ".", "datetimes", "import", "to_datetime", "if", "dtype", "is", "not", "None", ":", "if", "isinstance", "(", "dtype", ",", "str", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "dtype", ")", "is_datetime64", "=", "is_datetime64_dtype", "(", "dtype", ")", "is_datetime64tz", "=", "is_datetime64tz_dtype", "(", "dtype", ")", "is_timedelta64", "=", "is_timedelta64_dtype", "(", "dtype", ")", "if", "is_datetime64", "or", "is_datetime64tz", "or", "is_timedelta64", ":", "# Force the dtype if needed.", "msg", "=", "(", "\"The '{dtype}' dtype has no unit. \"", "\"Please pass in '{dtype}[ns]' instead.\"", ")", "if", "is_datetime64", "and", "not", "is_dtype_equal", "(", "dtype", ",", "_NS_DTYPE", ")", ":", "if", "dtype", ".", "name", "in", "(", "'datetime64'", ",", "'datetime64[ns]'", ")", ":", "if", "dtype", ".", "name", "==", "'datetime64'", ":", "raise", "ValueError", "(", "msg", ".", "format", "(", "dtype", "=", "dtype", ".", "name", ")", ")", "dtype", "=", "_NS_DTYPE", "else", ":", "raise", "TypeError", "(", "\"cannot convert datetimelike to \"", "\"dtype [{dtype}]\"", ".", "format", "(", "dtype", "=", "dtype", ")", ")", "elif", "is_datetime64tz", ":", "# our NaT doesn't support tz's", "# this will coerce to DatetimeIndex with", "# a matching dtype below", "if", "is_scalar", "(", "value", ")", "and", "isna", "(", "value", ")", ":", "value", "=", "[", "value", "]", "elif", "is_timedelta64", "and", "not", "is_dtype_equal", "(", "dtype", ",", "_TD_DTYPE", ")", ":", "if", "dtype", ".", "name", "in", "(", "'timedelta64'", ",", "'timedelta64[ns]'", ")", ":", "if", "dtype", ".", "name", "==", "'timedelta64'", ":", "raise", "ValueError", "(", "msg", ".", "format", "(", "dtype", "=", "dtype", ".", "name", ")", ")", "dtype", "=", "_TD_DTYPE", "else", ":", "raise", "TypeError", "(", "\"cannot convert timedeltalike to \"", "\"dtype [{dtype}]\"", ".", "format", "(", "dtype", "=", "dtype", ")", ")", "if", "is_scalar", "(", "value", ")", ":", "if", "value", "==", "iNaT", "or", "isna", "(", "value", ")", ":", "value", "=", "iNaT", "else", ":", "value", "=", "np", ".", "array", "(", "value", ",", "copy", "=", "False", ")", "# have a scalar array-like (e.g. NaT)", "if", "value", ".", "ndim", "==", "0", ":", "value", "=", "iNaT", "# we have an array of datetime or timedeltas & nulls", "elif", "np", ".", "prod", "(", "value", ".", "shape", ")", "or", "not", "is_dtype_equal", "(", "value", ".", "dtype", ",", "dtype", ")", ":", "try", ":", "if", "is_datetime64", ":", "value", "=", "to_datetime", "(", "value", ",", "errors", "=", "errors", ")", "# GH 25843: Remove tz information since the dtype", "# didn't specify one", "if", "value", ".", "tz", "is", "not", "None", ":", "value", "=", "value", ".", "tz_localize", "(", "None", ")", "value", "=", "value", ".", "_values", "elif", "is_datetime64tz", ":", "# The string check can be removed once issue #13712", "# is solved. String data that is passed with a", "# datetime64tz is assumed to be naive which should", "# be localized to the timezone.", "is_dt_string", "=", "is_string_dtype", "(", "value", ")", "value", "=", "to_datetime", "(", "value", ",", "errors", "=", "errors", ")", ".", "array", "if", "is_dt_string", ":", "# Strings here are naive, so directly localize", "value", "=", "value", ".", "tz_localize", "(", "dtype", ".", "tz", ")", "else", ":", "# Numeric values are UTC at this point,", "# so localize and convert", "value", "=", "(", "value", ".", "tz_localize", "(", "'UTC'", ")", ".", "tz_convert", "(", "dtype", ".", "tz", ")", ")", "elif", "is_timedelta64", ":", "value", "=", "to_timedelta", "(", "value", ",", "errors", "=", "errors", ")", ".", "_values", "except", "(", "AttributeError", ",", "ValueError", ",", "TypeError", ")", ":", "pass", "# coerce datetimelike to object", "elif", "is_datetime64_dtype", "(", "value", ")", "and", "not", "is_datetime64_dtype", "(", "dtype", ")", ":", "if", "is_object_dtype", "(", "dtype", ")", ":", "if", "value", ".", "dtype", "!=", "_NS_DTYPE", ":", "value", "=", "value", ".", "astype", "(", "_NS_DTYPE", ")", "ints", "=", "np", ".", "asarray", "(", "value", ")", ".", "view", "(", "'i8'", ")", "return", "tslib", ".", "ints_to_pydatetime", "(", "ints", ")", "# we have a non-castable dtype that was passed", "raise", "TypeError", "(", "'Cannot cast datetime64 to {dtype}'", ".", "format", "(", "dtype", "=", "dtype", ")", ")", "else", ":", "is_array", "=", "isinstance", "(", "value", ",", "np", ".", "ndarray", ")", "# catch a datetime/timedelta that is not of ns variety", "# and no coercion specified", "if", "is_array", "and", "value", ".", "dtype", ".", "kind", "in", "[", "'M'", ",", "'m'", "]", ":", "dtype", "=", "value", ".", "dtype", "if", "dtype", ".", "kind", "==", "'M'", "and", "dtype", "!=", "_NS_DTYPE", ":", "value", "=", "value", ".", "astype", "(", "_NS_DTYPE", ")", "elif", "dtype", ".", "kind", "==", "'m'", "and", "dtype", "!=", "_TD_DTYPE", ":", "value", "=", "to_timedelta", "(", "value", ")", "# only do this if we have an array and the dtype of the array is not", "# setup already we are not an integer/object, so don't bother with this", "# conversion", "elif", "not", "(", "is_array", "and", "not", "(", "issubclass", "(", "value", ".", "dtype", ".", "type", ",", "np", ".", "integer", ")", "or", "value", ".", "dtype", "==", "np", ".", "object_", ")", ")", ":", "value", "=", "maybe_infer_to_datetimelike", "(", "value", ")", "return", "value" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
find_common_type
Find a common data type among the given dtypes. Parameters ---------- types : list of dtypes Returns ------- pandas extension or numpy dtype See Also -------- numpy.find_common_type
pandas/core/dtypes/cast.py
def find_common_type(types): """ Find a common data type among the given dtypes. Parameters ---------- types : list of dtypes Returns ------- pandas extension or numpy dtype See Also -------- numpy.find_common_type """ if len(types) == 0: raise ValueError('no types given') first = types[0] # workaround for find_common_type([np.dtype('datetime64[ns]')] * 2) # => object if all(is_dtype_equal(first, t) for t in types[1:]): return first if any(isinstance(t, (PandasExtensionDtype, ExtensionDtype)) for t in types): return np.object # take lowest unit if all(is_datetime64_dtype(t) for t in types): return np.dtype('datetime64[ns]') if all(is_timedelta64_dtype(t) for t in types): return np.dtype('timedelta64[ns]') # don't mix bool / int or float or complex # this is different from numpy, which casts bool with float/int as int has_bools = any(is_bool_dtype(t) for t in types) if has_bools: for t in types: if is_integer_dtype(t) or is_float_dtype(t) or is_complex_dtype(t): return np.object return np.find_common_type(types, [])
def find_common_type(types): """ Find a common data type among the given dtypes. Parameters ---------- types : list of dtypes Returns ------- pandas extension or numpy dtype See Also -------- numpy.find_common_type """ if len(types) == 0: raise ValueError('no types given') first = types[0] # workaround for find_common_type([np.dtype('datetime64[ns]')] * 2) # => object if all(is_dtype_equal(first, t) for t in types[1:]): return first if any(isinstance(t, (PandasExtensionDtype, ExtensionDtype)) for t in types): return np.object # take lowest unit if all(is_datetime64_dtype(t) for t in types): return np.dtype('datetime64[ns]') if all(is_timedelta64_dtype(t) for t in types): return np.dtype('timedelta64[ns]') # don't mix bool / int or float or complex # this is different from numpy, which casts bool with float/int as int has_bools = any(is_bool_dtype(t) for t in types) if has_bools: for t in types: if is_integer_dtype(t) or is_float_dtype(t) or is_complex_dtype(t): return np.object return np.find_common_type(types, [])
[ "Find", "a", "common", "data", "type", "among", "the", "given", "dtypes", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L1083-L1129
[ "def", "find_common_type", "(", "types", ")", ":", "if", "len", "(", "types", ")", "==", "0", ":", "raise", "ValueError", "(", "'no types given'", ")", "first", "=", "types", "[", "0", "]", "# workaround for find_common_type([np.dtype('datetime64[ns]')] * 2)", "# => object", "if", "all", "(", "is_dtype_equal", "(", "first", ",", "t", ")", "for", "t", "in", "types", "[", "1", ":", "]", ")", ":", "return", "first", "if", "any", "(", "isinstance", "(", "t", ",", "(", "PandasExtensionDtype", ",", "ExtensionDtype", ")", ")", "for", "t", "in", "types", ")", ":", "return", "np", ".", "object", "# take lowest unit", "if", "all", "(", "is_datetime64_dtype", "(", "t", ")", "for", "t", "in", "types", ")", ":", "return", "np", ".", "dtype", "(", "'datetime64[ns]'", ")", "if", "all", "(", "is_timedelta64_dtype", "(", "t", ")", "for", "t", "in", "types", ")", ":", "return", "np", ".", "dtype", "(", "'timedelta64[ns]'", ")", "# don't mix bool / int or float or complex", "# this is different from numpy, which casts bool with float/int as int", "has_bools", "=", "any", "(", "is_bool_dtype", "(", "t", ")", "for", "t", "in", "types", ")", "if", "has_bools", ":", "for", "t", "in", "types", ":", "if", "is_integer_dtype", "(", "t", ")", "or", "is_float_dtype", "(", "t", ")", "or", "is_complex_dtype", "(", "t", ")", ":", "return", "np", ".", "object", "return", "np", ".", "find_common_type", "(", "types", ",", "[", "]", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
cast_scalar_to_array
create np.ndarray of specified shape and dtype, filled with values Parameters ---------- shape : tuple value : scalar value dtype : np.dtype, optional dtype to coerce Returns ------- ndarray of shape, filled with value, of specified / inferred dtype
pandas/core/dtypes/cast.py
def cast_scalar_to_array(shape, value, dtype=None): """ create np.ndarray of specified shape and dtype, filled with values Parameters ---------- shape : tuple value : scalar value dtype : np.dtype, optional dtype to coerce Returns ------- ndarray of shape, filled with value, of specified / inferred dtype """ if dtype is None: dtype, fill_value = infer_dtype_from_scalar(value) else: fill_value = value values = np.empty(shape, dtype=dtype) values.fill(fill_value) return values
def cast_scalar_to_array(shape, value, dtype=None): """ create np.ndarray of specified shape and dtype, filled with values Parameters ---------- shape : tuple value : scalar value dtype : np.dtype, optional dtype to coerce Returns ------- ndarray of shape, filled with value, of specified / inferred dtype """ if dtype is None: dtype, fill_value = infer_dtype_from_scalar(value) else: fill_value = value values = np.empty(shape, dtype=dtype) values.fill(fill_value) return values
[ "create", "np", ".", "ndarray", "of", "specified", "shape", "and", "dtype", "filled", "with", "values" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L1132-L1157
[ "def", "cast_scalar_to_array", "(", "shape", ",", "value", ",", "dtype", "=", "None", ")", ":", "if", "dtype", "is", "None", ":", "dtype", ",", "fill_value", "=", "infer_dtype_from_scalar", "(", "value", ")", "else", ":", "fill_value", "=", "value", "values", "=", "np", ".", "empty", "(", "shape", ",", "dtype", "=", "dtype", ")", "values", ".", "fill", "(", "fill_value", ")", "return", "values" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
construct_1d_arraylike_from_scalar
create a np.ndarray / pandas type of specified shape and dtype filled with values Parameters ---------- value : scalar value length : int dtype : pandas_dtype / np.dtype Returns ------- np.ndarray / pandas type of length, filled with value
pandas/core/dtypes/cast.py
def construct_1d_arraylike_from_scalar(value, length, dtype): """ create a np.ndarray / pandas type of specified shape and dtype filled with values Parameters ---------- value : scalar value length : int dtype : pandas_dtype / np.dtype Returns ------- np.ndarray / pandas type of length, filled with value """ if is_datetime64tz_dtype(dtype): from pandas import DatetimeIndex subarr = DatetimeIndex([value] * length, dtype=dtype) elif is_categorical_dtype(dtype): from pandas import Categorical subarr = Categorical([value] * length, dtype=dtype) else: if not isinstance(dtype, (np.dtype, type(np.dtype))): dtype = dtype.dtype if length and is_integer_dtype(dtype) and isna(value): # coerce if we have nan for an integer dtype dtype = np.dtype('float64') elif isinstance(dtype, np.dtype) and dtype.kind in ("U", "S"): # we need to coerce to object dtype to avoid # to allow numpy to take our string as a scalar value dtype = object if not isna(value): value = to_str(value) subarr = np.empty(length, dtype=dtype) subarr.fill(value) return subarr
def construct_1d_arraylike_from_scalar(value, length, dtype): """ create a np.ndarray / pandas type of specified shape and dtype filled with values Parameters ---------- value : scalar value length : int dtype : pandas_dtype / np.dtype Returns ------- np.ndarray / pandas type of length, filled with value """ if is_datetime64tz_dtype(dtype): from pandas import DatetimeIndex subarr = DatetimeIndex([value] * length, dtype=dtype) elif is_categorical_dtype(dtype): from pandas import Categorical subarr = Categorical([value] * length, dtype=dtype) else: if not isinstance(dtype, (np.dtype, type(np.dtype))): dtype = dtype.dtype if length and is_integer_dtype(dtype) and isna(value): # coerce if we have nan for an integer dtype dtype = np.dtype('float64') elif isinstance(dtype, np.dtype) and dtype.kind in ("U", "S"): # we need to coerce to object dtype to avoid # to allow numpy to take our string as a scalar value dtype = object if not isna(value): value = to_str(value) subarr = np.empty(length, dtype=dtype) subarr.fill(value) return subarr
[ "create", "a", "np", ".", "ndarray", "/", "pandas", "type", "of", "specified", "shape", "and", "dtype", "filled", "with", "values" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L1160-L1199
[ "def", "construct_1d_arraylike_from_scalar", "(", "value", ",", "length", ",", "dtype", ")", ":", "if", "is_datetime64tz_dtype", "(", "dtype", ")", ":", "from", "pandas", "import", "DatetimeIndex", "subarr", "=", "DatetimeIndex", "(", "[", "value", "]", "*", "length", ",", "dtype", "=", "dtype", ")", "elif", "is_categorical_dtype", "(", "dtype", ")", ":", "from", "pandas", "import", "Categorical", "subarr", "=", "Categorical", "(", "[", "value", "]", "*", "length", ",", "dtype", "=", "dtype", ")", "else", ":", "if", "not", "isinstance", "(", "dtype", ",", "(", "np", ".", "dtype", ",", "type", "(", "np", ".", "dtype", ")", ")", ")", ":", "dtype", "=", "dtype", ".", "dtype", "if", "length", "and", "is_integer_dtype", "(", "dtype", ")", "and", "isna", "(", "value", ")", ":", "# coerce if we have nan for an integer dtype", "dtype", "=", "np", ".", "dtype", "(", "'float64'", ")", "elif", "isinstance", "(", "dtype", ",", "np", ".", "dtype", ")", "and", "dtype", ".", "kind", "in", "(", "\"U\"", ",", "\"S\"", ")", ":", "# we need to coerce to object dtype to avoid", "# to allow numpy to take our string as a scalar value", "dtype", "=", "object", "if", "not", "isna", "(", "value", ")", ":", "value", "=", "to_str", "(", "value", ")", "subarr", "=", "np", ".", "empty", "(", "length", ",", "dtype", "=", "dtype", ")", "subarr", ".", "fill", "(", "value", ")", "return", "subarr" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
construct_1d_object_array_from_listlike
Transform any list-like object in a 1-dimensional numpy array of object dtype. Parameters ---------- values : any iterable which has a len() Raises ------ TypeError * If `values` does not have a len() Returns ------- 1-dimensional numpy array of dtype object
pandas/core/dtypes/cast.py
def construct_1d_object_array_from_listlike(values): """ Transform any list-like object in a 1-dimensional numpy array of object dtype. Parameters ---------- values : any iterable which has a len() Raises ------ TypeError * If `values` does not have a len() Returns ------- 1-dimensional numpy array of dtype object """ # numpy will try to interpret nested lists as further dimensions, hence # making a 1D array that contains list-likes is a bit tricky: result = np.empty(len(values), dtype='object') result[:] = values return result
def construct_1d_object_array_from_listlike(values): """ Transform any list-like object in a 1-dimensional numpy array of object dtype. Parameters ---------- values : any iterable which has a len() Raises ------ TypeError * If `values` does not have a len() Returns ------- 1-dimensional numpy array of dtype object """ # numpy will try to interpret nested lists as further dimensions, hence # making a 1D array that contains list-likes is a bit tricky: result = np.empty(len(values), dtype='object') result[:] = values return result
[ "Transform", "any", "list", "-", "like", "object", "in", "a", "1", "-", "dimensional", "numpy", "array", "of", "object", "dtype", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L1202-L1224
[ "def", "construct_1d_object_array_from_listlike", "(", "values", ")", ":", "# numpy will try to interpret nested lists as further dimensions, hence", "# making a 1D array that contains list-likes is a bit tricky:", "result", "=", "np", ".", "empty", "(", "len", "(", "values", ")", ",", "dtype", "=", "'object'", ")", "result", "[", ":", "]", "=", "values", "return", "result" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
construct_1d_ndarray_preserving_na
Construct a new ndarray, coercing `values` to `dtype`, preserving NA. Parameters ---------- values : Sequence dtype : numpy.dtype, optional copy : bool, default False Note that copies may still be made with ``copy=False`` if casting is required. Returns ------- arr : ndarray[dtype] Examples -------- >>> np.array([1.0, 2.0, None], dtype='str') array(['1.0', '2.0', 'None'], dtype='<U4') >>> construct_1d_ndarray_preserving_na([1.0, 2.0, None], dtype='str')
pandas/core/dtypes/cast.py
def construct_1d_ndarray_preserving_na(values, dtype=None, copy=False): """ Construct a new ndarray, coercing `values` to `dtype`, preserving NA. Parameters ---------- values : Sequence dtype : numpy.dtype, optional copy : bool, default False Note that copies may still be made with ``copy=False`` if casting is required. Returns ------- arr : ndarray[dtype] Examples -------- >>> np.array([1.0, 2.0, None], dtype='str') array(['1.0', '2.0', 'None'], dtype='<U4') >>> construct_1d_ndarray_preserving_na([1.0, 2.0, None], dtype='str') """ subarr = np.array(values, dtype=dtype, copy=copy) if dtype is not None and dtype.kind in ("U", "S"): # GH-21083 # We can't just return np.array(subarr, dtype='str') since # NumPy will convert the non-string objects into strings # Including NA values. Se we have to go # string -> object -> update NA, which requires an # additional pass over the data. na_values = isna(values) subarr2 = subarr.astype(object) subarr2[na_values] = np.asarray(values, dtype=object)[na_values] subarr = subarr2 return subarr
def construct_1d_ndarray_preserving_na(values, dtype=None, copy=False): """ Construct a new ndarray, coercing `values` to `dtype`, preserving NA. Parameters ---------- values : Sequence dtype : numpy.dtype, optional copy : bool, default False Note that copies may still be made with ``copy=False`` if casting is required. Returns ------- arr : ndarray[dtype] Examples -------- >>> np.array([1.0, 2.0, None], dtype='str') array(['1.0', '2.0', 'None'], dtype='<U4') >>> construct_1d_ndarray_preserving_na([1.0, 2.0, None], dtype='str') """ subarr = np.array(values, dtype=dtype, copy=copy) if dtype is not None and dtype.kind in ("U", "S"): # GH-21083 # We can't just return np.array(subarr, dtype='str') since # NumPy will convert the non-string objects into strings # Including NA values. Se we have to go # string -> object -> update NA, which requires an # additional pass over the data. na_values = isna(values) subarr2 = subarr.astype(object) subarr2[na_values] = np.asarray(values, dtype=object)[na_values] subarr = subarr2 return subarr
[ "Construct", "a", "new", "ndarray", "coercing", "values", "to", "dtype", "preserving", "NA", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L1227-L1266
[ "def", "construct_1d_ndarray_preserving_na", "(", "values", ",", "dtype", "=", "None", ",", "copy", "=", "False", ")", ":", "subarr", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "dtype", ",", "copy", "=", "copy", ")", "if", "dtype", "is", "not", "None", "and", "dtype", ".", "kind", "in", "(", "\"U\"", ",", "\"S\"", ")", ":", "# GH-21083", "# We can't just return np.array(subarr, dtype='str') since", "# NumPy will convert the non-string objects into strings", "# Including NA values. Se we have to go", "# string -> object -> update NA, which requires an", "# additional pass over the data.", "na_values", "=", "isna", "(", "values", ")", "subarr2", "=", "subarr", ".", "astype", "(", "object", ")", "subarr2", "[", "na_values", "]", "=", "np", ".", "asarray", "(", "values", ",", "dtype", "=", "object", ")", "[", "na_values", "]", "subarr", "=", "subarr2", "return", "subarr" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
maybe_cast_to_integer_array
Takes any dtype and returns the casted version, raising for when data is incompatible with integer/unsigned integer dtypes. .. versionadded:: 0.24.0 Parameters ---------- arr : array-like The array to cast. dtype : str, np.dtype The integer dtype to cast the array to. copy: boolean, default False Whether to make a copy of the array before returning. Returns ------- int_arr : ndarray An array of integer or unsigned integer dtype Raises ------ OverflowError : the dtype is incompatible with the data ValueError : loss of precision has occurred during casting Examples -------- If you try to coerce negative values to unsigned integers, it raises: >>> Series([-1], dtype="uint64") Traceback (most recent call last): ... OverflowError: Trying to coerce negative values to unsigned integers Also, if you try to coerce float values to integers, it raises: >>> Series([1, 2, 3.5], dtype="int64") Traceback (most recent call last): ... ValueError: Trying to coerce float values to integers
pandas/core/dtypes/cast.py
def maybe_cast_to_integer_array(arr, dtype, copy=False): """ Takes any dtype and returns the casted version, raising for when data is incompatible with integer/unsigned integer dtypes. .. versionadded:: 0.24.0 Parameters ---------- arr : array-like The array to cast. dtype : str, np.dtype The integer dtype to cast the array to. copy: boolean, default False Whether to make a copy of the array before returning. Returns ------- int_arr : ndarray An array of integer or unsigned integer dtype Raises ------ OverflowError : the dtype is incompatible with the data ValueError : loss of precision has occurred during casting Examples -------- If you try to coerce negative values to unsigned integers, it raises: >>> Series([-1], dtype="uint64") Traceback (most recent call last): ... OverflowError: Trying to coerce negative values to unsigned integers Also, if you try to coerce float values to integers, it raises: >>> Series([1, 2, 3.5], dtype="int64") Traceback (most recent call last): ... ValueError: Trying to coerce float values to integers """ try: if not hasattr(arr, "astype"): casted = np.array(arr, dtype=dtype, copy=copy) else: casted = arr.astype(dtype, copy=copy) except OverflowError: raise OverflowError("The elements provided in the data cannot all be " "casted to the dtype {dtype}".format(dtype=dtype)) if np.array_equal(arr, casted): return casted # We do this casting to allow for proper # data and dtype checking. # # We didn't do this earlier because NumPy # doesn't handle `uint64` correctly. arr = np.asarray(arr) if is_unsigned_integer_dtype(dtype) and (arr < 0).any(): raise OverflowError("Trying to coerce negative values " "to unsigned integers") if is_integer_dtype(dtype) and (is_float_dtype(arr) or is_object_dtype(arr)): raise ValueError("Trying to coerce float values to integers")
def maybe_cast_to_integer_array(arr, dtype, copy=False): """ Takes any dtype and returns the casted version, raising for when data is incompatible with integer/unsigned integer dtypes. .. versionadded:: 0.24.0 Parameters ---------- arr : array-like The array to cast. dtype : str, np.dtype The integer dtype to cast the array to. copy: boolean, default False Whether to make a copy of the array before returning. Returns ------- int_arr : ndarray An array of integer or unsigned integer dtype Raises ------ OverflowError : the dtype is incompatible with the data ValueError : loss of precision has occurred during casting Examples -------- If you try to coerce negative values to unsigned integers, it raises: >>> Series([-1], dtype="uint64") Traceback (most recent call last): ... OverflowError: Trying to coerce negative values to unsigned integers Also, if you try to coerce float values to integers, it raises: >>> Series([1, 2, 3.5], dtype="int64") Traceback (most recent call last): ... ValueError: Trying to coerce float values to integers """ try: if not hasattr(arr, "astype"): casted = np.array(arr, dtype=dtype, copy=copy) else: casted = arr.astype(dtype, copy=copy) except OverflowError: raise OverflowError("The elements provided in the data cannot all be " "casted to the dtype {dtype}".format(dtype=dtype)) if np.array_equal(arr, casted): return casted # We do this casting to allow for proper # data and dtype checking. # # We didn't do this earlier because NumPy # doesn't handle `uint64` correctly. arr = np.asarray(arr) if is_unsigned_integer_dtype(dtype) and (arr < 0).any(): raise OverflowError("Trying to coerce negative values " "to unsigned integers") if is_integer_dtype(dtype) and (is_float_dtype(arr) or is_object_dtype(arr)): raise ValueError("Trying to coerce float values to integers")
[ "Takes", "any", "dtype", "and", "returns", "the", "casted", "version", "raising", "for", "when", "data", "is", "incompatible", "with", "integer", "/", "unsigned", "integer", "dtypes", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/cast.py#L1269-L1337
[ "def", "maybe_cast_to_integer_array", "(", "arr", ",", "dtype", ",", "copy", "=", "False", ")", ":", "try", ":", "if", "not", "hasattr", "(", "arr", ",", "\"astype\"", ")", ":", "casted", "=", "np", ".", "array", "(", "arr", ",", "dtype", "=", "dtype", ",", "copy", "=", "copy", ")", "else", ":", "casted", "=", "arr", ".", "astype", "(", "dtype", ",", "copy", "=", "copy", ")", "except", "OverflowError", ":", "raise", "OverflowError", "(", "\"The elements provided in the data cannot all be \"", "\"casted to the dtype {dtype}\"", ".", "format", "(", "dtype", "=", "dtype", ")", ")", "if", "np", ".", "array_equal", "(", "arr", ",", "casted", ")", ":", "return", "casted", "# We do this casting to allow for proper", "# data and dtype checking.", "#", "# We didn't do this earlier because NumPy", "# doesn't handle `uint64` correctly.", "arr", "=", "np", ".", "asarray", "(", "arr", ")", "if", "is_unsigned_integer_dtype", "(", "dtype", ")", "and", "(", "arr", "<", "0", ")", ".", "any", "(", ")", ":", "raise", "OverflowError", "(", "\"Trying to coerce negative values \"", "\"to unsigned integers\"", ")", "if", "is_integer_dtype", "(", "dtype", ")", "and", "(", "is_float_dtype", "(", "arr", ")", "or", "is_object_dtype", "(", "arr", ")", ")", ":", "raise", "ValueError", "(", "\"Trying to coerce float values to integers\"", ")" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
scatter_plot
Make a scatter plot from two DataFrame columns Parameters ---------- data : DataFrame x : Column name for the x-axis values y : Column name for the y-axis values ax : Matplotlib axis object figsize : A tuple (width, height) in inches grid : Setting this to True will show the grid kwargs : other plotting keyword arguments To be passed to scatter function Returns ------- matplotlib.Figure
pandas/plotting/_core.py
def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs): """ Make a scatter plot from two DataFrame columns Parameters ---------- data : DataFrame x : Column name for the x-axis values y : Column name for the y-axis values ax : Matplotlib axis object figsize : A tuple (width, height) in inches grid : Setting this to True will show the grid kwargs : other plotting keyword arguments To be passed to scatter function Returns ------- matplotlib.Figure """ import matplotlib.pyplot as plt kwargs.setdefault('edgecolors', 'none') def plot_group(group, ax): xvals = group[x].values yvals = group[y].values ax.scatter(xvals, yvals, **kwargs) ax.grid(grid) if by is not None: fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax) else: if ax is None: fig = plt.figure() ax = fig.add_subplot(111) else: fig = ax.get_figure() plot_group(data, ax) ax.set_ylabel(pprint_thing(y)) ax.set_xlabel(pprint_thing(x)) ax.grid(grid) return fig
def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs): """ Make a scatter plot from two DataFrame columns Parameters ---------- data : DataFrame x : Column name for the x-axis values y : Column name for the y-axis values ax : Matplotlib axis object figsize : A tuple (width, height) in inches grid : Setting this to True will show the grid kwargs : other plotting keyword arguments To be passed to scatter function Returns ------- matplotlib.Figure """ import matplotlib.pyplot as plt kwargs.setdefault('edgecolors', 'none') def plot_group(group, ax): xvals = group[x].values yvals = group[y].values ax.scatter(xvals, yvals, **kwargs) ax.grid(grid) if by is not None: fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax) else: if ax is None: fig = plt.figure() ax = fig.add_subplot(111) else: fig = ax.get_figure() plot_group(data, ax) ax.set_ylabel(pprint_thing(y)) ax.set_xlabel(pprint_thing(x)) ax.grid(grid) return fig
[ "Make", "a", "scatter", "plot", "from", "two", "DataFrame", "columns" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L2284-L2328
[ "def", "scatter_plot", "(", "data", ",", "x", ",", "y", ",", "by", "=", "None", ",", "ax", "=", "None", ",", "figsize", "=", "None", ",", "grid", "=", "False", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "kwargs", ".", "setdefault", "(", "'edgecolors'", ",", "'none'", ")", "def", "plot_group", "(", "group", ",", "ax", ")", ":", "xvals", "=", "group", "[", "x", "]", ".", "values", "yvals", "=", "group", "[", "y", "]", ".", "values", "ax", ".", "scatter", "(", "xvals", ",", "yvals", ",", "*", "*", "kwargs", ")", "ax", ".", "grid", "(", "grid", ")", "if", "by", "is", "not", "None", ":", "fig", "=", "_grouped_plot", "(", "plot_group", ",", "data", ",", "by", "=", "by", ",", "figsize", "=", "figsize", ",", "ax", "=", "ax", ")", "else", ":", "if", "ax", "is", "None", ":", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "plot_group", "(", "data", ",", "ax", ")", "ax", ".", "set_ylabel", "(", "pprint_thing", "(", "y", ")", ")", "ax", ".", "set_xlabel", "(", "pprint_thing", "(", "x", ")", ")", "ax", ".", "grid", "(", "grid", ")", "return", "fig" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
hist_frame
Make a histogram of the DataFrame's. A `histogram`_ is a representation of the distribution of data. This function calls :meth:`matplotlib.pyplot.hist`, on each series in the DataFrame, resulting in one histogram per column. .. _histogram: https://en.wikipedia.org/wiki/Histogram Parameters ---------- data : DataFrame The pandas object holding the data. column : string or sequence If passed, will be used to limit data to a subset of columns. by : object, optional If passed, then used to form histograms for separate groups. grid : bool, default True Whether to show axis grid lines. xlabelsize : int, default None If specified changes the x-axis label size. xrot : float, default None Rotation of x axis labels. For example, a value of 90 displays the x labels rotated 90 degrees clockwise. ylabelsize : int, default None If specified changes the y-axis label size. yrot : float, default None Rotation of y axis labels. For example, a value of 90 displays the y labels rotated 90 degrees clockwise. ax : Matplotlib axes object, default None The axes to plot the histogram on. sharex : bool, default True if ax is None else False In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in. Note that passing in both an ax and sharex=True will alter all x axis labels for all subplots in a figure. sharey : bool, default False In case subplots=True, share y axis and set some y axis labels to invisible. figsize : tuple The size in inches of the figure to create. Uses the value in `matplotlib.rcParams` by default. layout : tuple, optional Tuple of (rows, columns) for the layout of the histograms. bins : integer or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. **kwds All other plotting keyword arguments to be passed to :meth:`matplotlib.pyplot.hist`. Returns ------- matplotlib.AxesSubplot or numpy.ndarray of them See Also -------- matplotlib.pyplot.hist : Plot a histogram using matplotlib. Examples -------- .. plot:: :context: close-figs This example draws a histogram based on the length and width of some animals, displayed in three bins >>> df = pd.DataFrame({ ... 'length': [1.5, 0.5, 1.2, 0.9, 3], ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1] ... }, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3)
pandas/plotting/_core.py
def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, **kwds): """ Make a histogram of the DataFrame's. A `histogram`_ is a representation of the distribution of data. This function calls :meth:`matplotlib.pyplot.hist`, on each series in the DataFrame, resulting in one histogram per column. .. _histogram: https://en.wikipedia.org/wiki/Histogram Parameters ---------- data : DataFrame The pandas object holding the data. column : string or sequence If passed, will be used to limit data to a subset of columns. by : object, optional If passed, then used to form histograms for separate groups. grid : bool, default True Whether to show axis grid lines. xlabelsize : int, default None If specified changes the x-axis label size. xrot : float, default None Rotation of x axis labels. For example, a value of 90 displays the x labels rotated 90 degrees clockwise. ylabelsize : int, default None If specified changes the y-axis label size. yrot : float, default None Rotation of y axis labels. For example, a value of 90 displays the y labels rotated 90 degrees clockwise. ax : Matplotlib axes object, default None The axes to plot the histogram on. sharex : bool, default True if ax is None else False In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in. Note that passing in both an ax and sharex=True will alter all x axis labels for all subplots in a figure. sharey : bool, default False In case subplots=True, share y axis and set some y axis labels to invisible. figsize : tuple The size in inches of the figure to create. Uses the value in `matplotlib.rcParams` by default. layout : tuple, optional Tuple of (rows, columns) for the layout of the histograms. bins : integer or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. **kwds All other plotting keyword arguments to be passed to :meth:`matplotlib.pyplot.hist`. Returns ------- matplotlib.AxesSubplot or numpy.ndarray of them See Also -------- matplotlib.pyplot.hist : Plot a histogram using matplotlib. Examples -------- .. plot:: :context: close-figs This example draws a histogram based on the length and width of some animals, displayed in three bins >>> df = pd.DataFrame({ ... 'length': [1.5, 0.5, 1.2, 0.9, 3], ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1] ... }, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3) """ _raise_if_no_mpl() _converter._WARN = False if by is not None: axes = grouped_hist(data, column=column, by=by, ax=ax, grid=grid, figsize=figsize, sharex=sharex, sharey=sharey, layout=layout, bins=bins, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, **kwds) return axes if column is not None: if not isinstance(column, (list, np.ndarray, ABCIndexClass)): column = [column] data = data[column] data = data._get_numeric_data() naxes = len(data.columns) fig, axes = _subplots(naxes=naxes, ax=ax, squeeze=False, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout) _axes = _flatten(axes) for i, col in enumerate(com.try_sort(data.columns)): ax = _axes[i] ax.hist(data[col].dropna().values, bins=bins, **kwds) ax.set_title(col) ax.grid(grid) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) fig.subplots_adjust(wspace=0.3, hspace=0.3) return axes
def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, **kwds): """ Make a histogram of the DataFrame's. A `histogram`_ is a representation of the distribution of data. This function calls :meth:`matplotlib.pyplot.hist`, on each series in the DataFrame, resulting in one histogram per column. .. _histogram: https://en.wikipedia.org/wiki/Histogram Parameters ---------- data : DataFrame The pandas object holding the data. column : string or sequence If passed, will be used to limit data to a subset of columns. by : object, optional If passed, then used to form histograms for separate groups. grid : bool, default True Whether to show axis grid lines. xlabelsize : int, default None If specified changes the x-axis label size. xrot : float, default None Rotation of x axis labels. For example, a value of 90 displays the x labels rotated 90 degrees clockwise. ylabelsize : int, default None If specified changes the y-axis label size. yrot : float, default None Rotation of y axis labels. For example, a value of 90 displays the y labels rotated 90 degrees clockwise. ax : Matplotlib axes object, default None The axes to plot the histogram on. sharex : bool, default True if ax is None else False In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in. Note that passing in both an ax and sharex=True will alter all x axis labels for all subplots in a figure. sharey : bool, default False In case subplots=True, share y axis and set some y axis labels to invisible. figsize : tuple The size in inches of the figure to create. Uses the value in `matplotlib.rcParams` by default. layout : tuple, optional Tuple of (rows, columns) for the layout of the histograms. bins : integer or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. **kwds All other plotting keyword arguments to be passed to :meth:`matplotlib.pyplot.hist`. Returns ------- matplotlib.AxesSubplot or numpy.ndarray of them See Also -------- matplotlib.pyplot.hist : Plot a histogram using matplotlib. Examples -------- .. plot:: :context: close-figs This example draws a histogram based on the length and width of some animals, displayed in three bins >>> df = pd.DataFrame({ ... 'length': [1.5, 0.5, 1.2, 0.9, 3], ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1] ... }, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3) """ _raise_if_no_mpl() _converter._WARN = False if by is not None: axes = grouped_hist(data, column=column, by=by, ax=ax, grid=grid, figsize=figsize, sharex=sharex, sharey=sharey, layout=layout, bins=bins, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, **kwds) return axes if column is not None: if not isinstance(column, (list, np.ndarray, ABCIndexClass)): column = [column] data = data[column] data = data._get_numeric_data() naxes = len(data.columns) fig, axes = _subplots(naxes=naxes, ax=ax, squeeze=False, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout) _axes = _flatten(axes) for i, col in enumerate(com.try_sort(data.columns)): ax = _axes[i] ax.hist(data[col].dropna().values, bins=bins, **kwds) ax.set_title(col) ax.grid(grid) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) fig.subplots_adjust(wspace=0.3, hspace=0.3) return axes
[ "Make", "a", "histogram", "of", "the", "DataFrame", "s", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L2331-L2443
[ "def", "hist_frame", "(", "data", ",", "column", "=", "None", ",", "by", "=", "None", ",", "grid", "=", "True", ",", "xlabelsize", "=", "None", ",", "xrot", "=", "None", ",", "ylabelsize", "=", "None", ",", "yrot", "=", "None", ",", "ax", "=", "None", ",", "sharex", "=", "False", ",", "sharey", "=", "False", ",", "figsize", "=", "None", ",", "layout", "=", "None", ",", "bins", "=", "10", ",", "*", "*", "kwds", ")", ":", "_raise_if_no_mpl", "(", ")", "_converter", ".", "_WARN", "=", "False", "if", "by", "is", "not", "None", ":", "axes", "=", "grouped_hist", "(", "data", ",", "column", "=", "column", ",", "by", "=", "by", ",", "ax", "=", "ax", ",", "grid", "=", "grid", ",", "figsize", "=", "figsize", ",", "sharex", "=", "sharex", ",", "sharey", "=", "sharey", ",", "layout", "=", "layout", ",", "bins", "=", "bins", ",", "xlabelsize", "=", "xlabelsize", ",", "xrot", "=", "xrot", ",", "ylabelsize", "=", "ylabelsize", ",", "yrot", "=", "yrot", ",", "*", "*", "kwds", ")", "return", "axes", "if", "column", "is", "not", "None", ":", "if", "not", "isinstance", "(", "column", ",", "(", "list", ",", "np", ".", "ndarray", ",", "ABCIndexClass", ")", ")", ":", "column", "=", "[", "column", "]", "data", "=", "data", "[", "column", "]", "data", "=", "data", ".", "_get_numeric_data", "(", ")", "naxes", "=", "len", "(", "data", ".", "columns", ")", "fig", ",", "axes", "=", "_subplots", "(", "naxes", "=", "naxes", ",", "ax", "=", "ax", ",", "squeeze", "=", "False", ",", "sharex", "=", "sharex", ",", "sharey", "=", "sharey", ",", "figsize", "=", "figsize", ",", "layout", "=", "layout", ")", "_axes", "=", "_flatten", "(", "axes", ")", "for", "i", ",", "col", "in", "enumerate", "(", "com", ".", "try_sort", "(", "data", ".", "columns", ")", ")", ":", "ax", "=", "_axes", "[", "i", "]", "ax", ".", "hist", "(", "data", "[", "col", "]", ".", "dropna", "(", ")", ".", "values", ",", "bins", "=", "bins", ",", "*", "*", "kwds", ")", "ax", ".", "set_title", "(", "col", ")", "ax", ".", "grid", "(", "grid", ")", "_set_ticks_props", "(", "axes", ",", "xlabelsize", "=", "xlabelsize", ",", "xrot", "=", "xrot", ",", "ylabelsize", "=", "ylabelsize", ",", "yrot", "=", "yrot", ")", "fig", ".", "subplots_adjust", "(", "wspace", "=", "0.3", ",", "hspace", "=", "0.3", ")", "return", "axes" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
hist_series
Draw histogram of the input series using matplotlib. Parameters ---------- by : object, optional If passed, then used to form histograms for separate groups ax : matplotlib axis object If not passed, uses gca() grid : bool, default True Whether to show axis grid lines xlabelsize : int, default None If specified changes the x-axis label size xrot : float, default None rotation of x axis labels ylabelsize : int, default None If specified changes the y-axis label size yrot : float, default None rotation of y axis labels figsize : tuple, default None figure size in inches by default bins : integer or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. bins : integer, default 10 Number of histogram bins to be used `**kwds` : keywords To be passed to the actual plotting function See Also -------- matplotlib.axes.Axes.hist : Plot a histogram using matplotlib.
pandas/plotting/_core.py
def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, figsize=None, bins=10, **kwds): """ Draw histogram of the input series using matplotlib. Parameters ---------- by : object, optional If passed, then used to form histograms for separate groups ax : matplotlib axis object If not passed, uses gca() grid : bool, default True Whether to show axis grid lines xlabelsize : int, default None If specified changes the x-axis label size xrot : float, default None rotation of x axis labels ylabelsize : int, default None If specified changes the y-axis label size yrot : float, default None rotation of y axis labels figsize : tuple, default None figure size in inches by default bins : integer or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. bins : integer, default 10 Number of histogram bins to be used `**kwds` : keywords To be passed to the actual plotting function See Also -------- matplotlib.axes.Axes.hist : Plot a histogram using matplotlib. """ import matplotlib.pyplot as plt if by is None: if kwds.get('layout', None) is not None: raise ValueError("The 'layout' keyword is not supported when " "'by' is None") # hack until the plotting interface is a bit more unified fig = kwds.pop('figure', plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize)) if (figsize is not None and tuple(figsize) != tuple(fig.get_size_inches())): fig.set_size_inches(*figsize, forward=True) if ax is None: ax = fig.gca() elif ax.get_figure() != fig: raise AssertionError('passed axis not bound to passed figure') values = self.dropna().values ax.hist(values, bins=bins, **kwds) ax.grid(grid) axes = np.array([ax]) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) else: if 'figure' in kwds: raise ValueError("Cannot pass 'figure' when using the " "'by' argument, since a new 'Figure' instance " "will be created") axes = grouped_hist(self, by=by, ax=ax, grid=grid, figsize=figsize, bins=bins, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, **kwds) if hasattr(axes, 'ndim'): if axes.ndim == 1 and len(axes) == 1: return axes[0] return axes
def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, figsize=None, bins=10, **kwds): """ Draw histogram of the input series using matplotlib. Parameters ---------- by : object, optional If passed, then used to form histograms for separate groups ax : matplotlib axis object If not passed, uses gca() grid : bool, default True Whether to show axis grid lines xlabelsize : int, default None If specified changes the x-axis label size xrot : float, default None rotation of x axis labels ylabelsize : int, default None If specified changes the y-axis label size yrot : float, default None rotation of y axis labels figsize : tuple, default None figure size in inches by default bins : integer or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. bins : integer, default 10 Number of histogram bins to be used `**kwds` : keywords To be passed to the actual plotting function See Also -------- matplotlib.axes.Axes.hist : Plot a histogram using matplotlib. """ import matplotlib.pyplot as plt if by is None: if kwds.get('layout', None) is not None: raise ValueError("The 'layout' keyword is not supported when " "'by' is None") # hack until the plotting interface is a bit more unified fig = kwds.pop('figure', plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize)) if (figsize is not None and tuple(figsize) != tuple(fig.get_size_inches())): fig.set_size_inches(*figsize, forward=True) if ax is None: ax = fig.gca() elif ax.get_figure() != fig: raise AssertionError('passed axis not bound to passed figure') values = self.dropna().values ax.hist(values, bins=bins, **kwds) ax.grid(grid) axes = np.array([ax]) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) else: if 'figure' in kwds: raise ValueError("Cannot pass 'figure' when using the " "'by' argument, since a new 'Figure' instance " "will be created") axes = grouped_hist(self, by=by, ax=ax, grid=grid, figsize=figsize, bins=bins, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, **kwds) if hasattr(axes, 'ndim'): if axes.ndim == 1 and len(axes) == 1: return axes[0] return axes
[ "Draw", "histogram", "of", "the", "input", "series", "using", "matplotlib", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L2446-L2521
[ "def", "hist_series", "(", "self", ",", "by", "=", "None", ",", "ax", "=", "None", ",", "grid", "=", "True", ",", "xlabelsize", "=", "None", ",", "xrot", "=", "None", ",", "ylabelsize", "=", "None", ",", "yrot", "=", "None", ",", "figsize", "=", "None", ",", "bins", "=", "10", ",", "*", "*", "kwds", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "by", "is", "None", ":", "if", "kwds", ".", "get", "(", "'layout'", ",", "None", ")", "is", "not", "None", ":", "raise", "ValueError", "(", "\"The 'layout' keyword is not supported when \"", "\"'by' is None\"", ")", "# hack until the plotting interface is a bit more unified", "fig", "=", "kwds", ".", "pop", "(", "'figure'", ",", "plt", ".", "gcf", "(", ")", "if", "plt", ".", "get_fignums", "(", ")", "else", "plt", ".", "figure", "(", "figsize", "=", "figsize", ")", ")", "if", "(", "figsize", "is", "not", "None", "and", "tuple", "(", "figsize", ")", "!=", "tuple", "(", "fig", ".", "get_size_inches", "(", ")", ")", ")", ":", "fig", ".", "set_size_inches", "(", "*", "figsize", ",", "forward", "=", "True", ")", "if", "ax", "is", "None", ":", "ax", "=", "fig", ".", "gca", "(", ")", "elif", "ax", ".", "get_figure", "(", ")", "!=", "fig", ":", "raise", "AssertionError", "(", "'passed axis not bound to passed figure'", ")", "values", "=", "self", ".", "dropna", "(", ")", ".", "values", "ax", ".", "hist", "(", "values", ",", "bins", "=", "bins", ",", "*", "*", "kwds", ")", "ax", ".", "grid", "(", "grid", ")", "axes", "=", "np", ".", "array", "(", "[", "ax", "]", ")", "_set_ticks_props", "(", "axes", ",", "xlabelsize", "=", "xlabelsize", ",", "xrot", "=", "xrot", ",", "ylabelsize", "=", "ylabelsize", ",", "yrot", "=", "yrot", ")", "else", ":", "if", "'figure'", "in", "kwds", ":", "raise", "ValueError", "(", "\"Cannot pass 'figure' when using the \"", "\"'by' argument, since a new 'Figure' instance \"", "\"will be created\"", ")", "axes", "=", "grouped_hist", "(", "self", ",", "by", "=", "by", ",", "ax", "=", "ax", ",", "grid", "=", "grid", ",", "figsize", "=", "figsize", ",", "bins", "=", "bins", ",", "xlabelsize", "=", "xlabelsize", ",", "xrot", "=", "xrot", ",", "ylabelsize", "=", "ylabelsize", ",", "yrot", "=", "yrot", ",", "*", "*", "kwds", ")", "if", "hasattr", "(", "axes", ",", "'ndim'", ")", ":", "if", "axes", ".", "ndim", "==", "1", "and", "len", "(", "axes", ")", "==", "1", ":", "return", "axes", "[", "0", "]", "return", "axes" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
grouped_hist
Grouped histogram Parameters ---------- data : Series/DataFrame column : object, optional by : object, optional ax : axes, optional bins : int, default 50 figsize : tuple, optional layout : optional sharex : bool, default False sharey : bool, default False rot : int, default 90 grid : bool, default True kwargs : dict, keyword arguments passed to matplotlib.Axes.hist Returns ------- collection of Matplotlib Axes
pandas/plotting/_core.py
def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None, layout=None, sharex=False, sharey=False, rot=90, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, **kwargs): """ Grouped histogram Parameters ---------- data : Series/DataFrame column : object, optional by : object, optional ax : axes, optional bins : int, default 50 figsize : tuple, optional layout : optional sharex : bool, default False sharey : bool, default False rot : int, default 90 grid : bool, default True kwargs : dict, keyword arguments passed to matplotlib.Axes.hist Returns ------- collection of Matplotlib Axes """ _raise_if_no_mpl() _converter._WARN = False def plot_group(group, ax): ax.hist(group.dropna().values, bins=bins, **kwargs) xrot = xrot or rot fig, axes = _grouped_plot(plot_group, data, column=column, by=by, sharex=sharex, sharey=sharey, ax=ax, figsize=figsize, layout=layout, rot=rot) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3) return axes
def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None, layout=None, sharex=False, sharey=False, rot=90, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, **kwargs): """ Grouped histogram Parameters ---------- data : Series/DataFrame column : object, optional by : object, optional ax : axes, optional bins : int, default 50 figsize : tuple, optional layout : optional sharex : bool, default False sharey : bool, default False rot : int, default 90 grid : bool, default True kwargs : dict, keyword arguments passed to matplotlib.Axes.hist Returns ------- collection of Matplotlib Axes """ _raise_if_no_mpl() _converter._WARN = False def plot_group(group, ax): ax.hist(group.dropna().values, bins=bins, **kwargs) xrot = xrot or rot fig, axes = _grouped_plot(plot_group, data, column=column, by=by, sharex=sharex, sharey=sharey, ax=ax, figsize=figsize, layout=layout, rot=rot) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3) return axes
[ "Grouped", "histogram" ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L2524-L2567
[ "def", "grouped_hist", "(", "data", ",", "column", "=", "None", ",", "by", "=", "None", ",", "ax", "=", "None", ",", "bins", "=", "50", ",", "figsize", "=", "None", ",", "layout", "=", "None", ",", "sharex", "=", "False", ",", "sharey", "=", "False", ",", "rot", "=", "90", ",", "grid", "=", "True", ",", "xlabelsize", "=", "None", ",", "xrot", "=", "None", ",", "ylabelsize", "=", "None", ",", "yrot", "=", "None", ",", "*", "*", "kwargs", ")", ":", "_raise_if_no_mpl", "(", ")", "_converter", ".", "_WARN", "=", "False", "def", "plot_group", "(", "group", ",", "ax", ")", ":", "ax", ".", "hist", "(", "group", ".", "dropna", "(", ")", ".", "values", ",", "bins", "=", "bins", ",", "*", "*", "kwargs", ")", "xrot", "=", "xrot", "or", "rot", "fig", ",", "axes", "=", "_grouped_plot", "(", "plot_group", ",", "data", ",", "column", "=", "column", ",", "by", "=", "by", ",", "sharex", "=", "sharex", ",", "sharey", "=", "sharey", ",", "ax", "=", "ax", ",", "figsize", "=", "figsize", ",", "layout", "=", "layout", ",", "rot", "=", "rot", ")", "_set_ticks_props", "(", "axes", ",", "xlabelsize", "=", "xlabelsize", ",", "xrot", "=", "xrot", ",", "ylabelsize", "=", "ylabelsize", ",", "yrot", "=", "yrot", ")", "fig", ".", "subplots_adjust", "(", "bottom", "=", "0.15", ",", "top", "=", "0.9", ",", "left", "=", "0.1", ",", "right", "=", "0.9", ",", "hspace", "=", "0.5", ",", "wspace", "=", "0.3", ")", "return", "axes" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037
train
boxplot_frame_groupby
Make box plots from DataFrameGroupBy data. Parameters ---------- grouped : Grouped DataFrame subplots : bool * ``False`` - no subplots will be used * ``True`` - create a subplot for each group column : column name or list of names, or vector Can be any valid input to groupby fontsize : int or string rot : label rotation angle grid : Setting this to True will show the grid ax : Matplotlib axis object, default None figsize : A tuple (width, height) in inches layout : tuple (optional) (rows, columns) for the layout of the plot sharex : bool, default False Whether x-axes will be shared among subplots .. versionadded:: 0.23.1 sharey : bool, default True Whether y-axes will be shared among subplots .. versionadded:: 0.23.1 `**kwds` : Keyword Arguments All other plotting keyword arguments to be passed to matplotlib's boxplot function Returns ------- dict of key/value = group key/DataFrame.boxplot return value or DataFrame.boxplot return value in case subplots=figures=False Examples -------- >>> import itertools >>> tuples = [t for t in itertools.product(range(1000), range(4))] >>> index = pd.MultiIndex.from_tuples(tuples, names=['lvl0', 'lvl1']) >>> data = np.random.randn(len(index),4) >>> df = pd.DataFrame(data, columns=list('ABCD'), index=index) >>> >>> grouped = df.groupby(level='lvl1') >>> boxplot_frame_groupby(grouped) >>> >>> grouped = df.unstack(level='lvl1').groupby(level=0, axis=1) >>> boxplot_frame_groupby(grouped, subplots=False)
pandas/plotting/_core.py
def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None, rot=0, grid=True, ax=None, figsize=None, layout=None, sharex=False, sharey=True, **kwds): """ Make box plots from DataFrameGroupBy data. Parameters ---------- grouped : Grouped DataFrame subplots : bool * ``False`` - no subplots will be used * ``True`` - create a subplot for each group column : column name or list of names, or vector Can be any valid input to groupby fontsize : int or string rot : label rotation angle grid : Setting this to True will show the grid ax : Matplotlib axis object, default None figsize : A tuple (width, height) in inches layout : tuple (optional) (rows, columns) for the layout of the plot sharex : bool, default False Whether x-axes will be shared among subplots .. versionadded:: 0.23.1 sharey : bool, default True Whether y-axes will be shared among subplots .. versionadded:: 0.23.1 `**kwds` : Keyword Arguments All other plotting keyword arguments to be passed to matplotlib's boxplot function Returns ------- dict of key/value = group key/DataFrame.boxplot return value or DataFrame.boxplot return value in case subplots=figures=False Examples -------- >>> import itertools >>> tuples = [t for t in itertools.product(range(1000), range(4))] >>> index = pd.MultiIndex.from_tuples(tuples, names=['lvl0', 'lvl1']) >>> data = np.random.randn(len(index),4) >>> df = pd.DataFrame(data, columns=list('ABCD'), index=index) >>> >>> grouped = df.groupby(level='lvl1') >>> boxplot_frame_groupby(grouped) >>> >>> grouped = df.unstack(level='lvl1').groupby(level=0, axis=1) >>> boxplot_frame_groupby(grouped, subplots=False) """ _raise_if_no_mpl() _converter._WARN = False if subplots is True: naxes = len(grouped) fig, axes = _subplots(naxes=naxes, squeeze=False, ax=ax, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout) axes = _flatten(axes) from pandas.core.series import Series ret = Series() for (key, group), ax in zip(grouped, axes): d = group.boxplot(ax=ax, column=column, fontsize=fontsize, rot=rot, grid=grid, **kwds) ax.set_title(pprint_thing(key)) ret.loc[key] = d fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) else: from pandas.core.reshape.concat import concat keys, frames = zip(*grouped) if grouped.axis == 0: df = concat(frames, keys=keys, axis=1) else: if len(frames) > 1: df = frames[0].join(frames[1::]) else: df = frames[0] ret = df.boxplot(column=column, fontsize=fontsize, rot=rot, grid=grid, ax=ax, figsize=figsize, layout=layout, **kwds) return ret
def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None, rot=0, grid=True, ax=None, figsize=None, layout=None, sharex=False, sharey=True, **kwds): """ Make box plots from DataFrameGroupBy data. Parameters ---------- grouped : Grouped DataFrame subplots : bool * ``False`` - no subplots will be used * ``True`` - create a subplot for each group column : column name or list of names, or vector Can be any valid input to groupby fontsize : int or string rot : label rotation angle grid : Setting this to True will show the grid ax : Matplotlib axis object, default None figsize : A tuple (width, height) in inches layout : tuple (optional) (rows, columns) for the layout of the plot sharex : bool, default False Whether x-axes will be shared among subplots .. versionadded:: 0.23.1 sharey : bool, default True Whether y-axes will be shared among subplots .. versionadded:: 0.23.1 `**kwds` : Keyword Arguments All other plotting keyword arguments to be passed to matplotlib's boxplot function Returns ------- dict of key/value = group key/DataFrame.boxplot return value or DataFrame.boxplot return value in case subplots=figures=False Examples -------- >>> import itertools >>> tuples = [t for t in itertools.product(range(1000), range(4))] >>> index = pd.MultiIndex.from_tuples(tuples, names=['lvl0', 'lvl1']) >>> data = np.random.randn(len(index),4) >>> df = pd.DataFrame(data, columns=list('ABCD'), index=index) >>> >>> grouped = df.groupby(level='lvl1') >>> boxplot_frame_groupby(grouped) >>> >>> grouped = df.unstack(level='lvl1').groupby(level=0, axis=1) >>> boxplot_frame_groupby(grouped, subplots=False) """ _raise_if_no_mpl() _converter._WARN = False if subplots is True: naxes = len(grouped) fig, axes = _subplots(naxes=naxes, squeeze=False, ax=ax, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout) axes = _flatten(axes) from pandas.core.series import Series ret = Series() for (key, group), ax in zip(grouped, axes): d = group.boxplot(ax=ax, column=column, fontsize=fontsize, rot=rot, grid=grid, **kwds) ax.set_title(pprint_thing(key)) ret.loc[key] = d fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) else: from pandas.core.reshape.concat import concat keys, frames = zip(*grouped) if grouped.axis == 0: df = concat(frames, keys=keys, axis=1) else: if len(frames) > 1: df = frames[0].join(frames[1::]) else: df = frames[0] ret = df.boxplot(column=column, fontsize=fontsize, rot=rot, grid=grid, ax=ax, figsize=figsize, layout=layout, **kwds) return ret
[ "Make", "box", "plots", "from", "DataFrameGroupBy", "data", "." ]
pandas-dev/pandas
python
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L2570-L2653
[ "def", "boxplot_frame_groupby", "(", "grouped", ",", "subplots", "=", "True", ",", "column", "=", "None", ",", "fontsize", "=", "None", ",", "rot", "=", "0", ",", "grid", "=", "True", ",", "ax", "=", "None", ",", "figsize", "=", "None", ",", "layout", "=", "None", ",", "sharex", "=", "False", ",", "sharey", "=", "True", ",", "*", "*", "kwds", ")", ":", "_raise_if_no_mpl", "(", ")", "_converter", ".", "_WARN", "=", "False", "if", "subplots", "is", "True", ":", "naxes", "=", "len", "(", "grouped", ")", "fig", ",", "axes", "=", "_subplots", "(", "naxes", "=", "naxes", ",", "squeeze", "=", "False", ",", "ax", "=", "ax", ",", "sharex", "=", "sharex", ",", "sharey", "=", "sharey", ",", "figsize", "=", "figsize", ",", "layout", "=", "layout", ")", "axes", "=", "_flatten", "(", "axes", ")", "from", "pandas", ".", "core", ".", "series", "import", "Series", "ret", "=", "Series", "(", ")", "for", "(", "key", ",", "group", ")", ",", "ax", "in", "zip", "(", "grouped", ",", "axes", ")", ":", "d", "=", "group", ".", "boxplot", "(", "ax", "=", "ax", ",", "column", "=", "column", ",", "fontsize", "=", "fontsize", ",", "rot", "=", "rot", ",", "grid", "=", "grid", ",", "*", "*", "kwds", ")", "ax", ".", "set_title", "(", "pprint_thing", "(", "key", ")", ")", "ret", ".", "loc", "[", "key", "]", "=", "d", "fig", ".", "subplots_adjust", "(", "bottom", "=", "0.15", ",", "top", "=", "0.9", ",", "left", "=", "0.1", ",", "right", "=", "0.9", ",", "wspace", "=", "0.2", ")", "else", ":", "from", "pandas", ".", "core", ".", "reshape", ".", "concat", "import", "concat", "keys", ",", "frames", "=", "zip", "(", "*", "grouped", ")", "if", "grouped", ".", "axis", "==", "0", ":", "df", "=", "concat", "(", "frames", ",", "keys", "=", "keys", ",", "axis", "=", "1", ")", "else", ":", "if", "len", "(", "frames", ")", ">", "1", ":", "df", "=", "frames", "[", "0", "]", ".", "join", "(", "frames", "[", "1", ":", ":", "]", ")", "else", ":", "df", "=", "frames", "[", "0", "]", "ret", "=", "df", ".", "boxplot", "(", "column", "=", "column", ",", "fontsize", "=", "fontsize", ",", "rot", "=", "rot", ",", "grid", "=", "grid", ",", "ax", "=", "ax", ",", "figsize", "=", "figsize", ",", "layout", "=", "layout", ",", "*", "*", "kwds", ")", "return", "ret" ]
9feb3ad92cc0397a04b665803a49299ee7aa1037