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 | DatetimeLikeArrayMixin.repeat | Repeat elements of an array.
See Also
--------
numpy.ndarray.repeat | pandas/core/arrays/datetimelike.py | def repeat(self, repeats, *args, **kwargs):
"""
Repeat elements of an array.
See Also
--------
numpy.ndarray.repeat
"""
nv.validate_repeat(args, kwargs)
values = self._data.repeat(repeats)
return type(self)(values.view('i8'), dtype=self.dtype) | def repeat(self, repeats, *args, **kwargs):
"""
Repeat elements of an array.
See Also
--------
numpy.ndarray.repeat
"""
nv.validate_repeat(args, kwargs)
values = self._data.repeat(repeats)
return type(self)(values.view('i8'), dtype=self.dtype) | [
"Repeat",
"elements",
"of",
"an",
"array",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L668-L678 | [
"def",
"repeat",
"(",
"self",
",",
"repeats",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_repeat",
"(",
"args",
",",
"kwargs",
")",
"values",
"=",
"self",
".",
"_data",
".",
"repeat",
"(",
"repeats",
")",
"return",
"type",
"(",
"self",
")",
"(",
"values",
".",
"view",
"(",
"'i8'",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin.value_counts | Return a Series containing counts of unique values.
Parameters
----------
dropna : boolean, default True
Don't include counts of NaT values.
Returns
-------
Series | pandas/core/arrays/datetimelike.py | def value_counts(self, dropna=False):
"""
Return a Series containing counts of unique values.
Parameters
----------
dropna : boolean, default True
Don't include counts of NaT values.
Returns
-------
Series
"""
from pandas import Series, Index
if dropna:
values = self[~self.isna()]._data
else:
values = self._data
cls = type(self)
result = value_counts(values, sort=False, dropna=dropna)
index = Index(cls(result.index.view('i8'), dtype=self.dtype),
name=result.index.name)
return Series(result.values, index=index, name=result.name) | def value_counts(self, dropna=False):
"""
Return a Series containing counts of unique values.
Parameters
----------
dropna : boolean, default True
Don't include counts of NaT values.
Returns
-------
Series
"""
from pandas import Series, Index
if dropna:
values = self[~self.isna()]._data
else:
values = self._data
cls = type(self)
result = value_counts(values, sort=False, dropna=dropna)
index = Index(cls(result.index.view('i8'), dtype=self.dtype),
name=result.index.name)
return Series(result.values, index=index, name=result.name) | [
"Return",
"a",
"Series",
"containing",
"counts",
"of",
"unique",
"values",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L680-L705 | [
"def",
"value_counts",
"(",
"self",
",",
"dropna",
"=",
"False",
")",
":",
"from",
"pandas",
"import",
"Series",
",",
"Index",
"if",
"dropna",
":",
"values",
"=",
"self",
"[",
"~",
"self",
".",
"isna",
"(",
")",
"]",
".",
"_data",
"else",
":",
"values",
"=",
"self",
".",
"_data",
"cls",
"=",
"type",
"(",
"self",
")",
"result",
"=",
"value_counts",
"(",
"values",
",",
"sort",
"=",
"False",
",",
"dropna",
"=",
"dropna",
")",
"index",
"=",
"Index",
"(",
"cls",
"(",
"result",
".",
"index",
".",
"view",
"(",
"'i8'",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
",",
"name",
"=",
"result",
".",
"index",
".",
"name",
")",
"return",
"Series",
"(",
"result",
".",
"values",
",",
"index",
"=",
"index",
",",
"name",
"=",
"result",
".",
"name",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._maybe_mask_results | Parameters
----------
result : a ndarray
fill_value : object, default iNaT
convert : string/dtype or None
Returns
-------
result : ndarray with values replace by the fill_value
mask the result if needed, convert to the provided dtype if its not
None
This is an internal routine. | pandas/core/arrays/datetimelike.py | def _maybe_mask_results(self, result, fill_value=iNaT, convert=None):
"""
Parameters
----------
result : a ndarray
fill_value : object, default iNaT
convert : string/dtype or None
Returns
-------
result : ndarray with values replace by the fill_value
mask the result if needed, convert to the provided dtype if its not
None
This is an internal routine.
"""
if self._hasnans:
if convert:
result = result.astype(convert)
if fill_value is None:
fill_value = np.nan
result[self._isnan] = fill_value
return result | def _maybe_mask_results(self, result, fill_value=iNaT, convert=None):
"""
Parameters
----------
result : a ndarray
fill_value : object, default iNaT
convert : string/dtype or None
Returns
-------
result : ndarray with values replace by the fill_value
mask the result if needed, convert to the provided dtype if its not
None
This is an internal routine.
"""
if self._hasnans:
if convert:
result = result.astype(convert)
if fill_value is None:
fill_value = np.nan
result[self._isnan] = fill_value
return result | [
"Parameters",
"----------",
"result",
":",
"a",
"ndarray",
"fill_value",
":",
"object",
"default",
"iNaT",
"convert",
":",
"string",
"/",
"dtype",
"or",
"None"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L737-L761 | [
"def",
"_maybe_mask_results",
"(",
"self",
",",
"result",
",",
"fill_value",
"=",
"iNaT",
",",
"convert",
"=",
"None",
")",
":",
"if",
"self",
".",
"_hasnans",
":",
"if",
"convert",
":",
"result",
"=",
"result",
".",
"astype",
"(",
"convert",
")",
"if",
"fill_value",
"is",
"None",
":",
"fill_value",
"=",
"np",
".",
"nan",
"result",
"[",
"self",
".",
"_isnan",
"]",
"=",
"fill_value",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._validate_frequency | Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
Parameters
----------
index : DatetimeIndex or TimedeltaIndex
The index on which to determine if the given frequency is valid
freq : DateOffset
The frequency to validate | pandas/core/arrays/datetimelike.py | def _validate_frequency(cls, index, freq, **kwargs):
"""
Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
Parameters
----------
index : DatetimeIndex or TimedeltaIndex
The index on which to determine if the given frequency is valid
freq : DateOffset
The frequency to validate
"""
if is_period_dtype(cls):
# Frequency validation is not meaningful for Period Array/Index
return None
inferred = index.inferred_freq
if index.size == 0 or inferred == freq.freqstr:
return None
try:
on_freq = cls._generate_range(start=index[0], end=None,
periods=len(index), freq=freq,
**kwargs)
if not np.array_equal(index.asi8, on_freq.asi8):
raise ValueError
except ValueError as e:
if "non-fixed" in str(e):
# non-fixed frequencies are not meaningful for timedelta64;
# we retain that error message
raise e
# GH#11587 the main way this is reached is if the `np.array_equal`
# check above is False. This can also be reached if index[0]
# is `NaT`, in which case the call to `cls._generate_range` will
# raise a ValueError, which we re-raise with a more targeted
# message.
raise ValueError('Inferred frequency {infer} from passed values '
'does not conform to passed frequency {passed}'
.format(infer=inferred, passed=freq.freqstr)) | def _validate_frequency(cls, index, freq, **kwargs):
"""
Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
Parameters
----------
index : DatetimeIndex or TimedeltaIndex
The index on which to determine if the given frequency is valid
freq : DateOffset
The frequency to validate
"""
if is_period_dtype(cls):
# Frequency validation is not meaningful for Period Array/Index
return None
inferred = index.inferred_freq
if index.size == 0 or inferred == freq.freqstr:
return None
try:
on_freq = cls._generate_range(start=index[0], end=None,
periods=len(index), freq=freq,
**kwargs)
if not np.array_equal(index.asi8, on_freq.asi8):
raise ValueError
except ValueError as e:
if "non-fixed" in str(e):
# non-fixed frequencies are not meaningful for timedelta64;
# we retain that error message
raise e
# GH#11587 the main way this is reached is if the `np.array_equal`
# check above is False. This can also be reached if index[0]
# is `NaT`, in which case the call to `cls._generate_range` will
# raise a ValueError, which we re-raise with a more targeted
# message.
raise ValueError('Inferred frequency {infer} from passed values '
'does not conform to passed frequency {passed}'
.format(infer=inferred, passed=freq.freqstr)) | [
"Validate",
"that",
"a",
"frequency",
"is",
"compatible",
"with",
"the",
"values",
"of",
"a",
"given",
"Datetime",
"Array",
"/",
"Index",
"or",
"Timedelta",
"Array",
"/",
"Index"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L860-L898 | [
"def",
"_validate_frequency",
"(",
"cls",
",",
"index",
",",
"freq",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"is_period_dtype",
"(",
"cls",
")",
":",
"# Frequency validation is not meaningful for Period Array/Index",
"return",
"None",
"inferred",
"=",
"index",
".",
"inferred_freq",
"if",
"index",
".",
"size",
"==",
"0",
"or",
"inferred",
"==",
"freq",
".",
"freqstr",
":",
"return",
"None",
"try",
":",
"on_freq",
"=",
"cls",
".",
"_generate_range",
"(",
"start",
"=",
"index",
"[",
"0",
"]",
",",
"end",
"=",
"None",
",",
"periods",
"=",
"len",
"(",
"index",
")",
",",
"freq",
"=",
"freq",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"np",
".",
"array_equal",
"(",
"index",
".",
"asi8",
",",
"on_freq",
".",
"asi8",
")",
":",
"raise",
"ValueError",
"except",
"ValueError",
"as",
"e",
":",
"if",
"\"non-fixed\"",
"in",
"str",
"(",
"e",
")",
":",
"# non-fixed frequencies are not meaningful for timedelta64;",
"# we retain that error message",
"raise",
"e",
"# GH#11587 the main way this is reached is if the `np.array_equal`",
"# check above is False. This can also be reached if index[0]",
"# is `NaT`, in which case the call to `cls._generate_range` will",
"# raise a ValueError, which we re-raise with a more targeted",
"# message.",
"raise",
"ValueError",
"(",
"'Inferred frequency {infer} from passed values '",
"'does not conform to passed frequency {passed}'",
".",
"format",
"(",
"infer",
"=",
"inferred",
",",
"passed",
"=",
"freq",
".",
"freqstr",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._add_delta | Add a timedelta-like, Tick or TimedeltaIndex-like object
to self, yielding an int64 numpy array
Parameters
----------
delta : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : ndarray[int64]
Notes
-----
The result's name is set outside of _add_delta by the calling
method (__add__ or __sub__), if necessary (i.e. for Indexes). | pandas/core/arrays/datetimelike.py | def _add_delta(self, other):
"""
Add a timedelta-like, Tick or TimedeltaIndex-like object
to self, yielding an int64 numpy array
Parameters
----------
delta : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : ndarray[int64]
Notes
-----
The result's name is set outside of _add_delta by the calling
method (__add__ or __sub__), if necessary (i.e. for Indexes).
"""
if isinstance(other, (Tick, timedelta, np.timedelta64)):
new_values = self._add_timedeltalike_scalar(other)
elif is_timedelta64_dtype(other):
# ndarray[timedelta64] or TimedeltaArray/index
new_values = self._add_delta_tdi(other)
return new_values | def _add_delta(self, other):
"""
Add a timedelta-like, Tick or TimedeltaIndex-like object
to self, yielding an int64 numpy array
Parameters
----------
delta : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : ndarray[int64]
Notes
-----
The result's name is set outside of _add_delta by the calling
method (__add__ or __sub__), if necessary (i.e. for Indexes).
"""
if isinstance(other, (Tick, timedelta, np.timedelta64)):
new_values = self._add_timedeltalike_scalar(other)
elif is_timedelta64_dtype(other):
# ndarray[timedelta64] or TimedeltaArray/index
new_values = self._add_delta_tdi(other)
return new_values | [
"Add",
"a",
"timedelta",
"-",
"like",
"Tick",
"or",
"TimedeltaIndex",
"-",
"like",
"object",
"to",
"self",
"yielding",
"an",
"int64",
"numpy",
"array"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L942-L967 | [
"def",
"_add_delta",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"(",
"Tick",
",",
"timedelta",
",",
"np",
".",
"timedelta64",
")",
")",
":",
"new_values",
"=",
"self",
".",
"_add_timedeltalike_scalar",
"(",
"other",
")",
"elif",
"is_timedelta64_dtype",
"(",
"other",
")",
":",
"# ndarray[timedelta64] or TimedeltaArray/index",
"new_values",
"=",
"self",
".",
"_add_delta_tdi",
"(",
"other",
")",
"return",
"new_values"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._add_timedeltalike_scalar | Add a delta of a timedeltalike
return the i8 result view | pandas/core/arrays/datetimelike.py | def _add_timedeltalike_scalar(self, other):
"""
Add a delta of a timedeltalike
return the i8 result view
"""
if isna(other):
# i.e np.timedelta64("NaT"), not recognized by delta_to_nanoseconds
new_values = np.empty(len(self), dtype='i8')
new_values[:] = iNaT
return new_values
inc = delta_to_nanoseconds(other)
new_values = checked_add_with_arr(self.asi8, inc,
arr_mask=self._isnan).view('i8')
new_values = self._maybe_mask_results(new_values)
return new_values.view('i8') | def _add_timedeltalike_scalar(self, other):
"""
Add a delta of a timedeltalike
return the i8 result view
"""
if isna(other):
# i.e np.timedelta64("NaT"), not recognized by delta_to_nanoseconds
new_values = np.empty(len(self), dtype='i8')
new_values[:] = iNaT
return new_values
inc = delta_to_nanoseconds(other)
new_values = checked_add_with_arr(self.asi8, inc,
arr_mask=self._isnan).view('i8')
new_values = self._maybe_mask_results(new_values)
return new_values.view('i8') | [
"Add",
"a",
"delta",
"of",
"a",
"timedeltalike",
"return",
"the",
"i8",
"result",
"view"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L969-L984 | [
"def",
"_add_timedeltalike_scalar",
"(",
"self",
",",
"other",
")",
":",
"if",
"isna",
"(",
"other",
")",
":",
"# i.e np.timedelta64(\"NaT\"), not recognized by delta_to_nanoseconds",
"new_values",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"self",
")",
",",
"dtype",
"=",
"'i8'",
")",
"new_values",
"[",
":",
"]",
"=",
"iNaT",
"return",
"new_values",
"inc",
"=",
"delta_to_nanoseconds",
"(",
"other",
")",
"new_values",
"=",
"checked_add_with_arr",
"(",
"self",
".",
"asi8",
",",
"inc",
",",
"arr_mask",
"=",
"self",
".",
"_isnan",
")",
".",
"view",
"(",
"'i8'",
")",
"new_values",
"=",
"self",
".",
"_maybe_mask_results",
"(",
"new_values",
")",
"return",
"new_values",
".",
"view",
"(",
"'i8'",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._add_delta_tdi | Add a delta of a TimedeltaIndex
return the i8 result view | pandas/core/arrays/datetimelike.py | def _add_delta_tdi(self, other):
"""
Add a delta of a TimedeltaIndex
return the i8 result view
"""
if len(self) != len(other):
raise ValueError("cannot add indices of unequal length")
if isinstance(other, np.ndarray):
# ndarray[timedelta64]; wrap in TimedeltaIndex for op
from pandas import TimedeltaIndex
other = TimedeltaIndex(other)
self_i8 = self.asi8
other_i8 = other.asi8
new_values = checked_add_with_arr(self_i8, other_i8,
arr_mask=self._isnan,
b_mask=other._isnan)
if self._hasnans or other._hasnans:
mask = (self._isnan) | (other._isnan)
new_values[mask] = iNaT
return new_values.view('i8') | def _add_delta_tdi(self, other):
"""
Add a delta of a TimedeltaIndex
return the i8 result view
"""
if len(self) != len(other):
raise ValueError("cannot add indices of unequal length")
if isinstance(other, np.ndarray):
# ndarray[timedelta64]; wrap in TimedeltaIndex for op
from pandas import TimedeltaIndex
other = TimedeltaIndex(other)
self_i8 = self.asi8
other_i8 = other.asi8
new_values = checked_add_with_arr(self_i8, other_i8,
arr_mask=self._isnan,
b_mask=other._isnan)
if self._hasnans or other._hasnans:
mask = (self._isnan) | (other._isnan)
new_values[mask] = iNaT
return new_values.view('i8') | [
"Add",
"a",
"delta",
"of",
"a",
"TimedeltaIndex",
"return",
"the",
"i8",
"result",
"view"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L986-L1007 | [
"def",
"_add_delta_tdi",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"self",
")",
"!=",
"len",
"(",
"other",
")",
":",
"raise",
"ValueError",
"(",
"\"cannot add indices of unequal length\"",
")",
"if",
"isinstance",
"(",
"other",
",",
"np",
".",
"ndarray",
")",
":",
"# ndarray[timedelta64]; wrap in TimedeltaIndex for op",
"from",
"pandas",
"import",
"TimedeltaIndex",
"other",
"=",
"TimedeltaIndex",
"(",
"other",
")",
"self_i8",
"=",
"self",
".",
"asi8",
"other_i8",
"=",
"other",
".",
"asi8",
"new_values",
"=",
"checked_add_with_arr",
"(",
"self_i8",
",",
"other_i8",
",",
"arr_mask",
"=",
"self",
".",
"_isnan",
",",
"b_mask",
"=",
"other",
".",
"_isnan",
")",
"if",
"self",
".",
"_hasnans",
"or",
"other",
".",
"_hasnans",
":",
"mask",
"=",
"(",
"self",
".",
"_isnan",
")",
"|",
"(",
"other",
".",
"_isnan",
")",
"new_values",
"[",
"mask",
"]",
"=",
"iNaT",
"return",
"new_values",
".",
"view",
"(",
"'i8'",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._add_nat | Add pd.NaT to self | pandas/core/arrays/datetimelike.py | def _add_nat(self):
"""
Add pd.NaT to self
"""
if is_period_dtype(self):
raise TypeError('Cannot add {cls} and {typ}'
.format(cls=type(self).__name__,
typ=type(NaT).__name__))
# GH#19124 pd.NaT is treated like a timedelta for both timedelta
# and datetime dtypes
result = np.zeros(len(self), dtype=np.int64)
result.fill(iNaT)
return type(self)(result, dtype=self.dtype, freq=None) | def _add_nat(self):
"""
Add pd.NaT to self
"""
if is_period_dtype(self):
raise TypeError('Cannot add {cls} and {typ}'
.format(cls=type(self).__name__,
typ=type(NaT).__name__))
# GH#19124 pd.NaT is treated like a timedelta for both timedelta
# and datetime dtypes
result = np.zeros(len(self), dtype=np.int64)
result.fill(iNaT)
return type(self)(result, dtype=self.dtype, freq=None) | [
"Add",
"pd",
".",
"NaT",
"to",
"self"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1009-L1022 | [
"def",
"_add_nat",
"(",
"self",
")",
":",
"if",
"is_period_dtype",
"(",
"self",
")",
":",
"raise",
"TypeError",
"(",
"'Cannot add {cls} and {typ}'",
".",
"format",
"(",
"cls",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"typ",
"=",
"type",
"(",
"NaT",
")",
".",
"__name__",
")",
")",
"# GH#19124 pd.NaT is treated like a timedelta for both timedelta",
"# and datetime dtypes",
"result",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"self",
")",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"result",
".",
"fill",
"(",
"iNaT",
")",
"return",
"type",
"(",
"self",
")",
"(",
"result",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"freq",
"=",
"None",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._sub_nat | Subtract pd.NaT from self | pandas/core/arrays/datetimelike.py | def _sub_nat(self):
"""
Subtract pd.NaT from self
"""
# GH#19124 Timedelta - datetime is not in general well-defined.
# We make an exception for pd.NaT, which in this case quacks
# like a timedelta.
# For datetime64 dtypes by convention we treat NaT as a datetime, so
# this subtraction returns a timedelta64 dtype.
# For period dtype, timedelta64 is a close-enough return dtype.
result = np.zeros(len(self), dtype=np.int64)
result.fill(iNaT)
return result.view('timedelta64[ns]') | def _sub_nat(self):
"""
Subtract pd.NaT from self
"""
# GH#19124 Timedelta - datetime is not in general well-defined.
# We make an exception for pd.NaT, which in this case quacks
# like a timedelta.
# For datetime64 dtypes by convention we treat NaT as a datetime, so
# this subtraction returns a timedelta64 dtype.
# For period dtype, timedelta64 is a close-enough return dtype.
result = np.zeros(len(self), dtype=np.int64)
result.fill(iNaT)
return result.view('timedelta64[ns]') | [
"Subtract",
"pd",
".",
"NaT",
"from",
"self"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1024-L1036 | [
"def",
"_sub_nat",
"(",
"self",
")",
":",
"# GH#19124 Timedelta - datetime is not in general well-defined.",
"# We make an exception for pd.NaT, which in this case quacks",
"# like a timedelta.",
"# For datetime64 dtypes by convention we treat NaT as a datetime, so",
"# this subtraction returns a timedelta64 dtype.",
"# For period dtype, timedelta64 is a close-enough return dtype.",
"result",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"self",
")",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"result",
".",
"fill",
"(",
"iNaT",
")",
"return",
"result",
".",
"view",
"(",
"'timedelta64[ns]'",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._sub_period_array | Subtract a Period Array/Index from self. This is only valid if self
is itself a Period Array/Index, raises otherwise. Both objects must
have the same frequency.
Parameters
----------
other : PeriodIndex or PeriodArray
Returns
-------
result : np.ndarray[object]
Array of DateOffset objects; nulls represented by NaT. | pandas/core/arrays/datetimelike.py | def _sub_period_array(self, other):
"""
Subtract a Period Array/Index from self. This is only valid if self
is itself a Period Array/Index, raises otherwise. Both objects must
have the same frequency.
Parameters
----------
other : PeriodIndex or PeriodArray
Returns
-------
result : np.ndarray[object]
Array of DateOffset objects; nulls represented by NaT.
"""
if not is_period_dtype(self):
raise TypeError("cannot subtract {dtype}-dtype from {cls}"
.format(dtype=other.dtype,
cls=type(self).__name__))
if len(self) != len(other):
raise ValueError("cannot subtract arrays/indices of "
"unequal length")
if self.freq != other.freq:
msg = DIFFERENT_FREQ.format(cls=type(self).__name__,
own_freq=self.freqstr,
other_freq=other.freqstr)
raise IncompatibleFrequency(msg)
new_values = checked_add_with_arr(self.asi8, -other.asi8,
arr_mask=self._isnan,
b_mask=other._isnan)
new_values = np.array([self.freq.base * x for x in new_values])
if self._hasnans or other._hasnans:
mask = (self._isnan) | (other._isnan)
new_values[mask] = NaT
return new_values | def _sub_period_array(self, other):
"""
Subtract a Period Array/Index from self. This is only valid if self
is itself a Period Array/Index, raises otherwise. Both objects must
have the same frequency.
Parameters
----------
other : PeriodIndex or PeriodArray
Returns
-------
result : np.ndarray[object]
Array of DateOffset objects; nulls represented by NaT.
"""
if not is_period_dtype(self):
raise TypeError("cannot subtract {dtype}-dtype from {cls}"
.format(dtype=other.dtype,
cls=type(self).__name__))
if len(self) != len(other):
raise ValueError("cannot subtract arrays/indices of "
"unequal length")
if self.freq != other.freq:
msg = DIFFERENT_FREQ.format(cls=type(self).__name__,
own_freq=self.freqstr,
other_freq=other.freqstr)
raise IncompatibleFrequency(msg)
new_values = checked_add_with_arr(self.asi8, -other.asi8,
arr_mask=self._isnan,
b_mask=other._isnan)
new_values = np.array([self.freq.base * x for x in new_values])
if self._hasnans or other._hasnans:
mask = (self._isnan) | (other._isnan)
new_values[mask] = NaT
return new_values | [
"Subtract",
"a",
"Period",
"Array",
"/",
"Index",
"from",
"self",
".",
"This",
"is",
"only",
"valid",
"if",
"self",
"is",
"itself",
"a",
"Period",
"Array",
"/",
"Index",
"raises",
"otherwise",
".",
"Both",
"objects",
"must",
"have",
"the",
"same",
"frequency",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1038-L1075 | [
"def",
"_sub_period_array",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"is_period_dtype",
"(",
"self",
")",
":",
"raise",
"TypeError",
"(",
"\"cannot subtract {dtype}-dtype from {cls}\"",
".",
"format",
"(",
"dtype",
"=",
"other",
".",
"dtype",
",",
"cls",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
")",
")",
"if",
"len",
"(",
"self",
")",
"!=",
"len",
"(",
"other",
")",
":",
"raise",
"ValueError",
"(",
"\"cannot subtract arrays/indices of \"",
"\"unequal length\"",
")",
"if",
"self",
".",
"freq",
"!=",
"other",
".",
"freq",
":",
"msg",
"=",
"DIFFERENT_FREQ",
".",
"format",
"(",
"cls",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"own_freq",
"=",
"self",
".",
"freqstr",
",",
"other_freq",
"=",
"other",
".",
"freqstr",
")",
"raise",
"IncompatibleFrequency",
"(",
"msg",
")",
"new_values",
"=",
"checked_add_with_arr",
"(",
"self",
".",
"asi8",
",",
"-",
"other",
".",
"asi8",
",",
"arr_mask",
"=",
"self",
".",
"_isnan",
",",
"b_mask",
"=",
"other",
".",
"_isnan",
")",
"new_values",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"freq",
".",
"base",
"*",
"x",
"for",
"x",
"in",
"new_values",
"]",
")",
"if",
"self",
".",
"_hasnans",
"or",
"other",
".",
"_hasnans",
":",
"mask",
"=",
"(",
"self",
".",
"_isnan",
")",
"|",
"(",
"other",
".",
"_isnan",
")",
"new_values",
"[",
"mask",
"]",
"=",
"NaT",
"return",
"new_values"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._addsub_int_array | Add or subtract array-like of integers equivalent to applying
`_time_shift` pointwise.
Parameters
----------
other : Index, ExtensionArray, np.ndarray
integer-dtype
op : {operator.add, operator.sub}
Returns
-------
result : same class as self | pandas/core/arrays/datetimelike.py | def _addsub_int_array(self, other, op):
"""
Add or subtract array-like of integers equivalent to applying
`_time_shift` pointwise.
Parameters
----------
other : Index, ExtensionArray, np.ndarray
integer-dtype
op : {operator.add, operator.sub}
Returns
-------
result : same class as self
"""
# _addsub_int_array is overriden by PeriodArray
assert not is_period_dtype(self)
assert op in [operator.add, operator.sub]
if self.freq is None:
# GH#19123
raise NullFrequencyError("Cannot shift with no freq")
elif isinstance(self.freq, Tick):
# easy case where we can convert to timedelta64 operation
td = Timedelta(self.freq)
return op(self, td * other)
# We should only get here with DatetimeIndex; dispatch
# to _addsub_offset_array
assert not is_timedelta64_dtype(self)
return op(self, np.array(other) * self.freq) | def _addsub_int_array(self, other, op):
"""
Add or subtract array-like of integers equivalent to applying
`_time_shift` pointwise.
Parameters
----------
other : Index, ExtensionArray, np.ndarray
integer-dtype
op : {operator.add, operator.sub}
Returns
-------
result : same class as self
"""
# _addsub_int_array is overriden by PeriodArray
assert not is_period_dtype(self)
assert op in [operator.add, operator.sub]
if self.freq is None:
# GH#19123
raise NullFrequencyError("Cannot shift with no freq")
elif isinstance(self.freq, Tick):
# easy case where we can convert to timedelta64 operation
td = Timedelta(self.freq)
return op(self, td * other)
# We should only get here with DatetimeIndex; dispatch
# to _addsub_offset_array
assert not is_timedelta64_dtype(self)
return op(self, np.array(other) * self.freq) | [
"Add",
"or",
"subtract",
"array",
"-",
"like",
"of",
"integers",
"equivalent",
"to",
"applying",
"_time_shift",
"pointwise",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1077-L1108 | [
"def",
"_addsub_int_array",
"(",
"self",
",",
"other",
",",
"op",
")",
":",
"# _addsub_int_array is overriden by PeriodArray",
"assert",
"not",
"is_period_dtype",
"(",
"self",
")",
"assert",
"op",
"in",
"[",
"operator",
".",
"add",
",",
"operator",
".",
"sub",
"]",
"if",
"self",
".",
"freq",
"is",
"None",
":",
"# GH#19123",
"raise",
"NullFrequencyError",
"(",
"\"Cannot shift with no freq\"",
")",
"elif",
"isinstance",
"(",
"self",
".",
"freq",
",",
"Tick",
")",
":",
"# easy case where we can convert to timedelta64 operation",
"td",
"=",
"Timedelta",
"(",
"self",
".",
"freq",
")",
"return",
"op",
"(",
"self",
",",
"td",
"*",
"other",
")",
"# We should only get here with DatetimeIndex; dispatch",
"# to _addsub_offset_array",
"assert",
"not",
"is_timedelta64_dtype",
"(",
"self",
")",
"return",
"op",
"(",
"self",
",",
"np",
".",
"array",
"(",
"other",
")",
"*",
"self",
".",
"freq",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._addsub_offset_array | Add or subtract array-like of DateOffset objects
Parameters
----------
other : Index, np.ndarray
object-dtype containing pd.DateOffset objects
op : {operator.add, operator.sub}
Returns
-------
result : same class as self | pandas/core/arrays/datetimelike.py | def _addsub_offset_array(self, other, op):
"""
Add or subtract array-like of DateOffset objects
Parameters
----------
other : Index, np.ndarray
object-dtype containing pd.DateOffset objects
op : {operator.add, operator.sub}
Returns
-------
result : same class as self
"""
assert op in [operator.add, operator.sub]
if len(other) == 1:
return op(self, other[0])
warnings.warn("Adding/subtracting array of DateOffsets to "
"{cls} not vectorized"
.format(cls=type(self).__name__), PerformanceWarning)
# For EA self.astype('O') returns a numpy array, not an Index
left = lib.values_from_object(self.astype('O'))
res_values = op(left, np.array(other))
kwargs = {}
if not is_period_dtype(self):
kwargs['freq'] = 'infer'
return self._from_sequence(res_values, **kwargs) | def _addsub_offset_array(self, other, op):
"""
Add or subtract array-like of DateOffset objects
Parameters
----------
other : Index, np.ndarray
object-dtype containing pd.DateOffset objects
op : {operator.add, operator.sub}
Returns
-------
result : same class as self
"""
assert op in [operator.add, operator.sub]
if len(other) == 1:
return op(self, other[0])
warnings.warn("Adding/subtracting array of DateOffsets to "
"{cls} not vectorized"
.format(cls=type(self).__name__), PerformanceWarning)
# For EA self.astype('O') returns a numpy array, not an Index
left = lib.values_from_object(self.astype('O'))
res_values = op(left, np.array(other))
kwargs = {}
if not is_period_dtype(self):
kwargs['freq'] = 'infer'
return self._from_sequence(res_values, **kwargs) | [
"Add",
"or",
"subtract",
"array",
"-",
"like",
"of",
"DateOffset",
"objects"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1110-L1139 | [
"def",
"_addsub_offset_array",
"(",
"self",
",",
"other",
",",
"op",
")",
":",
"assert",
"op",
"in",
"[",
"operator",
".",
"add",
",",
"operator",
".",
"sub",
"]",
"if",
"len",
"(",
"other",
")",
"==",
"1",
":",
"return",
"op",
"(",
"self",
",",
"other",
"[",
"0",
"]",
")",
"warnings",
".",
"warn",
"(",
"\"Adding/subtracting array of DateOffsets to \"",
"\"{cls} not vectorized\"",
".",
"format",
"(",
"cls",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
")",
",",
"PerformanceWarning",
")",
"# For EA self.astype('O') returns a numpy array, not an Index",
"left",
"=",
"lib",
".",
"values_from_object",
"(",
"self",
".",
"astype",
"(",
"'O'",
")",
")",
"res_values",
"=",
"op",
"(",
"left",
",",
"np",
".",
"array",
"(",
"other",
")",
")",
"kwargs",
"=",
"{",
"}",
"if",
"not",
"is_period_dtype",
"(",
"self",
")",
":",
"kwargs",
"[",
"'freq'",
"]",
"=",
"'infer'",
"return",
"self",
".",
"_from_sequence",
"(",
"res_values",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._time_shift | Shift each value by `periods`.
Note this is different from ExtensionArray.shift, which
shifts the *position* of each element, padding the end with
missing values.
Parameters
----------
periods : int
Number of periods to shift by.
freq : pandas.DateOffset, pandas.Timedelta, or string
Frequency increment to shift by. | pandas/core/arrays/datetimelike.py | def _time_shift(self, periods, freq=None):
"""
Shift each value by `periods`.
Note this is different from ExtensionArray.shift, which
shifts the *position* of each element, padding the end with
missing values.
Parameters
----------
periods : int
Number of periods to shift by.
freq : pandas.DateOffset, pandas.Timedelta, or string
Frequency increment to shift by.
"""
if freq is not None and freq != self.freq:
if isinstance(freq, str):
freq = frequencies.to_offset(freq)
offset = periods * freq
result = self + offset
return result
if periods == 0:
# immutable so OK
return self.copy()
if self.freq is None:
raise NullFrequencyError("Cannot shift with no freq")
start = self[0] + periods * self.freq
end = self[-1] + periods * self.freq
# Note: in the DatetimeTZ case, _generate_range will infer the
# appropriate timezone from `start` and `end`, so tz does not need
# to be passed explicitly.
return self._generate_range(start=start, end=end, periods=None,
freq=self.freq) | def _time_shift(self, periods, freq=None):
"""
Shift each value by `periods`.
Note this is different from ExtensionArray.shift, which
shifts the *position* of each element, padding the end with
missing values.
Parameters
----------
periods : int
Number of periods to shift by.
freq : pandas.DateOffset, pandas.Timedelta, or string
Frequency increment to shift by.
"""
if freq is not None and freq != self.freq:
if isinstance(freq, str):
freq = frequencies.to_offset(freq)
offset = periods * freq
result = self + offset
return result
if periods == 0:
# immutable so OK
return self.copy()
if self.freq is None:
raise NullFrequencyError("Cannot shift with no freq")
start = self[0] + periods * self.freq
end = self[-1] + periods * self.freq
# Note: in the DatetimeTZ case, _generate_range will infer the
# appropriate timezone from `start` and `end`, so tz does not need
# to be passed explicitly.
return self._generate_range(start=start, end=end, periods=None,
freq=self.freq) | [
"Shift",
"each",
"value",
"by",
"periods",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1141-L1177 | [
"def",
"_time_shift",
"(",
"self",
",",
"periods",
",",
"freq",
"=",
"None",
")",
":",
"if",
"freq",
"is",
"not",
"None",
"and",
"freq",
"!=",
"self",
".",
"freq",
":",
"if",
"isinstance",
"(",
"freq",
",",
"str",
")",
":",
"freq",
"=",
"frequencies",
".",
"to_offset",
"(",
"freq",
")",
"offset",
"=",
"periods",
"*",
"freq",
"result",
"=",
"self",
"+",
"offset",
"return",
"result",
"if",
"periods",
"==",
"0",
":",
"# immutable so OK",
"return",
"self",
".",
"copy",
"(",
")",
"if",
"self",
".",
"freq",
"is",
"None",
":",
"raise",
"NullFrequencyError",
"(",
"\"Cannot shift with no freq\"",
")",
"start",
"=",
"self",
"[",
"0",
"]",
"+",
"periods",
"*",
"self",
".",
"freq",
"end",
"=",
"self",
"[",
"-",
"1",
"]",
"+",
"periods",
"*",
"self",
".",
"freq",
"# Note: in the DatetimeTZ case, _generate_range will infer the",
"# appropriate timezone from `start` and `end`, so tz does not need",
"# to be passed explicitly.",
"return",
"self",
".",
"_generate_range",
"(",
"start",
"=",
"start",
",",
"end",
"=",
"end",
",",
"periods",
"=",
"None",
",",
"freq",
"=",
"self",
".",
"freq",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin._ensure_localized | Ensure that we are re-localized.
This is for compat as we can then call this on all datetimelike
arrays generally (ignored for Period/Timedelta)
Parameters
----------
arg : Union[DatetimeLikeArray, DatetimeIndexOpsMixin, ndarray]
ambiguous : str, bool, or bool-ndarray, default 'raise'
nonexistent : str, default 'raise'
from_utc : bool, default False
If True, localize the i8 ndarray to UTC first before converting to
the appropriate tz. If False, localize directly to the tz.
Returns
-------
localized array | pandas/core/arrays/datetimelike.py | def _ensure_localized(self, arg, ambiguous='raise', nonexistent='raise',
from_utc=False):
"""
Ensure that we are re-localized.
This is for compat as we can then call this on all datetimelike
arrays generally (ignored for Period/Timedelta)
Parameters
----------
arg : Union[DatetimeLikeArray, DatetimeIndexOpsMixin, ndarray]
ambiguous : str, bool, or bool-ndarray, default 'raise'
nonexistent : str, default 'raise'
from_utc : bool, default False
If True, localize the i8 ndarray to UTC first before converting to
the appropriate tz. If False, localize directly to the tz.
Returns
-------
localized array
"""
# reconvert to local tz
tz = getattr(self, 'tz', None)
if tz is not None:
if not isinstance(arg, type(self)):
arg = self._simple_new(arg)
if from_utc:
arg = arg.tz_localize('UTC').tz_convert(self.tz)
else:
arg = arg.tz_localize(
self.tz, ambiguous=ambiguous, nonexistent=nonexistent
)
return arg | def _ensure_localized(self, arg, ambiguous='raise', nonexistent='raise',
from_utc=False):
"""
Ensure that we are re-localized.
This is for compat as we can then call this on all datetimelike
arrays generally (ignored for Period/Timedelta)
Parameters
----------
arg : Union[DatetimeLikeArray, DatetimeIndexOpsMixin, ndarray]
ambiguous : str, bool, or bool-ndarray, default 'raise'
nonexistent : str, default 'raise'
from_utc : bool, default False
If True, localize the i8 ndarray to UTC first before converting to
the appropriate tz. If False, localize directly to the tz.
Returns
-------
localized array
"""
# reconvert to local tz
tz = getattr(self, 'tz', None)
if tz is not None:
if not isinstance(arg, type(self)):
arg = self._simple_new(arg)
if from_utc:
arg = arg.tz_localize('UTC').tz_convert(self.tz)
else:
arg = arg.tz_localize(
self.tz, ambiguous=ambiguous, nonexistent=nonexistent
)
return arg | [
"Ensure",
"that",
"we",
"are",
"re",
"-",
"localized",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1340-L1373 | [
"def",
"_ensure_localized",
"(",
"self",
",",
"arg",
",",
"ambiguous",
"=",
"'raise'",
",",
"nonexistent",
"=",
"'raise'",
",",
"from_utc",
"=",
"False",
")",
":",
"# reconvert to local tz",
"tz",
"=",
"getattr",
"(",
"self",
",",
"'tz'",
",",
"None",
")",
"if",
"tz",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"type",
"(",
"self",
")",
")",
":",
"arg",
"=",
"self",
".",
"_simple_new",
"(",
"arg",
")",
"if",
"from_utc",
":",
"arg",
"=",
"arg",
".",
"tz_localize",
"(",
"'UTC'",
")",
".",
"tz_convert",
"(",
"self",
".",
"tz",
")",
"else",
":",
"arg",
"=",
"arg",
".",
"tz_localize",
"(",
"self",
".",
"tz",
",",
"ambiguous",
"=",
"ambiguous",
",",
"nonexistent",
"=",
"nonexistent",
")",
"return",
"arg"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin.min | Return the minimum value of the Array or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Index.min : Return the minimum value in an Index.
Series.min : Return the minimum value in a Series. | pandas/core/arrays/datetimelike.py | def min(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the minimum value of the Array or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Index.min : Return the minimum value in an Index.
Series.min : Return the minimum value in a Series.
"""
nv.validate_min(args, kwargs)
nv.validate_minmax_axis(axis)
result = nanops.nanmin(self.asi8, skipna=skipna, mask=self.isna())
if isna(result):
# Period._from_ordinal does not handle np.nan gracefully
return NaT
return self._box_func(result) | def min(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the minimum value of the Array or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Index.min : Return the minimum value in an Index.
Series.min : Return the minimum value in a Series.
"""
nv.validate_min(args, kwargs)
nv.validate_minmax_axis(axis)
result = nanops.nanmin(self.asi8, skipna=skipna, mask=self.isna())
if isna(result):
# Period._from_ordinal does not handle np.nan gracefully
return NaT
return self._box_func(result) | [
"Return",
"the",
"minimum",
"value",
"of",
"the",
"Array",
"or",
"minimum",
"along",
"an",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1385-L1403 | [
"def",
"min",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_min",
"(",
"args",
",",
"kwargs",
")",
"nv",
".",
"validate_minmax_axis",
"(",
"axis",
")",
"result",
"=",
"nanops",
".",
"nanmin",
"(",
"self",
".",
"asi8",
",",
"skipna",
"=",
"skipna",
",",
"mask",
"=",
"self",
".",
"isna",
"(",
")",
")",
"if",
"isna",
"(",
"result",
")",
":",
"# Period._from_ordinal does not handle np.nan gracefully",
"return",
"NaT",
"return",
"self",
".",
"_box_func",
"(",
"result",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeLikeArrayMixin.max | Return the maximum value of the Array or maximum along
an axis.
See Also
--------
numpy.ndarray.max
Index.max : Return the maximum value in an Index.
Series.max : Return the maximum value in a Series. | pandas/core/arrays/datetimelike.py | def max(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the maximum value of the Array or maximum along
an axis.
See Also
--------
numpy.ndarray.max
Index.max : Return the maximum value in an Index.
Series.max : Return the maximum value in a Series.
"""
# TODO: skipna is broken with max.
# See https://github.com/pandas-dev/pandas/issues/24265
nv.validate_max(args, kwargs)
nv.validate_minmax_axis(axis)
mask = self.isna()
if skipna:
values = self[~mask].asi8
elif mask.any():
return NaT
else:
values = self.asi8
if not len(values):
# short-circut for empty max / min
return NaT
result = nanops.nanmax(values, skipna=skipna)
# Don't have to worry about NA `result`, since no NA went in.
return self._box_func(result) | def max(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the maximum value of the Array or maximum along
an axis.
See Also
--------
numpy.ndarray.max
Index.max : Return the maximum value in an Index.
Series.max : Return the maximum value in a Series.
"""
# TODO: skipna is broken with max.
# See https://github.com/pandas-dev/pandas/issues/24265
nv.validate_max(args, kwargs)
nv.validate_minmax_axis(axis)
mask = self.isna()
if skipna:
values = self[~mask].asi8
elif mask.any():
return NaT
else:
values = self.asi8
if not len(values):
# short-circut for empty max / min
return NaT
result = nanops.nanmax(values, skipna=skipna)
# Don't have to worry about NA `result`, since no NA went in.
return self._box_func(result) | [
"Return",
"the",
"maximum",
"value",
"of",
"the",
"Array",
"or",
"maximum",
"along",
"an",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L1405-L1435 | [
"def",
"max",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: skipna is broken with max.",
"# See https://github.com/pandas-dev/pandas/issues/24265",
"nv",
".",
"validate_max",
"(",
"args",
",",
"kwargs",
")",
"nv",
".",
"validate_minmax_axis",
"(",
"axis",
")",
"mask",
"=",
"self",
".",
"isna",
"(",
")",
"if",
"skipna",
":",
"values",
"=",
"self",
"[",
"~",
"mask",
"]",
".",
"asi8",
"elif",
"mask",
".",
"any",
"(",
")",
":",
"return",
"NaT",
"else",
":",
"values",
"=",
"self",
".",
"asi8",
"if",
"not",
"len",
"(",
"values",
")",
":",
"# short-circut for empty max / min",
"return",
"NaT",
"result",
"=",
"nanops",
".",
"nanmax",
"(",
"values",
",",
"skipna",
"=",
"skipna",
")",
"# Don't have to worry about NA `result`, since no NA went in.",
"return",
"self",
".",
"_box_func",
"(",
"result",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _period_array_cmp | Wrap comparison operations to convert Period-like to PeriodDtype | pandas/core/arrays/period.py | def _period_array_cmp(cls, op):
"""
Wrap comparison operations to convert Period-like to PeriodDtype
"""
opname = '__{name}__'.format(name=op.__name__)
nat_result = opname == '__ne__'
def wrapper(self, other):
op = getattr(self.asi8, opname)
if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)):
return NotImplemented
if is_list_like(other) and len(other) != len(self):
raise ValueError("Lengths must match")
if isinstance(other, Period):
self._check_compatible_with(other)
result = op(other.ordinal)
elif isinstance(other, cls):
self._check_compatible_with(other)
result = op(other.asi8)
mask = self._isnan | other._isnan
if mask.any():
result[mask] = nat_result
return result
elif other is NaT:
result = np.empty(len(self.asi8), dtype=bool)
result.fill(nat_result)
else:
other = Period(other, freq=self.freq)
result = op(other.ordinal)
if self._hasnans:
result[self._isnan] = nat_result
return result
return compat.set_function_name(wrapper, opname, cls) | def _period_array_cmp(cls, op):
"""
Wrap comparison operations to convert Period-like to PeriodDtype
"""
opname = '__{name}__'.format(name=op.__name__)
nat_result = opname == '__ne__'
def wrapper(self, other):
op = getattr(self.asi8, opname)
if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)):
return NotImplemented
if is_list_like(other) and len(other) != len(self):
raise ValueError("Lengths must match")
if isinstance(other, Period):
self._check_compatible_with(other)
result = op(other.ordinal)
elif isinstance(other, cls):
self._check_compatible_with(other)
result = op(other.asi8)
mask = self._isnan | other._isnan
if mask.any():
result[mask] = nat_result
return result
elif other is NaT:
result = np.empty(len(self.asi8), dtype=bool)
result.fill(nat_result)
else:
other = Period(other, freq=self.freq)
result = op(other.ordinal)
if self._hasnans:
result[self._isnan] = nat_result
return result
return compat.set_function_name(wrapper, opname, cls) | [
"Wrap",
"comparison",
"operations",
"to",
"convert",
"Period",
"-",
"like",
"to",
"PeriodDtype"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L44-L86 | [
"def",
"_period_array_cmp",
"(",
"cls",
",",
"op",
")",
":",
"opname",
"=",
"'__{name}__'",
".",
"format",
"(",
"name",
"=",
"op",
".",
"__name__",
")",
"nat_result",
"=",
"opname",
"==",
"'__ne__'",
"def",
"wrapper",
"(",
"self",
",",
"other",
")",
":",
"op",
"=",
"getattr",
"(",
"self",
".",
"asi8",
",",
"opname",
")",
"if",
"isinstance",
"(",
"other",
",",
"(",
"ABCDataFrame",
",",
"ABCSeries",
",",
"ABCIndexClass",
")",
")",
":",
"return",
"NotImplemented",
"if",
"is_list_like",
"(",
"other",
")",
"and",
"len",
"(",
"other",
")",
"!=",
"len",
"(",
"self",
")",
":",
"raise",
"ValueError",
"(",
"\"Lengths must match\"",
")",
"if",
"isinstance",
"(",
"other",
",",
"Period",
")",
":",
"self",
".",
"_check_compatible_with",
"(",
"other",
")",
"result",
"=",
"op",
"(",
"other",
".",
"ordinal",
")",
"elif",
"isinstance",
"(",
"other",
",",
"cls",
")",
":",
"self",
".",
"_check_compatible_with",
"(",
"other",
")",
"result",
"=",
"op",
"(",
"other",
".",
"asi8",
")",
"mask",
"=",
"self",
".",
"_isnan",
"|",
"other",
".",
"_isnan",
"if",
"mask",
".",
"any",
"(",
")",
":",
"result",
"[",
"mask",
"]",
"=",
"nat_result",
"return",
"result",
"elif",
"other",
"is",
"NaT",
":",
"result",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"self",
".",
"asi8",
")",
",",
"dtype",
"=",
"bool",
")",
"result",
".",
"fill",
"(",
"nat_result",
")",
"else",
":",
"other",
"=",
"Period",
"(",
"other",
",",
"freq",
"=",
"self",
".",
"freq",
")",
"result",
"=",
"op",
"(",
"other",
".",
"ordinal",
")",
"if",
"self",
".",
"_hasnans",
":",
"result",
"[",
"self",
".",
"_isnan",
"]",
"=",
"nat_result",
"return",
"result",
"return",
"compat",
".",
"set_function_name",
"(",
"wrapper",
",",
"opname",
",",
"cls",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _raise_on_incompatible | Helper function to render a consistent error message when raising
IncompatibleFrequency.
Parameters
----------
left : PeriodArray
right : DateOffset, Period, ndarray, or timedelta-like
Raises
------
IncompatibleFrequency | pandas/core/arrays/period.py | def _raise_on_incompatible(left, right):
"""
Helper function to render a consistent error message when raising
IncompatibleFrequency.
Parameters
----------
left : PeriodArray
right : DateOffset, Period, ndarray, or timedelta-like
Raises
------
IncompatibleFrequency
"""
# GH#24283 error message format depends on whether right is scalar
if isinstance(right, np.ndarray):
other_freq = None
elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)):
other_freq = right.freqstr
else:
other_freq = _delta_to_tick(Timedelta(right)).freqstr
msg = DIFFERENT_FREQ.format(cls=type(left).__name__,
own_freq=left.freqstr,
other_freq=other_freq)
raise IncompatibleFrequency(msg) | def _raise_on_incompatible(left, right):
"""
Helper function to render a consistent error message when raising
IncompatibleFrequency.
Parameters
----------
left : PeriodArray
right : DateOffset, Period, ndarray, or timedelta-like
Raises
------
IncompatibleFrequency
"""
# GH#24283 error message format depends on whether right is scalar
if isinstance(right, np.ndarray):
other_freq = None
elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)):
other_freq = right.freqstr
else:
other_freq = _delta_to_tick(Timedelta(right)).freqstr
msg = DIFFERENT_FREQ.format(cls=type(left).__name__,
own_freq=left.freqstr,
other_freq=other_freq)
raise IncompatibleFrequency(msg) | [
"Helper",
"function",
"to",
"render",
"a",
"consistent",
"error",
"message",
"when",
"raising",
"IncompatibleFrequency",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L681-L706 | [
"def",
"_raise_on_incompatible",
"(",
"left",
",",
"right",
")",
":",
"# GH#24283 error message format depends on whether right is scalar",
"if",
"isinstance",
"(",
"right",
",",
"np",
".",
"ndarray",
")",
":",
"other_freq",
"=",
"None",
"elif",
"isinstance",
"(",
"right",
",",
"(",
"ABCPeriodIndex",
",",
"PeriodArray",
",",
"Period",
",",
"DateOffset",
")",
")",
":",
"other_freq",
"=",
"right",
".",
"freqstr",
"else",
":",
"other_freq",
"=",
"_delta_to_tick",
"(",
"Timedelta",
"(",
"right",
")",
")",
".",
"freqstr",
"msg",
"=",
"DIFFERENT_FREQ",
".",
"format",
"(",
"cls",
"=",
"type",
"(",
"left",
")",
".",
"__name__",
",",
"own_freq",
"=",
"left",
".",
"freqstr",
",",
"other_freq",
"=",
"other_freq",
")",
"raise",
"IncompatibleFrequency",
"(",
"msg",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | period_array | Construct a new PeriodArray from a sequence of Period scalars.
Parameters
----------
data : Sequence of Period objects
A sequence of Period objects. These are required to all have
the same ``freq.`` Missing values can be indicated by ``None``
or ``pandas.NaT``.
freq : str, Tick, or Offset
The frequency of every element of the array. This can be specified
to avoid inferring the `freq` from `data`.
copy : bool, default False
Whether to ensure a copy of the data is made.
Returns
-------
PeriodArray
See Also
--------
PeriodArray
pandas.PeriodIndex
Examples
--------
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A')])
<PeriodArray>
['2017', '2018']
Length: 2, dtype: period[A-DEC]
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A'),
... pd.NaT])
<PeriodArray>
['2017', '2018', 'NaT']
Length: 3, dtype: period[A-DEC]
Integers that look like years are handled
>>> period_array([2000, 2001, 2002], freq='D')
['2000-01-01', '2001-01-01', '2002-01-01']
Length: 3, dtype: period[D]
Datetime-like strings may also be passed
>>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')
<PeriodArray>
['2000Q1', '2000Q2', '2000Q3', '2000Q4']
Length: 4, dtype: period[Q-DEC] | pandas/core/arrays/period.py | def period_array(
data: Sequence[Optional[Period]],
freq: Optional[Tick] = None,
copy: bool = False,
) -> PeriodArray:
"""
Construct a new PeriodArray from a sequence of Period scalars.
Parameters
----------
data : Sequence of Period objects
A sequence of Period objects. These are required to all have
the same ``freq.`` Missing values can be indicated by ``None``
or ``pandas.NaT``.
freq : str, Tick, or Offset
The frequency of every element of the array. This can be specified
to avoid inferring the `freq` from `data`.
copy : bool, default False
Whether to ensure a copy of the data is made.
Returns
-------
PeriodArray
See Also
--------
PeriodArray
pandas.PeriodIndex
Examples
--------
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A')])
<PeriodArray>
['2017', '2018']
Length: 2, dtype: period[A-DEC]
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A'),
... pd.NaT])
<PeriodArray>
['2017', '2018', 'NaT']
Length: 3, dtype: period[A-DEC]
Integers that look like years are handled
>>> period_array([2000, 2001, 2002], freq='D')
['2000-01-01', '2001-01-01', '2002-01-01']
Length: 3, dtype: period[D]
Datetime-like strings may also be passed
>>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')
<PeriodArray>
['2000Q1', '2000Q2', '2000Q3', '2000Q4']
Length: 4, dtype: period[Q-DEC]
"""
if is_datetime64_dtype(data):
return PeriodArray._from_datetime64(data, freq)
if isinstance(data, (ABCPeriodIndex, ABCSeries, PeriodArray)):
return PeriodArray(data, freq)
# other iterable of some kind
if not isinstance(data, (np.ndarray, list, tuple)):
data = list(data)
data = np.asarray(data)
if freq:
dtype = PeriodDtype(freq)
else:
dtype = None
if is_float_dtype(data) and len(data) > 0:
raise TypeError("PeriodIndex does not allow "
"floating point in construction")
data = ensure_object(data)
return PeriodArray._from_sequence(data, dtype=dtype) | def period_array(
data: Sequence[Optional[Period]],
freq: Optional[Tick] = None,
copy: bool = False,
) -> PeriodArray:
"""
Construct a new PeriodArray from a sequence of Period scalars.
Parameters
----------
data : Sequence of Period objects
A sequence of Period objects. These are required to all have
the same ``freq.`` Missing values can be indicated by ``None``
or ``pandas.NaT``.
freq : str, Tick, or Offset
The frequency of every element of the array. This can be specified
to avoid inferring the `freq` from `data`.
copy : bool, default False
Whether to ensure a copy of the data is made.
Returns
-------
PeriodArray
See Also
--------
PeriodArray
pandas.PeriodIndex
Examples
--------
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A')])
<PeriodArray>
['2017', '2018']
Length: 2, dtype: period[A-DEC]
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A'),
... pd.NaT])
<PeriodArray>
['2017', '2018', 'NaT']
Length: 3, dtype: period[A-DEC]
Integers that look like years are handled
>>> period_array([2000, 2001, 2002], freq='D')
['2000-01-01', '2001-01-01', '2002-01-01']
Length: 3, dtype: period[D]
Datetime-like strings may also be passed
>>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')
<PeriodArray>
['2000Q1', '2000Q2', '2000Q3', '2000Q4']
Length: 4, dtype: period[Q-DEC]
"""
if is_datetime64_dtype(data):
return PeriodArray._from_datetime64(data, freq)
if isinstance(data, (ABCPeriodIndex, ABCSeries, PeriodArray)):
return PeriodArray(data, freq)
# other iterable of some kind
if not isinstance(data, (np.ndarray, list, tuple)):
data = list(data)
data = np.asarray(data)
if freq:
dtype = PeriodDtype(freq)
else:
dtype = None
if is_float_dtype(data) and len(data) > 0:
raise TypeError("PeriodIndex does not allow "
"floating point in construction")
data = ensure_object(data)
return PeriodArray._from_sequence(data, dtype=dtype) | [
"Construct",
"a",
"new",
"PeriodArray",
"from",
"a",
"sequence",
"of",
"Period",
"scalars",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L712-L791 | [
"def",
"period_array",
"(",
"data",
":",
"Sequence",
"[",
"Optional",
"[",
"Period",
"]",
"]",
",",
"freq",
":",
"Optional",
"[",
"Tick",
"]",
"=",
"None",
",",
"copy",
":",
"bool",
"=",
"False",
",",
")",
"->",
"PeriodArray",
":",
"if",
"is_datetime64_dtype",
"(",
"data",
")",
":",
"return",
"PeriodArray",
".",
"_from_datetime64",
"(",
"data",
",",
"freq",
")",
"if",
"isinstance",
"(",
"data",
",",
"(",
"ABCPeriodIndex",
",",
"ABCSeries",
",",
"PeriodArray",
")",
")",
":",
"return",
"PeriodArray",
"(",
"data",
",",
"freq",
")",
"# other iterable of some kind",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"np",
".",
"ndarray",
",",
"list",
",",
"tuple",
")",
")",
":",
"data",
"=",
"list",
"(",
"data",
")",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"if",
"freq",
":",
"dtype",
"=",
"PeriodDtype",
"(",
"freq",
")",
"else",
":",
"dtype",
"=",
"None",
"if",
"is_float_dtype",
"(",
"data",
")",
"and",
"len",
"(",
"data",
")",
">",
"0",
":",
"raise",
"TypeError",
"(",
"\"PeriodIndex does not allow \"",
"\"floating point in construction\"",
")",
"data",
"=",
"ensure_object",
"(",
"data",
")",
"return",
"PeriodArray",
".",
"_from_sequence",
"(",
"data",
",",
"dtype",
"=",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | validate_dtype_freq | If both a dtype and a freq are available, ensure they match. If only
dtype is available, extract the implied freq.
Parameters
----------
dtype : dtype
freq : DateOffset or None
Returns
-------
freq : DateOffset
Raises
------
ValueError : non-period dtype
IncompatibleFrequency : mismatch between dtype and freq | pandas/core/arrays/period.py | def validate_dtype_freq(dtype, freq):
"""
If both a dtype and a freq are available, ensure they match. If only
dtype is available, extract the implied freq.
Parameters
----------
dtype : dtype
freq : DateOffset or None
Returns
-------
freq : DateOffset
Raises
------
ValueError : non-period dtype
IncompatibleFrequency : mismatch between dtype and freq
"""
if freq is not None:
freq = frequencies.to_offset(freq)
if dtype is not None:
dtype = pandas_dtype(dtype)
if not is_period_dtype(dtype):
raise ValueError('dtype must be PeriodDtype')
if freq is None:
freq = dtype.freq
elif freq != dtype.freq:
raise IncompatibleFrequency('specified freq and dtype '
'are different')
return freq | def validate_dtype_freq(dtype, freq):
"""
If both a dtype and a freq are available, ensure they match. If only
dtype is available, extract the implied freq.
Parameters
----------
dtype : dtype
freq : DateOffset or None
Returns
-------
freq : DateOffset
Raises
------
ValueError : non-period dtype
IncompatibleFrequency : mismatch between dtype and freq
"""
if freq is not None:
freq = frequencies.to_offset(freq)
if dtype is not None:
dtype = pandas_dtype(dtype)
if not is_period_dtype(dtype):
raise ValueError('dtype must be PeriodDtype')
if freq is None:
freq = dtype.freq
elif freq != dtype.freq:
raise IncompatibleFrequency('specified freq and dtype '
'are different')
return freq | [
"If",
"both",
"a",
"dtype",
"and",
"a",
"freq",
"are",
"available",
"ensure",
"they",
"match",
".",
"If",
"only",
"dtype",
"is",
"available",
"extract",
"the",
"implied",
"freq",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L794-L825 | [
"def",
"validate_dtype_freq",
"(",
"dtype",
",",
"freq",
")",
":",
"if",
"freq",
"is",
"not",
"None",
":",
"freq",
"=",
"frequencies",
".",
"to_offset",
"(",
"freq",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"dtype",
"=",
"pandas_dtype",
"(",
"dtype",
")",
"if",
"not",
"is_period_dtype",
"(",
"dtype",
")",
":",
"raise",
"ValueError",
"(",
"'dtype must be PeriodDtype'",
")",
"if",
"freq",
"is",
"None",
":",
"freq",
"=",
"dtype",
".",
"freq",
"elif",
"freq",
"!=",
"dtype",
".",
"freq",
":",
"raise",
"IncompatibleFrequency",
"(",
"'specified freq and dtype '",
"'are different'",
")",
"return",
"freq"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | dt64arr_to_periodarr | Convert an datetime-like array to values Period ordinals.
Parameters
----------
data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]
freq : Optional[Union[str, Tick]]
Must match the `freq` on the `data` if `data` is a DatetimeIndex
or Series.
tz : Optional[tzinfo]
Returns
-------
ordinals : ndarray[int]
freq : Tick
The frequencey extracted from the Series or DatetimeIndex if that's
used. | pandas/core/arrays/period.py | def dt64arr_to_periodarr(data, freq, tz=None):
"""
Convert an datetime-like array to values Period ordinals.
Parameters
----------
data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]
freq : Optional[Union[str, Tick]]
Must match the `freq` on the `data` if `data` is a DatetimeIndex
or Series.
tz : Optional[tzinfo]
Returns
-------
ordinals : ndarray[int]
freq : Tick
The frequencey extracted from the Series or DatetimeIndex if that's
used.
"""
if data.dtype != np.dtype('M8[ns]'):
raise ValueError('Wrong dtype: {dtype}'.format(dtype=data.dtype))
if freq is None:
if isinstance(data, ABCIndexClass):
data, freq = data._values, data.freq
elif isinstance(data, ABCSeries):
data, freq = data._values, data.dt.freq
freq = Period._maybe_convert_freq(freq)
if isinstance(data, (ABCIndexClass, ABCSeries)):
data = data._values
base, mult = libfrequencies.get_freq_code(freq)
return libperiod.dt64arr_to_periodarr(data.view('i8'), base, tz), freq | def dt64arr_to_periodarr(data, freq, tz=None):
"""
Convert an datetime-like array to values Period ordinals.
Parameters
----------
data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]
freq : Optional[Union[str, Tick]]
Must match the `freq` on the `data` if `data` is a DatetimeIndex
or Series.
tz : Optional[tzinfo]
Returns
-------
ordinals : ndarray[int]
freq : Tick
The frequencey extracted from the Series or DatetimeIndex if that's
used.
"""
if data.dtype != np.dtype('M8[ns]'):
raise ValueError('Wrong dtype: {dtype}'.format(dtype=data.dtype))
if freq is None:
if isinstance(data, ABCIndexClass):
data, freq = data._values, data.freq
elif isinstance(data, ABCSeries):
data, freq = data._values, data.dt.freq
freq = Period._maybe_convert_freq(freq)
if isinstance(data, (ABCIndexClass, ABCSeries)):
data = data._values
base, mult = libfrequencies.get_freq_code(freq)
return libperiod.dt64arr_to_periodarr(data.view('i8'), base, tz), freq | [
"Convert",
"an",
"datetime",
"-",
"like",
"array",
"to",
"values",
"Period",
"ordinals",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L828-L863 | [
"def",
"dt64arr_to_periodarr",
"(",
"data",
",",
"freq",
",",
"tz",
"=",
"None",
")",
":",
"if",
"data",
".",
"dtype",
"!=",
"np",
".",
"dtype",
"(",
"'M8[ns]'",
")",
":",
"raise",
"ValueError",
"(",
"'Wrong dtype: {dtype}'",
".",
"format",
"(",
"dtype",
"=",
"data",
".",
"dtype",
")",
")",
"if",
"freq",
"is",
"None",
":",
"if",
"isinstance",
"(",
"data",
",",
"ABCIndexClass",
")",
":",
"data",
",",
"freq",
"=",
"data",
".",
"_values",
",",
"data",
".",
"freq",
"elif",
"isinstance",
"(",
"data",
",",
"ABCSeries",
")",
":",
"data",
",",
"freq",
"=",
"data",
".",
"_values",
",",
"data",
".",
"dt",
".",
"freq",
"freq",
"=",
"Period",
".",
"_maybe_convert_freq",
"(",
"freq",
")",
"if",
"isinstance",
"(",
"data",
",",
"(",
"ABCIndexClass",
",",
"ABCSeries",
")",
")",
":",
"data",
"=",
"data",
".",
"_values",
"base",
",",
"mult",
"=",
"libfrequencies",
".",
"get_freq_code",
"(",
"freq",
")",
"return",
"libperiod",
".",
"dt64arr_to_periodarr",
"(",
"data",
".",
"view",
"(",
"'i8'",
")",
",",
"base",
",",
"tz",
")",
",",
"freq"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray._from_datetime64 | Construct a PeriodArray from a datetime64 array
Parameters
----------
data : ndarray[datetime64[ns], datetime64[ns, tz]]
freq : str or Tick
tz : tzinfo, optional
Returns
-------
PeriodArray[freq] | pandas/core/arrays/period.py | def _from_datetime64(cls, data, freq, tz=None):
"""
Construct a PeriodArray from a datetime64 array
Parameters
----------
data : ndarray[datetime64[ns], datetime64[ns, tz]]
freq : str or Tick
tz : tzinfo, optional
Returns
-------
PeriodArray[freq]
"""
data, freq = dt64arr_to_periodarr(data, freq, tz)
return cls(data, freq=freq) | def _from_datetime64(cls, data, freq, tz=None):
"""
Construct a PeriodArray from a datetime64 array
Parameters
----------
data : ndarray[datetime64[ns], datetime64[ns, tz]]
freq : str or Tick
tz : tzinfo, optional
Returns
-------
PeriodArray[freq]
"""
data, freq = dt64arr_to_periodarr(data, freq, tz)
return cls(data, freq=freq) | [
"Construct",
"a",
"PeriodArray",
"from",
"a",
"datetime64",
"array"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L211-L226 | [
"def",
"_from_datetime64",
"(",
"cls",
",",
"data",
",",
"freq",
",",
"tz",
"=",
"None",
")",
":",
"data",
",",
"freq",
"=",
"dt64arr_to_periodarr",
"(",
"data",
",",
"freq",
",",
"tz",
")",
"return",
"cls",
"(",
"data",
",",
"freq",
"=",
"freq",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray.to_timestamp | Cast to DatetimeArray/Index.
Parameters
----------
freq : string or DateOffset, optional
Target frequency. The default is 'D' for week or longer,
'S' otherwise
how : {'s', 'e', 'start', 'end'}
Returns
-------
DatetimeArray/Index | pandas/core/arrays/period.py | def to_timestamp(self, freq=None, how='start'):
"""
Cast to DatetimeArray/Index.
Parameters
----------
freq : string or DateOffset, optional
Target frequency. The default is 'D' for week or longer,
'S' otherwise
how : {'s', 'e', 'start', 'end'}
Returns
-------
DatetimeArray/Index
"""
from pandas.core.arrays import DatetimeArray
how = libperiod._validate_end_alias(how)
end = how == 'E'
if end:
if freq == 'B':
# roll forward to ensure we land on B date
adjust = Timedelta(1, 'D') - Timedelta(1, 'ns')
return self.to_timestamp(how='start') + adjust
else:
adjust = Timedelta(1, 'ns')
return (self + self.freq).to_timestamp(how='start') - adjust
if freq is None:
base, mult = libfrequencies.get_freq_code(self.freq)
freq = libfrequencies.get_to_timestamp_base(base)
else:
freq = Period._maybe_convert_freq(freq)
base, mult = libfrequencies.get_freq_code(freq)
new_data = self.asfreq(freq, how=how)
new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base)
return DatetimeArray._from_sequence(new_data, freq='infer') | def to_timestamp(self, freq=None, how='start'):
"""
Cast to DatetimeArray/Index.
Parameters
----------
freq : string or DateOffset, optional
Target frequency. The default is 'D' for week or longer,
'S' otherwise
how : {'s', 'e', 'start', 'end'}
Returns
-------
DatetimeArray/Index
"""
from pandas.core.arrays import DatetimeArray
how = libperiod._validate_end_alias(how)
end = how == 'E'
if end:
if freq == 'B':
# roll forward to ensure we land on B date
adjust = Timedelta(1, 'D') - Timedelta(1, 'ns')
return self.to_timestamp(how='start') + adjust
else:
adjust = Timedelta(1, 'ns')
return (self + self.freq).to_timestamp(how='start') - adjust
if freq is None:
base, mult = libfrequencies.get_freq_code(self.freq)
freq = libfrequencies.get_to_timestamp_base(base)
else:
freq = Period._maybe_convert_freq(freq)
base, mult = libfrequencies.get_freq_code(freq)
new_data = self.asfreq(freq, how=how)
new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base)
return DatetimeArray._from_sequence(new_data, freq='infer') | [
"Cast",
"to",
"DatetimeArray",
"/",
"Index",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L327-L366 | [
"def",
"to_timestamp",
"(",
"self",
",",
"freq",
"=",
"None",
",",
"how",
"=",
"'start'",
")",
":",
"from",
"pandas",
".",
"core",
".",
"arrays",
"import",
"DatetimeArray",
"how",
"=",
"libperiod",
".",
"_validate_end_alias",
"(",
"how",
")",
"end",
"=",
"how",
"==",
"'E'",
"if",
"end",
":",
"if",
"freq",
"==",
"'B'",
":",
"# roll forward to ensure we land on B date",
"adjust",
"=",
"Timedelta",
"(",
"1",
",",
"'D'",
")",
"-",
"Timedelta",
"(",
"1",
",",
"'ns'",
")",
"return",
"self",
".",
"to_timestamp",
"(",
"how",
"=",
"'start'",
")",
"+",
"adjust",
"else",
":",
"adjust",
"=",
"Timedelta",
"(",
"1",
",",
"'ns'",
")",
"return",
"(",
"self",
"+",
"self",
".",
"freq",
")",
".",
"to_timestamp",
"(",
"how",
"=",
"'start'",
")",
"-",
"adjust",
"if",
"freq",
"is",
"None",
":",
"base",
",",
"mult",
"=",
"libfrequencies",
".",
"get_freq_code",
"(",
"self",
".",
"freq",
")",
"freq",
"=",
"libfrequencies",
".",
"get_to_timestamp_base",
"(",
"base",
")",
"else",
":",
"freq",
"=",
"Period",
".",
"_maybe_convert_freq",
"(",
"freq",
")",
"base",
",",
"mult",
"=",
"libfrequencies",
".",
"get_freq_code",
"(",
"freq",
")",
"new_data",
"=",
"self",
".",
"asfreq",
"(",
"freq",
",",
"how",
"=",
"how",
")",
"new_data",
"=",
"libperiod",
".",
"periodarr_to_dt64arr",
"(",
"new_data",
".",
"asi8",
",",
"base",
")",
"return",
"DatetimeArray",
".",
"_from_sequence",
"(",
"new_data",
",",
"freq",
"=",
"'infer'",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray._time_shift | Shift each value by `periods`.
Note this is different from ExtensionArray.shift, which
shifts the *position* of each element, padding the end with
missing values.
Parameters
----------
periods : int
Number of periods to shift by.
freq : pandas.DateOffset, pandas.Timedelta, or string
Frequency increment to shift by. | pandas/core/arrays/period.py | def _time_shift(self, periods, freq=None):
"""
Shift each value by `periods`.
Note this is different from ExtensionArray.shift, which
shifts the *position* of each element, padding the end with
missing values.
Parameters
----------
periods : int
Number of periods to shift by.
freq : pandas.DateOffset, pandas.Timedelta, or string
Frequency increment to shift by.
"""
if freq is not None:
raise TypeError("`freq` argument is not supported for "
"{cls}._time_shift"
.format(cls=type(self).__name__))
values = self.asi8 + periods * self.freq.n
if self._hasnans:
values[self._isnan] = iNaT
return type(self)(values, freq=self.freq) | def _time_shift(self, periods, freq=None):
"""
Shift each value by `periods`.
Note this is different from ExtensionArray.shift, which
shifts the *position* of each element, padding the end with
missing values.
Parameters
----------
periods : int
Number of periods to shift by.
freq : pandas.DateOffset, pandas.Timedelta, or string
Frequency increment to shift by.
"""
if freq is not None:
raise TypeError("`freq` argument is not supported for "
"{cls}._time_shift"
.format(cls=type(self).__name__))
values = self.asi8 + periods * self.freq.n
if self._hasnans:
values[self._isnan] = iNaT
return type(self)(values, freq=self.freq) | [
"Shift",
"each",
"value",
"by",
"periods",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L390-L412 | [
"def",
"_time_shift",
"(",
"self",
",",
"periods",
",",
"freq",
"=",
"None",
")",
":",
"if",
"freq",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"`freq` argument is not supported for \"",
"\"{cls}._time_shift\"",
".",
"format",
"(",
"cls",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
")",
")",
"values",
"=",
"self",
".",
"asi8",
"+",
"periods",
"*",
"self",
".",
"freq",
".",
"n",
"if",
"self",
".",
"_hasnans",
":",
"values",
"[",
"self",
".",
"_isnan",
"]",
"=",
"iNaT",
"return",
"type",
"(",
"self",
")",
"(",
"values",
",",
"freq",
"=",
"self",
".",
"freq",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray.asfreq | Convert the Period Array/Index to the specified frequency `freq`.
Parameters
----------
freq : str
a frequency
how : str {'E', 'S'}
'E', 'END', or 'FINISH' for end,
'S', 'START', or 'BEGIN' for start.
Whether the elements should be aligned to the end
or start within pa period. January 31st ('END') vs.
January 1st ('START') for example.
Returns
-------
new : Period Array/Index with the new frequency
Examples
--------
>>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
>>> pidx
PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],
dtype='period[A-DEC]', freq='A-DEC')
>>> pidx.asfreq('M')
PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12',
'2015-12'], dtype='period[M]', freq='M')
>>> pidx.asfreq('M', how='S')
PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',
'2015-01'], dtype='period[M]', freq='M') | pandas/core/arrays/period.py | def asfreq(self, freq=None, how='E'):
"""
Convert the Period Array/Index to the specified frequency `freq`.
Parameters
----------
freq : str
a frequency
how : str {'E', 'S'}
'E', 'END', or 'FINISH' for end,
'S', 'START', or 'BEGIN' for start.
Whether the elements should be aligned to the end
or start within pa period. January 31st ('END') vs.
January 1st ('START') for example.
Returns
-------
new : Period Array/Index with the new frequency
Examples
--------
>>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
>>> pidx
PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],
dtype='period[A-DEC]', freq='A-DEC')
>>> pidx.asfreq('M')
PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12',
'2015-12'], dtype='period[M]', freq='M')
>>> pidx.asfreq('M', how='S')
PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',
'2015-01'], dtype='period[M]', freq='M')
"""
how = libperiod._validate_end_alias(how)
freq = Period._maybe_convert_freq(freq)
base1, mult1 = libfrequencies.get_freq_code(self.freq)
base2, mult2 = libfrequencies.get_freq_code(freq)
asi8 = self.asi8
# mult1 can't be negative or 0
end = how == 'E'
if end:
ordinal = asi8 + mult1 - 1
else:
ordinal = asi8
new_data = period_asfreq_arr(ordinal, base1, base2, end)
if self._hasnans:
new_data[self._isnan] = iNaT
return type(self)(new_data, freq=freq) | def asfreq(self, freq=None, how='E'):
"""
Convert the Period Array/Index to the specified frequency `freq`.
Parameters
----------
freq : str
a frequency
how : str {'E', 'S'}
'E', 'END', or 'FINISH' for end,
'S', 'START', or 'BEGIN' for start.
Whether the elements should be aligned to the end
or start within pa period. January 31st ('END') vs.
January 1st ('START') for example.
Returns
-------
new : Period Array/Index with the new frequency
Examples
--------
>>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
>>> pidx
PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],
dtype='period[A-DEC]', freq='A-DEC')
>>> pidx.asfreq('M')
PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12',
'2015-12'], dtype='period[M]', freq='M')
>>> pidx.asfreq('M', how='S')
PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',
'2015-01'], dtype='period[M]', freq='M')
"""
how = libperiod._validate_end_alias(how)
freq = Period._maybe_convert_freq(freq)
base1, mult1 = libfrequencies.get_freq_code(self.freq)
base2, mult2 = libfrequencies.get_freq_code(freq)
asi8 = self.asi8
# mult1 can't be negative or 0
end = how == 'E'
if end:
ordinal = asi8 + mult1 - 1
else:
ordinal = asi8
new_data = period_asfreq_arr(ordinal, base1, base2, end)
if self._hasnans:
new_data[self._isnan] = iNaT
return type(self)(new_data, freq=freq) | [
"Convert",
"the",
"Period",
"Array",
"/",
"Index",
"to",
"the",
"specified",
"frequency",
"freq",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L418-L472 | [
"def",
"asfreq",
"(",
"self",
",",
"freq",
"=",
"None",
",",
"how",
"=",
"'E'",
")",
":",
"how",
"=",
"libperiod",
".",
"_validate_end_alias",
"(",
"how",
")",
"freq",
"=",
"Period",
".",
"_maybe_convert_freq",
"(",
"freq",
")",
"base1",
",",
"mult1",
"=",
"libfrequencies",
".",
"get_freq_code",
"(",
"self",
".",
"freq",
")",
"base2",
",",
"mult2",
"=",
"libfrequencies",
".",
"get_freq_code",
"(",
"freq",
")",
"asi8",
"=",
"self",
".",
"asi8",
"# mult1 can't be negative or 0",
"end",
"=",
"how",
"==",
"'E'",
"if",
"end",
":",
"ordinal",
"=",
"asi8",
"+",
"mult1",
"-",
"1",
"else",
":",
"ordinal",
"=",
"asi8",
"new_data",
"=",
"period_asfreq_arr",
"(",
"ordinal",
",",
"base1",
",",
"base2",
",",
"end",
")",
"if",
"self",
".",
"_hasnans",
":",
"new_data",
"[",
"self",
".",
"_isnan",
"]",
"=",
"iNaT",
"return",
"type",
"(",
"self",
")",
"(",
"new_data",
",",
"freq",
"=",
"freq",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray._format_native_types | actually format my specific types | pandas/core/arrays/period.py | def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs):
"""
actually format my specific types
"""
values = self.astype(object)
if date_format:
formatter = lambda dt: dt.strftime(date_format)
else:
formatter = lambda dt: '%s' % dt
if self._hasnans:
mask = self._isnan
values[mask] = na_rep
imask = ~mask
values[imask] = np.array([formatter(dt) for dt
in values[imask]])
else:
values = np.array([formatter(dt) for dt in values])
return values | def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs):
"""
actually format my specific types
"""
values = self.astype(object)
if date_format:
formatter = lambda dt: dt.strftime(date_format)
else:
formatter = lambda dt: '%s' % dt
if self._hasnans:
mask = self._isnan
values[mask] = na_rep
imask = ~mask
values[imask] = np.array([formatter(dt) for dt
in values[imask]])
else:
values = np.array([formatter(dt) for dt in values])
return values | [
"actually",
"format",
"my",
"specific",
"types"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L477-L496 | [
"def",
"_format_native_types",
"(",
"self",
",",
"na_rep",
"=",
"'NaT'",
",",
"date_format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"self",
".",
"astype",
"(",
"object",
")",
"if",
"date_format",
":",
"formatter",
"=",
"lambda",
"dt",
":",
"dt",
".",
"strftime",
"(",
"date_format",
")",
"else",
":",
"formatter",
"=",
"lambda",
"dt",
":",
"'%s'",
"%",
"dt",
"if",
"self",
".",
"_hasnans",
":",
"mask",
"=",
"self",
".",
"_isnan",
"values",
"[",
"mask",
"]",
"=",
"na_rep",
"imask",
"=",
"~",
"mask",
"values",
"[",
"imask",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"formatter",
"(",
"dt",
")",
"for",
"dt",
"in",
"values",
"[",
"imask",
"]",
"]",
")",
"else",
":",
"values",
"=",
"np",
".",
"array",
"(",
"[",
"formatter",
"(",
"dt",
")",
"for",
"dt",
"in",
"values",
"]",
")",
"return",
"values"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray._add_timedeltalike_scalar | Parameters
----------
other : timedelta, Tick, np.timedelta64
Returns
-------
result : ndarray[int64] | pandas/core/arrays/period.py | def _add_timedeltalike_scalar(self, other):
"""
Parameters
----------
other : timedelta, Tick, np.timedelta64
Returns
-------
result : ndarray[int64]
"""
assert isinstance(self.freq, Tick) # checked by calling function
assert isinstance(other, (timedelta, np.timedelta64, Tick))
if notna(other):
# special handling for np.timedelta64("NaT"), avoid calling
# _check_timedeltalike_freq_compat as that would raise TypeError
other = self._check_timedeltalike_freq_compat(other)
# Note: when calling parent class's _add_timedeltalike_scalar,
# it will call delta_to_nanoseconds(delta). Because delta here
# is an integer, delta_to_nanoseconds will return it unchanged.
ordinals = super()._add_timedeltalike_scalar(other)
return ordinals | def _add_timedeltalike_scalar(self, other):
"""
Parameters
----------
other : timedelta, Tick, np.timedelta64
Returns
-------
result : ndarray[int64]
"""
assert isinstance(self.freq, Tick) # checked by calling function
assert isinstance(other, (timedelta, np.timedelta64, Tick))
if notna(other):
# special handling for np.timedelta64("NaT"), avoid calling
# _check_timedeltalike_freq_compat as that would raise TypeError
other = self._check_timedeltalike_freq_compat(other)
# Note: when calling parent class's _add_timedeltalike_scalar,
# it will call delta_to_nanoseconds(delta). Because delta here
# is an integer, delta_to_nanoseconds will return it unchanged.
ordinals = super()._add_timedeltalike_scalar(other)
return ordinals | [
"Parameters",
"----------",
"other",
":",
"timedelta",
"Tick",
"np",
".",
"timedelta64"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L565-L587 | [
"def",
"_add_timedeltalike_scalar",
"(",
"self",
",",
"other",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"freq",
",",
"Tick",
")",
"# checked by calling function",
"assert",
"isinstance",
"(",
"other",
",",
"(",
"timedelta",
",",
"np",
".",
"timedelta64",
",",
"Tick",
")",
")",
"if",
"notna",
"(",
"other",
")",
":",
"# special handling for np.timedelta64(\"NaT\"), avoid calling",
"# _check_timedeltalike_freq_compat as that would raise TypeError",
"other",
"=",
"self",
".",
"_check_timedeltalike_freq_compat",
"(",
"other",
")",
"# Note: when calling parent class's _add_timedeltalike_scalar,",
"# it will call delta_to_nanoseconds(delta). Because delta here",
"# is an integer, delta_to_nanoseconds will return it unchanged.",
"ordinals",
"=",
"super",
"(",
")",
".",
"_add_timedeltalike_scalar",
"(",
"other",
")",
"return",
"ordinals"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray._add_delta_tdi | Parameters
----------
other : TimedeltaArray or ndarray[timedelta64]
Returns
-------
result : ndarray[int64] | pandas/core/arrays/period.py | def _add_delta_tdi(self, other):
"""
Parameters
----------
other : TimedeltaArray or ndarray[timedelta64]
Returns
-------
result : ndarray[int64]
"""
assert isinstance(self.freq, Tick) # checked by calling function
delta = self._check_timedeltalike_freq_compat(other)
return self._addsub_int_array(delta, operator.add).asi8 | def _add_delta_tdi(self, other):
"""
Parameters
----------
other : TimedeltaArray or ndarray[timedelta64]
Returns
-------
result : ndarray[int64]
"""
assert isinstance(self.freq, Tick) # checked by calling function
delta = self._check_timedeltalike_freq_compat(other)
return self._addsub_int_array(delta, operator.add).asi8 | [
"Parameters",
"----------",
"other",
":",
"TimedeltaArray",
"or",
"ndarray",
"[",
"timedelta64",
"]"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L589-L602 | [
"def",
"_add_delta_tdi",
"(",
"self",
",",
"other",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"freq",
",",
"Tick",
")",
"# checked by calling function",
"delta",
"=",
"self",
".",
"_check_timedeltalike_freq_compat",
"(",
"other",
")",
"return",
"self",
".",
"_addsub_int_array",
"(",
"delta",
",",
"operator",
".",
"add",
")",
".",
"asi8"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray._add_delta | Add a timedelta-like, Tick, or TimedeltaIndex-like object
to self, yielding a new PeriodArray
Parameters
----------
other : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : PeriodArray | pandas/core/arrays/period.py | def _add_delta(self, other):
"""
Add a timedelta-like, Tick, or TimedeltaIndex-like object
to self, yielding a new PeriodArray
Parameters
----------
other : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : PeriodArray
"""
if not isinstance(self.freq, Tick):
# We cannot add timedelta-like to non-tick PeriodArray
_raise_on_incompatible(self, other)
new_ordinals = super()._add_delta(other)
return type(self)(new_ordinals, freq=self.freq) | def _add_delta(self, other):
"""
Add a timedelta-like, Tick, or TimedeltaIndex-like object
to self, yielding a new PeriodArray
Parameters
----------
other : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : PeriodArray
"""
if not isinstance(self.freq, Tick):
# We cannot add timedelta-like to non-tick PeriodArray
_raise_on_incompatible(self, other)
new_ordinals = super()._add_delta(other)
return type(self)(new_ordinals, freq=self.freq) | [
"Add",
"a",
"timedelta",
"-",
"like",
"Tick",
"or",
"TimedeltaIndex",
"-",
"like",
"object",
"to",
"self",
"yielding",
"a",
"new",
"PeriodArray"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L604-L623 | [
"def",
"_add_delta",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"freq",
",",
"Tick",
")",
":",
"# We cannot add timedelta-like to non-tick PeriodArray",
"_raise_on_incompatible",
"(",
"self",
",",
"other",
")",
"new_ordinals",
"=",
"super",
"(",
")",
".",
"_add_delta",
"(",
"other",
")",
"return",
"type",
"(",
"self",
")",
"(",
"new_ordinals",
",",
"freq",
"=",
"self",
".",
"freq",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | PeriodArray._check_timedeltalike_freq_compat | Arithmetic operations with timedelta-like scalars or array `other`
are only valid if `other` is an integer multiple of `self.freq`.
If the operation is valid, find that integer multiple. Otherwise,
raise because the operation is invalid.
Parameters
----------
other : timedelta, np.timedelta64, Tick,
ndarray[timedelta64], TimedeltaArray, TimedeltaIndex
Returns
-------
multiple : int or ndarray[int64]
Raises
------
IncompatibleFrequency | pandas/core/arrays/period.py | def _check_timedeltalike_freq_compat(self, other):
"""
Arithmetic operations with timedelta-like scalars or array `other`
are only valid if `other` is an integer multiple of `self.freq`.
If the operation is valid, find that integer multiple. Otherwise,
raise because the operation is invalid.
Parameters
----------
other : timedelta, np.timedelta64, Tick,
ndarray[timedelta64], TimedeltaArray, TimedeltaIndex
Returns
-------
multiple : int or ndarray[int64]
Raises
------
IncompatibleFrequency
"""
assert isinstance(self.freq, Tick) # checked by calling function
own_offset = frequencies.to_offset(self.freq.rule_code)
base_nanos = delta_to_nanoseconds(own_offset)
if isinstance(other, (timedelta, np.timedelta64, Tick)):
nanos = delta_to_nanoseconds(other)
elif isinstance(other, np.ndarray):
# numpy timedelta64 array; all entries must be compatible
assert other.dtype.kind == 'm'
if other.dtype != _TD_DTYPE:
# i.e. non-nano unit
# TODO: disallow unit-less timedelta64
other = other.astype(_TD_DTYPE)
nanos = other.view('i8')
else:
# TimedeltaArray/Index
nanos = other.asi8
if np.all(nanos % base_nanos == 0):
# nanos being added is an integer multiple of the
# base-frequency to self.freq
delta = nanos // base_nanos
# delta is the integer (or integer-array) number of periods
# by which will be added to self.
return delta
_raise_on_incompatible(self, other) | def _check_timedeltalike_freq_compat(self, other):
"""
Arithmetic operations with timedelta-like scalars or array `other`
are only valid if `other` is an integer multiple of `self.freq`.
If the operation is valid, find that integer multiple. Otherwise,
raise because the operation is invalid.
Parameters
----------
other : timedelta, np.timedelta64, Tick,
ndarray[timedelta64], TimedeltaArray, TimedeltaIndex
Returns
-------
multiple : int or ndarray[int64]
Raises
------
IncompatibleFrequency
"""
assert isinstance(self.freq, Tick) # checked by calling function
own_offset = frequencies.to_offset(self.freq.rule_code)
base_nanos = delta_to_nanoseconds(own_offset)
if isinstance(other, (timedelta, np.timedelta64, Tick)):
nanos = delta_to_nanoseconds(other)
elif isinstance(other, np.ndarray):
# numpy timedelta64 array; all entries must be compatible
assert other.dtype.kind == 'm'
if other.dtype != _TD_DTYPE:
# i.e. non-nano unit
# TODO: disallow unit-less timedelta64
other = other.astype(_TD_DTYPE)
nanos = other.view('i8')
else:
# TimedeltaArray/Index
nanos = other.asi8
if np.all(nanos % base_nanos == 0):
# nanos being added is an integer multiple of the
# base-frequency to self.freq
delta = nanos // base_nanos
# delta is the integer (or integer-array) number of periods
# by which will be added to self.
return delta
_raise_on_incompatible(self, other) | [
"Arithmetic",
"operations",
"with",
"timedelta",
"-",
"like",
"scalars",
"or",
"array",
"other",
"are",
"only",
"valid",
"if",
"other",
"is",
"an",
"integer",
"multiple",
"of",
"self",
".",
"freq",
".",
"If",
"the",
"operation",
"is",
"valid",
"find",
"that",
"integer",
"multiple",
".",
"Otherwise",
"raise",
"because",
"the",
"operation",
"is",
"invalid",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/period.py#L625-L672 | [
"def",
"_check_timedeltalike_freq_compat",
"(",
"self",
",",
"other",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"freq",
",",
"Tick",
")",
"# checked by calling function",
"own_offset",
"=",
"frequencies",
".",
"to_offset",
"(",
"self",
".",
"freq",
".",
"rule_code",
")",
"base_nanos",
"=",
"delta_to_nanoseconds",
"(",
"own_offset",
")",
"if",
"isinstance",
"(",
"other",
",",
"(",
"timedelta",
",",
"np",
".",
"timedelta64",
",",
"Tick",
")",
")",
":",
"nanos",
"=",
"delta_to_nanoseconds",
"(",
"other",
")",
"elif",
"isinstance",
"(",
"other",
",",
"np",
".",
"ndarray",
")",
":",
"# numpy timedelta64 array; all entries must be compatible",
"assert",
"other",
".",
"dtype",
".",
"kind",
"==",
"'m'",
"if",
"other",
".",
"dtype",
"!=",
"_TD_DTYPE",
":",
"# i.e. non-nano unit",
"# TODO: disallow unit-less timedelta64",
"other",
"=",
"other",
".",
"astype",
"(",
"_TD_DTYPE",
")",
"nanos",
"=",
"other",
".",
"view",
"(",
"'i8'",
")",
"else",
":",
"# TimedeltaArray/Index",
"nanos",
"=",
"other",
".",
"asi8",
"if",
"np",
".",
"all",
"(",
"nanos",
"%",
"base_nanos",
"==",
"0",
")",
":",
"# nanos being added is an integer multiple of the",
"# base-frequency to self.freq",
"delta",
"=",
"nanos",
"//",
"base_nanos",
"# delta is the integer (or integer-array) number of periods",
"# by which will be added to self.",
"return",
"delta",
"_raise_on_incompatible",
"(",
"self",
",",
"other",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _isna_old | Detect missing values. Treat None, NaN, INF, -INF as null.
Parameters
----------
arr: ndarray or object value
Returns
-------
boolean ndarray or boolean | pandas/core/dtypes/missing.py | def _isna_old(obj):
"""Detect missing values. Treat None, NaN, INF, -INF as null.
Parameters
----------
arr: ndarray or object value
Returns
-------
boolean ndarray or boolean
"""
if is_scalar(obj):
return libmissing.checknull_old(obj)
# hack (for now) because MI registers as ndarray
elif isinstance(obj, ABCMultiIndex):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCGeneric):
return obj._constructor(obj._data.isna(func=_isna_old))
elif isinstance(obj, list):
return _isna_ndarraylike_old(np.asarray(obj, dtype=object))
elif hasattr(obj, '__array__'):
return _isna_ndarraylike_old(np.asarray(obj))
else:
return obj is None | def _isna_old(obj):
"""Detect missing values. Treat None, NaN, INF, -INF as null.
Parameters
----------
arr: ndarray or object value
Returns
-------
boolean ndarray or boolean
"""
if is_scalar(obj):
return libmissing.checknull_old(obj)
# hack (for now) because MI registers as ndarray
elif isinstance(obj, ABCMultiIndex):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCGeneric):
return obj._constructor(obj._data.isna(func=_isna_old))
elif isinstance(obj, list):
return _isna_ndarraylike_old(np.asarray(obj, dtype=object))
elif hasattr(obj, '__array__'):
return _isna_ndarraylike_old(np.asarray(obj))
else:
return obj is None | [
"Detect",
"missing",
"values",
".",
"Treat",
"None",
"NaN",
"INF",
"-",
"INF",
"as",
"null",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L126-L151 | [
"def",
"_isna_old",
"(",
"obj",
")",
":",
"if",
"is_scalar",
"(",
"obj",
")",
":",
"return",
"libmissing",
".",
"checknull_old",
"(",
"obj",
")",
"# hack (for now) because MI registers as ndarray",
"elif",
"isinstance",
"(",
"obj",
",",
"ABCMultiIndex",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"isna is not defined for MultiIndex\"",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"ABCSeries",
",",
"np",
".",
"ndarray",
",",
"ABCIndexClass",
")",
")",
":",
"return",
"_isna_ndarraylike_old",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"ABCGeneric",
")",
":",
"return",
"obj",
".",
"_constructor",
"(",
"obj",
".",
"_data",
".",
"isna",
"(",
"func",
"=",
"_isna_old",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"_isna_ndarraylike_old",
"(",
"np",
".",
"asarray",
"(",
"obj",
",",
"dtype",
"=",
"object",
")",
")",
"elif",
"hasattr",
"(",
"obj",
",",
"'__array__'",
")",
":",
"return",
"_isna_ndarraylike_old",
"(",
"np",
".",
"asarray",
"(",
"obj",
")",
")",
"else",
":",
"return",
"obj",
"is",
"None"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _use_inf_as_na | Option change callback for na/inf behaviour
Choose which replacement for numpy.isnan / -numpy.isfinite is used.
Parameters
----------
flag: bool
True means treat None, NaN, INF, -INF as null (old way),
False means None and NaN are null, but INF, -INF are not null
(new way).
Notes
-----
This approach to setting global module values is discussed and
approved here:
* http://stackoverflow.com/questions/4859217/
programmatically-creating-variables-in-python/4859312#4859312 | pandas/core/dtypes/missing.py | def _use_inf_as_na(key):
"""Option change callback for na/inf behaviour
Choose which replacement for numpy.isnan / -numpy.isfinite is used.
Parameters
----------
flag: bool
True means treat None, NaN, INF, -INF as null (old way),
False means None and NaN are null, but INF, -INF are not null
(new way).
Notes
-----
This approach to setting global module values is discussed and
approved here:
* http://stackoverflow.com/questions/4859217/
programmatically-creating-variables-in-python/4859312#4859312
"""
from pandas._config import get_option
flag = get_option(key)
if flag:
globals()['_isna'] = _isna_old
else:
globals()['_isna'] = _isna_new | def _use_inf_as_na(key):
"""Option change callback for na/inf behaviour
Choose which replacement for numpy.isnan / -numpy.isfinite is used.
Parameters
----------
flag: bool
True means treat None, NaN, INF, -INF as null (old way),
False means None and NaN are null, but INF, -INF are not null
(new way).
Notes
-----
This approach to setting global module values is discussed and
approved here:
* http://stackoverflow.com/questions/4859217/
programmatically-creating-variables-in-python/4859312#4859312
"""
from pandas._config import get_option
flag = get_option(key)
if flag:
globals()['_isna'] = _isna_old
else:
globals()['_isna'] = _isna_new | [
"Option",
"change",
"callback",
"for",
"na",
"/",
"inf",
"behaviour",
"Choose",
"which",
"replacement",
"for",
"numpy",
".",
"isnan",
"/",
"-",
"numpy",
".",
"isfinite",
"is",
"used",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L157-L181 | [
"def",
"_use_inf_as_na",
"(",
"key",
")",
":",
"from",
"pandas",
".",
"_config",
"import",
"get_option",
"flag",
"=",
"get_option",
"(",
"key",
")",
"if",
"flag",
":",
"globals",
"(",
")",
"[",
"'_isna'",
"]",
"=",
"_isna_old",
"else",
":",
"globals",
"(",
")",
"[",
"'_isna'",
"]",
"=",
"_isna_new"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _isna_compat | Parameters
----------
arr: a numpy array
fill_value: fill value, default to np.nan
Returns
-------
True if we can fill using this fill_value | pandas/core/dtypes/missing.py | def _isna_compat(arr, fill_value=np.nan):
"""
Parameters
----------
arr: a numpy array
fill_value: fill value, default to np.nan
Returns
-------
True if we can fill using this fill_value
"""
dtype = arr.dtype
if isna(fill_value):
return not (is_bool_dtype(dtype) or
is_integer_dtype(dtype))
return True | def _isna_compat(arr, fill_value=np.nan):
"""
Parameters
----------
arr: a numpy array
fill_value: fill value, default to np.nan
Returns
-------
True if we can fill using this fill_value
"""
dtype = arr.dtype
if isna(fill_value):
return not (is_bool_dtype(dtype) or
is_integer_dtype(dtype))
return True | [
"Parameters",
"----------",
"arr",
":",
"a",
"numpy",
"array",
"fill_value",
":",
"fill",
"value",
"default",
"to",
"np",
".",
"nan"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L343-L358 | [
"def",
"_isna_compat",
"(",
"arr",
",",
"fill_value",
"=",
"np",
".",
"nan",
")",
":",
"dtype",
"=",
"arr",
".",
"dtype",
"if",
"isna",
"(",
"fill_value",
")",
":",
"return",
"not",
"(",
"is_bool_dtype",
"(",
"dtype",
")",
"or",
"is_integer_dtype",
"(",
"dtype",
")",
")",
"return",
"True"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | array_equivalent | True if two arrays, left and right, have equal non-NaN elements, and NaNs
in corresponding locations. False otherwise. It is assumed that left and
right are NumPy arrays of the same dtype. The behavior of this function
(particularly with respect to NaNs) is not defined if the dtypes are
different.
Parameters
----------
left, right : ndarrays
strict_nan : bool, default False
If True, consider NaN and None to be different.
Returns
-------
b : bool
Returns True if the arrays are equivalent.
Examples
--------
>>> array_equivalent(
... np.array([1, 2, np.nan]),
... np.array([1, 2, np.nan]))
True
>>> array_equivalent(
... np.array([1, np.nan, 2]),
... np.array([1, 2, np.nan]))
False | pandas/core/dtypes/missing.py | def array_equivalent(left, right, strict_nan=False):
"""
True if two arrays, left and right, have equal non-NaN elements, and NaNs
in corresponding locations. False otherwise. It is assumed that left and
right are NumPy arrays of the same dtype. The behavior of this function
(particularly with respect to NaNs) is not defined if the dtypes are
different.
Parameters
----------
left, right : ndarrays
strict_nan : bool, default False
If True, consider NaN and None to be different.
Returns
-------
b : bool
Returns True if the arrays are equivalent.
Examples
--------
>>> array_equivalent(
... np.array([1, 2, np.nan]),
... np.array([1, 2, np.nan]))
True
>>> array_equivalent(
... np.array([1, np.nan, 2]),
... np.array([1, 2, np.nan]))
False
"""
left, right = np.asarray(left), np.asarray(right)
# shape compat
if left.shape != right.shape:
return False
# Object arrays can contain None, NaN and NaT.
# string dtypes must be come to this path for NumPy 1.7.1 compat
if is_string_dtype(left) or is_string_dtype(right):
if not strict_nan:
# isna considers NaN and None to be equivalent.
return lib.array_equivalent_object(
ensure_object(left.ravel()), ensure_object(right.ravel()))
for left_value, right_value in zip(left, right):
if left_value is NaT and right_value is not NaT:
return False
elif isinstance(left_value, float) and np.isnan(left_value):
if (not isinstance(right_value, float) or
not np.isnan(right_value)):
return False
else:
if left_value != right_value:
return False
return True
# NaNs can occur in float and complex arrays.
if is_float_dtype(left) or is_complex_dtype(left):
# empty
if not (np.prod(left.shape) and np.prod(right.shape)):
return True
return ((left == right) | (isna(left) & isna(right))).all()
# numpy will will not allow this type of datetimelike vs integer comparison
elif is_datetimelike_v_numeric(left, right):
return False
# M8/m8
elif needs_i8_conversion(left) and needs_i8_conversion(right):
if not is_dtype_equal(left.dtype, right.dtype):
return False
left = left.view('i8')
right = right.view('i8')
# if we have structured dtypes, compare first
if (left.dtype.type is np.void or
right.dtype.type is np.void):
if left.dtype != right.dtype:
return False
return np.array_equal(left, right) | def array_equivalent(left, right, strict_nan=False):
"""
True if two arrays, left and right, have equal non-NaN elements, and NaNs
in corresponding locations. False otherwise. It is assumed that left and
right are NumPy arrays of the same dtype. The behavior of this function
(particularly with respect to NaNs) is not defined if the dtypes are
different.
Parameters
----------
left, right : ndarrays
strict_nan : bool, default False
If True, consider NaN and None to be different.
Returns
-------
b : bool
Returns True if the arrays are equivalent.
Examples
--------
>>> array_equivalent(
... np.array([1, 2, np.nan]),
... np.array([1, 2, np.nan]))
True
>>> array_equivalent(
... np.array([1, np.nan, 2]),
... np.array([1, 2, np.nan]))
False
"""
left, right = np.asarray(left), np.asarray(right)
# shape compat
if left.shape != right.shape:
return False
# Object arrays can contain None, NaN and NaT.
# string dtypes must be come to this path for NumPy 1.7.1 compat
if is_string_dtype(left) or is_string_dtype(right):
if not strict_nan:
# isna considers NaN and None to be equivalent.
return lib.array_equivalent_object(
ensure_object(left.ravel()), ensure_object(right.ravel()))
for left_value, right_value in zip(left, right):
if left_value is NaT and right_value is not NaT:
return False
elif isinstance(left_value, float) and np.isnan(left_value):
if (not isinstance(right_value, float) or
not np.isnan(right_value)):
return False
else:
if left_value != right_value:
return False
return True
# NaNs can occur in float and complex arrays.
if is_float_dtype(left) or is_complex_dtype(left):
# empty
if not (np.prod(left.shape) and np.prod(right.shape)):
return True
return ((left == right) | (isna(left) & isna(right))).all()
# numpy will will not allow this type of datetimelike vs integer comparison
elif is_datetimelike_v_numeric(left, right):
return False
# M8/m8
elif needs_i8_conversion(left) and needs_i8_conversion(right):
if not is_dtype_equal(left.dtype, right.dtype):
return False
left = left.view('i8')
right = right.view('i8')
# if we have structured dtypes, compare first
if (left.dtype.type is np.void or
right.dtype.type is np.void):
if left.dtype != right.dtype:
return False
return np.array_equal(left, right) | [
"True",
"if",
"two",
"arrays",
"left",
"and",
"right",
"have",
"equal",
"non",
"-",
"NaN",
"elements",
"and",
"NaNs",
"in",
"corresponding",
"locations",
".",
"False",
"otherwise",
".",
"It",
"is",
"assumed",
"that",
"left",
"and",
"right",
"are",
"NumPy",
"arrays",
"of",
"the",
"same",
"dtype",
".",
"The",
"behavior",
"of",
"this",
"function",
"(",
"particularly",
"with",
"respect",
"to",
"NaNs",
")",
"is",
"not",
"defined",
"if",
"the",
"dtypes",
"are",
"different",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L361-L446 | [
"def",
"array_equivalent",
"(",
"left",
",",
"right",
",",
"strict_nan",
"=",
"False",
")",
":",
"left",
",",
"right",
"=",
"np",
".",
"asarray",
"(",
"left",
")",
",",
"np",
".",
"asarray",
"(",
"right",
")",
"# shape compat",
"if",
"left",
".",
"shape",
"!=",
"right",
".",
"shape",
":",
"return",
"False",
"# Object arrays can contain None, NaN and NaT.",
"# string dtypes must be come to this path for NumPy 1.7.1 compat",
"if",
"is_string_dtype",
"(",
"left",
")",
"or",
"is_string_dtype",
"(",
"right",
")",
":",
"if",
"not",
"strict_nan",
":",
"# isna considers NaN and None to be equivalent.",
"return",
"lib",
".",
"array_equivalent_object",
"(",
"ensure_object",
"(",
"left",
".",
"ravel",
"(",
")",
")",
",",
"ensure_object",
"(",
"right",
".",
"ravel",
"(",
")",
")",
")",
"for",
"left_value",
",",
"right_value",
"in",
"zip",
"(",
"left",
",",
"right",
")",
":",
"if",
"left_value",
"is",
"NaT",
"and",
"right_value",
"is",
"not",
"NaT",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"left_value",
",",
"float",
")",
"and",
"np",
".",
"isnan",
"(",
"left_value",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"right_value",
",",
"float",
")",
"or",
"not",
"np",
".",
"isnan",
"(",
"right_value",
")",
")",
":",
"return",
"False",
"else",
":",
"if",
"left_value",
"!=",
"right_value",
":",
"return",
"False",
"return",
"True",
"# NaNs can occur in float and complex arrays.",
"if",
"is_float_dtype",
"(",
"left",
")",
"or",
"is_complex_dtype",
"(",
"left",
")",
":",
"# empty",
"if",
"not",
"(",
"np",
".",
"prod",
"(",
"left",
".",
"shape",
")",
"and",
"np",
".",
"prod",
"(",
"right",
".",
"shape",
")",
")",
":",
"return",
"True",
"return",
"(",
"(",
"left",
"==",
"right",
")",
"|",
"(",
"isna",
"(",
"left",
")",
"&",
"isna",
"(",
"right",
")",
")",
")",
".",
"all",
"(",
")",
"# numpy will will not allow this type of datetimelike vs integer comparison",
"elif",
"is_datetimelike_v_numeric",
"(",
"left",
",",
"right",
")",
":",
"return",
"False",
"# M8/m8",
"elif",
"needs_i8_conversion",
"(",
"left",
")",
"and",
"needs_i8_conversion",
"(",
"right",
")",
":",
"if",
"not",
"is_dtype_equal",
"(",
"left",
".",
"dtype",
",",
"right",
".",
"dtype",
")",
":",
"return",
"False",
"left",
"=",
"left",
".",
"view",
"(",
"'i8'",
")",
"right",
"=",
"right",
".",
"view",
"(",
"'i8'",
")",
"# if we have structured dtypes, compare first",
"if",
"(",
"left",
".",
"dtype",
".",
"type",
"is",
"np",
".",
"void",
"or",
"right",
".",
"dtype",
".",
"type",
"is",
"np",
".",
"void",
")",
":",
"if",
"left",
".",
"dtype",
"!=",
"right",
".",
"dtype",
":",
"return",
"False",
"return",
"np",
".",
"array_equal",
"(",
"left",
",",
"right",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _infer_fill_value | infer the fill value for the nan/NaT from the provided
scalar/ndarray/list-like if we are a NaT, return the correct dtyped
element to provide proper block construction | pandas/core/dtypes/missing.py | def _infer_fill_value(val):
"""
infer the fill value for the nan/NaT from the provided
scalar/ndarray/list-like if we are a NaT, return the correct dtyped
element to provide proper block construction
"""
if not is_list_like(val):
val = [val]
val = np.array(val, copy=False)
if is_datetimelike(val):
return np.array('NaT', dtype=val.dtype)
elif is_object_dtype(val.dtype):
dtype = lib.infer_dtype(ensure_object(val), skipna=False)
if dtype in ['datetime', 'datetime64']:
return np.array('NaT', dtype=_NS_DTYPE)
elif dtype in ['timedelta', 'timedelta64']:
return np.array('NaT', dtype=_TD_DTYPE)
return np.nan | def _infer_fill_value(val):
"""
infer the fill value for the nan/NaT from the provided
scalar/ndarray/list-like if we are a NaT, return the correct dtyped
element to provide proper block construction
"""
if not is_list_like(val):
val = [val]
val = np.array(val, copy=False)
if is_datetimelike(val):
return np.array('NaT', dtype=val.dtype)
elif is_object_dtype(val.dtype):
dtype = lib.infer_dtype(ensure_object(val), skipna=False)
if dtype in ['datetime', 'datetime64']:
return np.array('NaT', dtype=_NS_DTYPE)
elif dtype in ['timedelta', 'timedelta64']:
return np.array('NaT', dtype=_TD_DTYPE)
return np.nan | [
"infer",
"the",
"fill",
"value",
"for",
"the",
"nan",
"/",
"NaT",
"from",
"the",
"provided",
"scalar",
"/",
"ndarray",
"/",
"list",
"-",
"like",
"if",
"we",
"are",
"a",
"NaT",
"return",
"the",
"correct",
"dtyped",
"element",
"to",
"provide",
"proper",
"block",
"construction"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L449-L467 | [
"def",
"_infer_fill_value",
"(",
"val",
")",
":",
"if",
"not",
"is_list_like",
"(",
"val",
")",
":",
"val",
"=",
"[",
"val",
"]",
"val",
"=",
"np",
".",
"array",
"(",
"val",
",",
"copy",
"=",
"False",
")",
"if",
"is_datetimelike",
"(",
"val",
")",
":",
"return",
"np",
".",
"array",
"(",
"'NaT'",
",",
"dtype",
"=",
"val",
".",
"dtype",
")",
"elif",
"is_object_dtype",
"(",
"val",
".",
"dtype",
")",
":",
"dtype",
"=",
"lib",
".",
"infer_dtype",
"(",
"ensure_object",
"(",
"val",
")",
",",
"skipna",
"=",
"False",
")",
"if",
"dtype",
"in",
"[",
"'datetime'",
",",
"'datetime64'",
"]",
":",
"return",
"np",
".",
"array",
"(",
"'NaT'",
",",
"dtype",
"=",
"_NS_DTYPE",
")",
"elif",
"dtype",
"in",
"[",
"'timedelta'",
",",
"'timedelta64'",
"]",
":",
"return",
"np",
".",
"array",
"(",
"'NaT'",
",",
"dtype",
"=",
"_TD_DTYPE",
")",
"return",
"np",
".",
"nan"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _maybe_fill | if we have a compatible fill_value and arr dtype, then fill | pandas/core/dtypes/missing.py | def _maybe_fill(arr, fill_value=np.nan):
"""
if we have a compatible fill_value and arr dtype, then fill
"""
if _isna_compat(arr, fill_value):
arr.fill(fill_value)
return arr | def _maybe_fill(arr, fill_value=np.nan):
"""
if we have a compatible fill_value and arr dtype, then fill
"""
if _isna_compat(arr, fill_value):
arr.fill(fill_value)
return arr | [
"if",
"we",
"have",
"a",
"compatible",
"fill_value",
"and",
"arr",
"dtype",
"then",
"fill"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L470-L476 | [
"def",
"_maybe_fill",
"(",
"arr",
",",
"fill_value",
"=",
"np",
".",
"nan",
")",
":",
"if",
"_isna_compat",
"(",
"arr",
",",
"fill_value",
")",
":",
"arr",
".",
"fill",
"(",
"fill_value",
")",
"return",
"arr"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | na_value_for_dtype | Return a dtype compat na value
Parameters
----------
dtype : string / dtype
compat : boolean, default True
Returns
-------
np.dtype or a pandas dtype
Examples
--------
>>> na_value_for_dtype(np.dtype('int64'))
0
>>> na_value_for_dtype(np.dtype('int64'), compat=False)
nan
>>> na_value_for_dtype(np.dtype('float64'))
nan
>>> na_value_for_dtype(np.dtype('bool'))
False
>>> na_value_for_dtype(np.dtype('datetime64[ns]'))
NaT | pandas/core/dtypes/missing.py | def na_value_for_dtype(dtype, compat=True):
"""
Return a dtype compat na value
Parameters
----------
dtype : string / dtype
compat : boolean, default True
Returns
-------
np.dtype or a pandas dtype
Examples
--------
>>> na_value_for_dtype(np.dtype('int64'))
0
>>> na_value_for_dtype(np.dtype('int64'), compat=False)
nan
>>> na_value_for_dtype(np.dtype('float64'))
nan
>>> na_value_for_dtype(np.dtype('bool'))
False
>>> na_value_for_dtype(np.dtype('datetime64[ns]'))
NaT
"""
dtype = pandas_dtype(dtype)
if is_extension_array_dtype(dtype):
return dtype.na_value
if (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or
is_timedelta64_dtype(dtype) or is_period_dtype(dtype)):
return NaT
elif is_float_dtype(dtype):
return np.nan
elif is_integer_dtype(dtype):
if compat:
return 0
return np.nan
elif is_bool_dtype(dtype):
return False
return np.nan | def na_value_for_dtype(dtype, compat=True):
"""
Return a dtype compat na value
Parameters
----------
dtype : string / dtype
compat : boolean, default True
Returns
-------
np.dtype or a pandas dtype
Examples
--------
>>> na_value_for_dtype(np.dtype('int64'))
0
>>> na_value_for_dtype(np.dtype('int64'), compat=False)
nan
>>> na_value_for_dtype(np.dtype('float64'))
nan
>>> na_value_for_dtype(np.dtype('bool'))
False
>>> na_value_for_dtype(np.dtype('datetime64[ns]'))
NaT
"""
dtype = pandas_dtype(dtype)
if is_extension_array_dtype(dtype):
return dtype.na_value
if (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or
is_timedelta64_dtype(dtype) or is_period_dtype(dtype)):
return NaT
elif is_float_dtype(dtype):
return np.nan
elif is_integer_dtype(dtype):
if compat:
return 0
return np.nan
elif is_bool_dtype(dtype):
return False
return np.nan | [
"Return",
"a",
"dtype",
"compat",
"na",
"value"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L479-L520 | [
"def",
"na_value_for_dtype",
"(",
"dtype",
",",
"compat",
"=",
"True",
")",
":",
"dtype",
"=",
"pandas_dtype",
"(",
"dtype",
")",
"if",
"is_extension_array_dtype",
"(",
"dtype",
")",
":",
"return",
"dtype",
".",
"na_value",
"if",
"(",
"is_datetime64_dtype",
"(",
"dtype",
")",
"or",
"is_datetime64tz_dtype",
"(",
"dtype",
")",
"or",
"is_timedelta64_dtype",
"(",
"dtype",
")",
"or",
"is_period_dtype",
"(",
"dtype",
")",
")",
":",
"return",
"NaT",
"elif",
"is_float_dtype",
"(",
"dtype",
")",
":",
"return",
"np",
".",
"nan",
"elif",
"is_integer_dtype",
"(",
"dtype",
")",
":",
"if",
"compat",
":",
"return",
"0",
"return",
"np",
".",
"nan",
"elif",
"is_bool_dtype",
"(",
"dtype",
")",
":",
"return",
"False",
"return",
"np",
".",
"nan"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | remove_na_arraylike | Return array-like containing only true/non-NaN values, possibly empty. | pandas/core/dtypes/missing.py | def remove_na_arraylike(arr):
"""
Return array-like containing only true/non-NaN values, possibly empty.
"""
if is_extension_array_dtype(arr):
return arr[notna(arr)]
else:
return arr[notna(lib.values_from_object(arr))] | def remove_na_arraylike(arr):
"""
Return array-like containing only true/non-NaN values, possibly empty.
"""
if is_extension_array_dtype(arr):
return arr[notna(arr)]
else:
return arr[notna(lib.values_from_object(arr))] | [
"Return",
"array",
"-",
"like",
"containing",
"only",
"true",
"/",
"non",
"-",
"NaN",
"values",
"possibly",
"empty",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L523-L530 | [
"def",
"remove_na_arraylike",
"(",
"arr",
")",
":",
"if",
"is_extension_array_dtype",
"(",
"arr",
")",
":",
"return",
"arr",
"[",
"notna",
"(",
"arr",
")",
"]",
"else",
":",
"return",
"arr",
"[",
"notna",
"(",
"lib",
".",
"values_from_object",
"(",
"arr",
")",
")",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | table | Helper function to convert DataFrame and Series to matplotlib.table
Parameters
----------
ax : Matplotlib axes object
data : DataFrame or Series
data for table contents
kwargs : keywords, optional
keyword arguments which passed to matplotlib.table.table.
If `rowLabels` or `colLabels` is not specified, data index or column
name will be used.
Returns
-------
matplotlib table object | pandas/plotting/_tools.py | def table(ax, data, rowLabels=None, colLabels=None, **kwargs):
"""
Helper function to convert DataFrame and Series to matplotlib.table
Parameters
----------
ax : Matplotlib axes object
data : DataFrame or Series
data for table contents
kwargs : keywords, optional
keyword arguments which passed to matplotlib.table.table.
If `rowLabels` or `colLabels` is not specified, data index or column
name will be used.
Returns
-------
matplotlib table object
"""
if isinstance(data, ABCSeries):
data = data.to_frame()
elif isinstance(data, ABCDataFrame):
pass
else:
raise ValueError('Input data must be DataFrame or Series')
if rowLabels is None:
rowLabels = data.index
if colLabels is None:
colLabels = data.columns
cellText = data.values
import matplotlib.table
table = matplotlib.table.table(ax, cellText=cellText,
rowLabels=rowLabels,
colLabels=colLabels, **kwargs)
return table | def table(ax, data, rowLabels=None, colLabels=None, **kwargs):
"""
Helper function to convert DataFrame and Series to matplotlib.table
Parameters
----------
ax : Matplotlib axes object
data : DataFrame or Series
data for table contents
kwargs : keywords, optional
keyword arguments which passed to matplotlib.table.table.
If `rowLabels` or `colLabels` is not specified, data index or column
name will be used.
Returns
-------
matplotlib table object
"""
if isinstance(data, ABCSeries):
data = data.to_frame()
elif isinstance(data, ABCDataFrame):
pass
else:
raise ValueError('Input data must be DataFrame or Series')
if rowLabels is None:
rowLabels = data.index
if colLabels is None:
colLabels = data.columns
cellText = data.values
import matplotlib.table
table = matplotlib.table.table(ax, cellText=cellText,
rowLabels=rowLabels,
colLabels=colLabels, **kwargs)
return table | [
"Helper",
"function",
"to",
"convert",
"DataFrame",
"and",
"Series",
"to",
"matplotlib",
".",
"table"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_tools.py#L23-L60 | [
"def",
"table",
"(",
"ax",
",",
"data",
",",
"rowLabels",
"=",
"None",
",",
"colLabels",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"ABCSeries",
")",
":",
"data",
"=",
"data",
".",
"to_frame",
"(",
")",
"elif",
"isinstance",
"(",
"data",
",",
"ABCDataFrame",
")",
":",
"pass",
"else",
":",
"raise",
"ValueError",
"(",
"'Input data must be DataFrame or Series'",
")",
"if",
"rowLabels",
"is",
"None",
":",
"rowLabels",
"=",
"data",
".",
"index",
"if",
"colLabels",
"is",
"None",
":",
"colLabels",
"=",
"data",
".",
"columns",
"cellText",
"=",
"data",
".",
"values",
"import",
"matplotlib",
".",
"table",
"table",
"=",
"matplotlib",
".",
"table",
".",
"table",
"(",
"ax",
",",
"cellText",
"=",
"cellText",
",",
"rowLabels",
"=",
"rowLabels",
",",
"colLabels",
"=",
"colLabels",
",",
"*",
"*",
"kwargs",
")",
"return",
"table"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _subplots | Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Keyword arguments:
naxes : int
Number of required axes. Exceeded axes are set invisible. Default is
nrows * ncols.
sharex : bool
If True, the X axis will be shared amongst all subplots.
sharey : bool
If True, the Y axis will be shared amongst all subplots.
squeeze : bool
If True, extra dimensions are squeezed out from the returned axis object:
- if only one subplot is constructed (nrows=ncols=1), the resulting
single Axis object is returned as a scalar.
- for Nx1 or 1xN subplots, the returned object is a 1-d numpy object
array of Axis objects are returned as numpy 1-d arrays.
- for NxM subplots with N>1 and M>1 are returned as a 2d array.
If False, no squeezing is done: the returned axis object is always
a 2-d array containing Axis instances, even if it ends up being 1x1.
subplot_kw : dict
Dict with keywords passed to the add_subplot() call used to create each
subplots.
ax : Matplotlib axis object, optional
layout : tuple
Number of rows and columns of the subplot grid.
If not specified, calculated from naxes and layout_type
layout_type : {'box', 'horziontal', 'vertical'}, default 'box'
Specify how to layout the subplot grid.
fig_kw : Other keyword arguments to be passed to the figure() call.
Note that all keywords not recognized above will be
automatically included here.
Returns:
fig, ax : tuple
- fig is the Matplotlib Figure object
- ax can be either a single axis object or an array of axis objects if
more than one subplot was created. The dimensions of the resulting array
can be controlled with the squeeze keyword, see above.
**Examples:**
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Two subplots, unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Four polar axes
plt.subplots(2, 2, subplot_kw=dict(polar=True)) | pandas/plotting/_tools.py | def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, ax=None, layout=None, layout_type='box',
**fig_kw):
"""Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Keyword arguments:
naxes : int
Number of required axes. Exceeded axes are set invisible. Default is
nrows * ncols.
sharex : bool
If True, the X axis will be shared amongst all subplots.
sharey : bool
If True, the Y axis will be shared amongst all subplots.
squeeze : bool
If True, extra dimensions are squeezed out from the returned axis object:
- if only one subplot is constructed (nrows=ncols=1), the resulting
single Axis object is returned as a scalar.
- for Nx1 or 1xN subplots, the returned object is a 1-d numpy object
array of Axis objects are returned as numpy 1-d arrays.
- for NxM subplots with N>1 and M>1 are returned as a 2d array.
If False, no squeezing is done: the returned axis object is always
a 2-d array containing Axis instances, even if it ends up being 1x1.
subplot_kw : dict
Dict with keywords passed to the add_subplot() call used to create each
subplots.
ax : Matplotlib axis object, optional
layout : tuple
Number of rows and columns of the subplot grid.
If not specified, calculated from naxes and layout_type
layout_type : {'box', 'horziontal', 'vertical'}, default 'box'
Specify how to layout the subplot grid.
fig_kw : Other keyword arguments to be passed to the figure() call.
Note that all keywords not recognized above will be
automatically included here.
Returns:
fig, ax : tuple
- fig is the Matplotlib Figure object
- ax can be either a single axis object or an array of axis objects if
more than one subplot was created. The dimensions of the resulting array
can be controlled with the squeeze keyword, see above.
**Examples:**
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Two subplots, unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Four polar axes
plt.subplots(2, 2, subplot_kw=dict(polar=True))
"""
import matplotlib.pyplot as plt
if subplot_kw is None:
subplot_kw = {}
if ax is None:
fig = plt.figure(**fig_kw)
else:
if is_list_like(ax):
ax = _flatten(ax)
if layout is not None:
warnings.warn("When passing multiple axes, layout keyword is "
"ignored", UserWarning)
if sharex or sharey:
warnings.warn("When passing multiple axes, sharex and sharey "
"are ignored. These settings must be specified "
"when creating axes", UserWarning,
stacklevel=4)
if len(ax) == naxes:
fig = ax[0].get_figure()
return fig, ax
else:
raise ValueError("The number of passed axes must be {0}, the "
"same as the output plot".format(naxes))
fig = ax.get_figure()
# if ax is passed and a number of subplots is 1, return ax as it is
if naxes == 1:
if squeeze:
return fig, ax
else:
return fig, _flatten(ax)
else:
warnings.warn("To output multiple subplots, the figure containing "
"the passed axes is being cleared", UserWarning,
stacklevel=4)
fig.clear()
nrows, ncols = _get_layout(naxes, layout=layout, layout_type=layout_type)
nplots = nrows * ncols
# Create empty object array to hold all axes. It's easiest to make it 1-d
# so we can just append subplots upon creation, and then
axarr = np.empty(nplots, dtype=object)
# Create first subplot separately, so we can share it if requested
ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)
if sharex:
subplot_kw['sharex'] = ax0
if sharey:
subplot_kw['sharey'] = ax0
axarr[0] = ax0
# Note off-by-one counting because add_subplot uses the MATLAB 1-based
# convention.
for i in range(1, nplots):
kwds = subplot_kw.copy()
# Set sharex and sharey to None for blank/dummy axes, these can
# interfere with proper axis limits on the visible axes if
# they share axes e.g. issue #7528
if i >= naxes:
kwds['sharex'] = None
kwds['sharey'] = None
ax = fig.add_subplot(nrows, ncols, i + 1, **kwds)
axarr[i] = ax
if naxes != nplots:
for ax in axarr[naxes:]:
ax.set_visible(False)
_handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
if squeeze:
# Reshape the array to have the final desired dimension (nrow,ncol),
# though discarding unneeded dimensions that equal 1. If we only have
# one subplot, just return it instead of a 1-element array.
if nplots == 1:
axes = axarr[0]
else:
axes = axarr.reshape(nrows, ncols).squeeze()
else:
# returned axis array will be always 2-d, even if nrows=ncols=1
axes = axarr.reshape(nrows, ncols)
return fig, axes | def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, ax=None, layout=None, layout_type='box',
**fig_kw):
"""Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Keyword arguments:
naxes : int
Number of required axes. Exceeded axes are set invisible. Default is
nrows * ncols.
sharex : bool
If True, the X axis will be shared amongst all subplots.
sharey : bool
If True, the Y axis will be shared amongst all subplots.
squeeze : bool
If True, extra dimensions are squeezed out from the returned axis object:
- if only one subplot is constructed (nrows=ncols=1), the resulting
single Axis object is returned as a scalar.
- for Nx1 or 1xN subplots, the returned object is a 1-d numpy object
array of Axis objects are returned as numpy 1-d arrays.
- for NxM subplots with N>1 and M>1 are returned as a 2d array.
If False, no squeezing is done: the returned axis object is always
a 2-d array containing Axis instances, even if it ends up being 1x1.
subplot_kw : dict
Dict with keywords passed to the add_subplot() call used to create each
subplots.
ax : Matplotlib axis object, optional
layout : tuple
Number of rows and columns of the subplot grid.
If not specified, calculated from naxes and layout_type
layout_type : {'box', 'horziontal', 'vertical'}, default 'box'
Specify how to layout the subplot grid.
fig_kw : Other keyword arguments to be passed to the figure() call.
Note that all keywords not recognized above will be
automatically included here.
Returns:
fig, ax : tuple
- fig is the Matplotlib Figure object
- ax can be either a single axis object or an array of axis objects if
more than one subplot was created. The dimensions of the resulting array
can be controlled with the squeeze keyword, see above.
**Examples:**
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Two subplots, unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Four polar axes
plt.subplots(2, 2, subplot_kw=dict(polar=True))
"""
import matplotlib.pyplot as plt
if subplot_kw is None:
subplot_kw = {}
if ax is None:
fig = plt.figure(**fig_kw)
else:
if is_list_like(ax):
ax = _flatten(ax)
if layout is not None:
warnings.warn("When passing multiple axes, layout keyword is "
"ignored", UserWarning)
if sharex or sharey:
warnings.warn("When passing multiple axes, sharex and sharey "
"are ignored. These settings must be specified "
"when creating axes", UserWarning,
stacklevel=4)
if len(ax) == naxes:
fig = ax[0].get_figure()
return fig, ax
else:
raise ValueError("The number of passed axes must be {0}, the "
"same as the output plot".format(naxes))
fig = ax.get_figure()
# if ax is passed and a number of subplots is 1, return ax as it is
if naxes == 1:
if squeeze:
return fig, ax
else:
return fig, _flatten(ax)
else:
warnings.warn("To output multiple subplots, the figure containing "
"the passed axes is being cleared", UserWarning,
stacklevel=4)
fig.clear()
nrows, ncols = _get_layout(naxes, layout=layout, layout_type=layout_type)
nplots = nrows * ncols
# Create empty object array to hold all axes. It's easiest to make it 1-d
# so we can just append subplots upon creation, and then
axarr = np.empty(nplots, dtype=object)
# Create first subplot separately, so we can share it if requested
ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)
if sharex:
subplot_kw['sharex'] = ax0
if sharey:
subplot_kw['sharey'] = ax0
axarr[0] = ax0
# Note off-by-one counting because add_subplot uses the MATLAB 1-based
# convention.
for i in range(1, nplots):
kwds = subplot_kw.copy()
# Set sharex and sharey to None for blank/dummy axes, these can
# interfere with proper axis limits on the visible axes if
# they share axes e.g. issue #7528
if i >= naxes:
kwds['sharex'] = None
kwds['sharey'] = None
ax = fig.add_subplot(nrows, ncols, i + 1, **kwds)
axarr[i] = ax
if naxes != nplots:
for ax in axarr[naxes:]:
ax.set_visible(False)
_handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
if squeeze:
# Reshape the array to have the final desired dimension (nrow,ncol),
# though discarding unneeded dimensions that equal 1. If we only have
# one subplot, just return it instead of a 1-element array.
if nplots == 1:
axes = axarr[0]
else:
axes = axarr.reshape(nrows, ncols).squeeze()
else:
# returned axis array will be always 2-d, even if nrows=ncols=1
axes = axarr.reshape(nrows, ncols)
return fig, axes | [
"Create",
"a",
"figure",
"with",
"a",
"set",
"of",
"subplots",
"already",
"made",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_tools.py#L110-L271 | [
"def",
"_subplots",
"(",
"naxes",
"=",
"None",
",",
"sharex",
"=",
"False",
",",
"sharey",
"=",
"False",
",",
"squeeze",
"=",
"True",
",",
"subplot_kw",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"layout",
"=",
"None",
",",
"layout_type",
"=",
"'box'",
",",
"*",
"*",
"fig_kw",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"if",
"subplot_kw",
"is",
"None",
":",
"subplot_kw",
"=",
"{",
"}",
"if",
"ax",
"is",
"None",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"*",
"*",
"fig_kw",
")",
"else",
":",
"if",
"is_list_like",
"(",
"ax",
")",
":",
"ax",
"=",
"_flatten",
"(",
"ax",
")",
"if",
"layout",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"When passing multiple axes, layout keyword is \"",
"\"ignored\"",
",",
"UserWarning",
")",
"if",
"sharex",
"or",
"sharey",
":",
"warnings",
".",
"warn",
"(",
"\"When passing multiple axes, sharex and sharey \"",
"\"are ignored. These settings must be specified \"",
"\"when creating axes\"",
",",
"UserWarning",
",",
"stacklevel",
"=",
"4",
")",
"if",
"len",
"(",
"ax",
")",
"==",
"naxes",
":",
"fig",
"=",
"ax",
"[",
"0",
"]",
".",
"get_figure",
"(",
")",
"return",
"fig",
",",
"ax",
"else",
":",
"raise",
"ValueError",
"(",
"\"The number of passed axes must be {0}, the \"",
"\"same as the output plot\"",
".",
"format",
"(",
"naxes",
")",
")",
"fig",
"=",
"ax",
".",
"get_figure",
"(",
")",
"# if ax is passed and a number of subplots is 1, return ax as it is",
"if",
"naxes",
"==",
"1",
":",
"if",
"squeeze",
":",
"return",
"fig",
",",
"ax",
"else",
":",
"return",
"fig",
",",
"_flatten",
"(",
"ax",
")",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"To output multiple subplots, the figure containing \"",
"\"the passed axes is being cleared\"",
",",
"UserWarning",
",",
"stacklevel",
"=",
"4",
")",
"fig",
".",
"clear",
"(",
")",
"nrows",
",",
"ncols",
"=",
"_get_layout",
"(",
"naxes",
",",
"layout",
"=",
"layout",
",",
"layout_type",
"=",
"layout_type",
")",
"nplots",
"=",
"nrows",
"*",
"ncols",
"# Create empty object array to hold all axes. It's easiest to make it 1-d",
"# so we can just append subplots upon creation, and then",
"axarr",
"=",
"np",
".",
"empty",
"(",
"nplots",
",",
"dtype",
"=",
"object",
")",
"# Create first subplot separately, so we can share it if requested",
"ax0",
"=",
"fig",
".",
"add_subplot",
"(",
"nrows",
",",
"ncols",
",",
"1",
",",
"*",
"*",
"subplot_kw",
")",
"if",
"sharex",
":",
"subplot_kw",
"[",
"'sharex'",
"]",
"=",
"ax0",
"if",
"sharey",
":",
"subplot_kw",
"[",
"'sharey'",
"]",
"=",
"ax0",
"axarr",
"[",
"0",
"]",
"=",
"ax0",
"# Note off-by-one counting because add_subplot uses the MATLAB 1-based",
"# convention.",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"nplots",
")",
":",
"kwds",
"=",
"subplot_kw",
".",
"copy",
"(",
")",
"# Set sharex and sharey to None for blank/dummy axes, these can",
"# interfere with proper axis limits on the visible axes if",
"# they share axes e.g. issue #7528",
"if",
"i",
">=",
"naxes",
":",
"kwds",
"[",
"'sharex'",
"]",
"=",
"None",
"kwds",
"[",
"'sharey'",
"]",
"=",
"None",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"nrows",
",",
"ncols",
",",
"i",
"+",
"1",
",",
"*",
"*",
"kwds",
")",
"axarr",
"[",
"i",
"]",
"=",
"ax",
"if",
"naxes",
"!=",
"nplots",
":",
"for",
"ax",
"in",
"axarr",
"[",
"naxes",
":",
"]",
":",
"ax",
".",
"set_visible",
"(",
"False",
")",
"_handle_shared_axes",
"(",
"axarr",
",",
"nplots",
",",
"naxes",
",",
"nrows",
",",
"ncols",
",",
"sharex",
",",
"sharey",
")",
"if",
"squeeze",
":",
"# Reshape the array to have the final desired dimension (nrow,ncol),",
"# though discarding unneeded dimensions that equal 1. If we only have",
"# one subplot, just return it instead of a 1-element array.",
"if",
"nplots",
"==",
"1",
":",
"axes",
"=",
"axarr",
"[",
"0",
"]",
"else",
":",
"axes",
"=",
"axarr",
".",
"reshape",
"(",
"nrows",
",",
"ncols",
")",
".",
"squeeze",
"(",
")",
"else",
":",
"# returned axis array will be always 2-d, even if nrows=ncols=1",
"axes",
"=",
"axarr",
".",
"reshape",
"(",
"nrows",
",",
"ncols",
")",
"return",
"fig",
",",
"axes"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | maybe_cythonize | Render tempita templates before calling cythonize | setup.py | def maybe_cythonize(extensions, *args, **kwargs):
"""
Render tempita templates before calling cythonize
"""
if len(sys.argv) > 1 and 'clean' in sys.argv:
# Avoid running cythonize on `python setup.py clean`
# See https://github.com/cython/cython/issues/1495
return extensions
if not cython:
# Avoid trying to look up numpy when installing from sdist
# https://github.com/pandas-dev/pandas/issues/25193
# TODO: See if this can be removed after pyproject.toml added.
return extensions
numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')
# TODO: Is this really necessary here?
for ext in extensions:
if (hasattr(ext, 'include_dirs') and
numpy_incl not in ext.include_dirs):
ext.include_dirs.append(numpy_incl)
build_ext.render_templates(_pxifiles)
return cythonize(extensions, *args, **kwargs) | def maybe_cythonize(extensions, *args, **kwargs):
"""
Render tempita templates before calling cythonize
"""
if len(sys.argv) > 1 and 'clean' in sys.argv:
# Avoid running cythonize on `python setup.py clean`
# See https://github.com/cython/cython/issues/1495
return extensions
if not cython:
# Avoid trying to look up numpy when installing from sdist
# https://github.com/pandas-dev/pandas/issues/25193
# TODO: See if this can be removed after pyproject.toml added.
return extensions
numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')
# TODO: Is this really necessary here?
for ext in extensions:
if (hasattr(ext, 'include_dirs') and
numpy_incl not in ext.include_dirs):
ext.include_dirs.append(numpy_incl)
build_ext.render_templates(_pxifiles)
return cythonize(extensions, *args, **kwargs) | [
"Render",
"tempita",
"templates",
"before",
"calling",
"cythonize"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/setup.py#L490-L512 | [
"def",
"maybe_cythonize",
"(",
"extensions",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
"and",
"'clean'",
"in",
"sys",
".",
"argv",
":",
"# Avoid running cythonize on `python setup.py clean`",
"# See https://github.com/cython/cython/issues/1495",
"return",
"extensions",
"if",
"not",
"cython",
":",
"# Avoid trying to look up numpy when installing from sdist",
"# https://github.com/pandas-dev/pandas/issues/25193",
"# TODO: See if this can be removed after pyproject.toml added.",
"return",
"extensions",
"numpy_incl",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"'numpy'",
",",
"'core/include'",
")",
"# TODO: Is this really necessary here?",
"for",
"ext",
"in",
"extensions",
":",
"if",
"(",
"hasattr",
"(",
"ext",
",",
"'include_dirs'",
")",
"and",
"numpy_incl",
"not",
"in",
"ext",
".",
"include_dirs",
")",
":",
"ext",
".",
"include_dirs",
".",
"append",
"(",
"numpy_incl",
")",
"build_ext",
".",
"render_templates",
"(",
"_pxifiles",
")",
"return",
"cythonize",
"(",
"extensions",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrameGroupBy._transform_fast | Fast transform path for aggregations | pandas/core/groupby/generic.py | def _transform_fast(self, result, obj, func_nm):
"""
Fast transform path for aggregations
"""
# if there were groups with no observations (Categorical only?)
# try casting data to original dtype
cast = self._transform_should_cast(func_nm)
# for each col, reshape to to size of original frame
# by take operation
ids, _, ngroup = self.grouper.group_info
output = []
for i, _ in enumerate(result.columns):
res = algorithms.take_1d(result.iloc[:, i].values, ids)
if cast:
res = self._try_cast(res, obj.iloc[:, i])
output.append(res)
return DataFrame._from_arrays(output, columns=result.columns,
index=obj.index) | def _transform_fast(self, result, obj, func_nm):
"""
Fast transform path for aggregations
"""
# if there were groups with no observations (Categorical only?)
# try casting data to original dtype
cast = self._transform_should_cast(func_nm)
# for each col, reshape to to size of original frame
# by take operation
ids, _, ngroup = self.grouper.group_info
output = []
for i, _ in enumerate(result.columns):
res = algorithms.take_1d(result.iloc[:, i].values, ids)
if cast:
res = self._try_cast(res, obj.iloc[:, i])
output.append(res)
return DataFrame._from_arrays(output, columns=result.columns,
index=obj.index) | [
"Fast",
"transform",
"path",
"for",
"aggregations"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L526-L545 | [
"def",
"_transform_fast",
"(",
"self",
",",
"result",
",",
"obj",
",",
"func_nm",
")",
":",
"# if there were groups with no observations (Categorical only?)",
"# try casting data to original dtype",
"cast",
"=",
"self",
".",
"_transform_should_cast",
"(",
"func_nm",
")",
"# for each col, reshape to to size of original frame",
"# by take operation",
"ids",
",",
"_",
",",
"ngroup",
"=",
"self",
".",
"grouper",
".",
"group_info",
"output",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"result",
".",
"columns",
")",
":",
"res",
"=",
"algorithms",
".",
"take_1d",
"(",
"result",
".",
"iloc",
"[",
":",
",",
"i",
"]",
".",
"values",
",",
"ids",
")",
"if",
"cast",
":",
"res",
"=",
"self",
".",
"_try_cast",
"(",
"res",
",",
"obj",
".",
"iloc",
"[",
":",
",",
"i",
"]",
")",
"output",
".",
"append",
"(",
"res",
")",
"return",
"DataFrame",
".",
"_from_arrays",
"(",
"output",
",",
"columns",
"=",
"result",
".",
"columns",
",",
"index",
"=",
"obj",
".",
"index",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrameGroupBy.filter | Return a copy of a DataFrame excluding elements from groups that
do not satisfy the boolean criterion specified by func.
Parameters
----------
f : function
Function to apply to each subframe. Should return True or False.
dropna : Drop groups that do not pass the filter. True by default;
if False, groups that evaluate False are filled with NaNs.
Returns
-------
filtered : DataFrame
Notes
-----
Each subframe is endowed the attribute 'name' in case you need to know
which group you are working on.
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : [1, 2, 3, 4, 5, 6],
... 'C' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
>>> grouped.filter(lambda x: x['B'].mean() > 3.)
A B C
1 bar 2 5.0
3 bar 4 1.0
5 bar 6 9.0 | pandas/core/groupby/generic.py | def filter(self, func, dropna=True, *args, **kwargs): # noqa
"""
Return a copy of a DataFrame excluding elements from groups that
do not satisfy the boolean criterion specified by func.
Parameters
----------
f : function
Function to apply to each subframe. Should return True or False.
dropna : Drop groups that do not pass the filter. True by default;
if False, groups that evaluate False are filled with NaNs.
Returns
-------
filtered : DataFrame
Notes
-----
Each subframe is endowed the attribute 'name' in case you need to know
which group you are working on.
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : [1, 2, 3, 4, 5, 6],
... 'C' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
>>> grouped.filter(lambda x: x['B'].mean() > 3.)
A B C
1 bar 2 5.0
3 bar 4 1.0
5 bar 6 9.0
"""
indices = []
obj = self._selected_obj
gen = self.grouper.get_iterator(obj, axis=self.axis)
for name, group in gen:
object.__setattr__(group, 'name', name)
res = func(group, *args, **kwargs)
try:
res = res.squeeze()
except AttributeError: # allow e.g., scalars and frames to pass
pass
# interpret the result of the filter
if is_bool(res) or (is_scalar(res) and isna(res)):
if res and notna(res):
indices.append(self._get_index(name))
else:
# non scalars aren't allowed
raise TypeError("filter function returned a %s, "
"but expected a scalar bool" %
type(res).__name__)
return self._apply_filter(indices, dropna) | def filter(self, func, dropna=True, *args, **kwargs): # noqa
"""
Return a copy of a DataFrame excluding elements from groups that
do not satisfy the boolean criterion specified by func.
Parameters
----------
f : function
Function to apply to each subframe. Should return True or False.
dropna : Drop groups that do not pass the filter. True by default;
if False, groups that evaluate False are filled with NaNs.
Returns
-------
filtered : DataFrame
Notes
-----
Each subframe is endowed the attribute 'name' in case you need to know
which group you are working on.
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : [1, 2, 3, 4, 5, 6],
... 'C' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
>>> grouped.filter(lambda x: x['B'].mean() > 3.)
A B C
1 bar 2 5.0
3 bar 4 1.0
5 bar 6 9.0
"""
indices = []
obj = self._selected_obj
gen = self.grouper.get_iterator(obj, axis=self.axis)
for name, group in gen:
object.__setattr__(group, 'name', name)
res = func(group, *args, **kwargs)
try:
res = res.squeeze()
except AttributeError: # allow e.g., scalars and frames to pass
pass
# interpret the result of the filter
if is_bool(res) or (is_scalar(res) and isna(res)):
if res and notna(res):
indices.append(self._get_index(name))
else:
# non scalars aren't allowed
raise TypeError("filter function returned a %s, "
"but expected a scalar bool" %
type(res).__name__)
return self._apply_filter(indices, dropna) | [
"Return",
"a",
"copy",
"of",
"a",
"DataFrame",
"excluding",
"elements",
"from",
"groups",
"that",
"do",
"not",
"satisfy",
"the",
"boolean",
"criterion",
"specified",
"by",
"func",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L601-L661 | [
"def",
"filter",
"(",
"self",
",",
"func",
",",
"dropna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa",
"indices",
"=",
"[",
"]",
"obj",
"=",
"self",
".",
"_selected_obj",
"gen",
"=",
"self",
".",
"grouper",
".",
"get_iterator",
"(",
"obj",
",",
"axis",
"=",
"self",
".",
"axis",
")",
"for",
"name",
",",
"group",
"in",
"gen",
":",
"object",
".",
"__setattr__",
"(",
"group",
",",
"'name'",
",",
"name",
")",
"res",
"=",
"func",
"(",
"group",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"res",
"=",
"res",
".",
"squeeze",
"(",
")",
"except",
"AttributeError",
":",
"# allow e.g., scalars and frames to pass",
"pass",
"# interpret the result of the filter",
"if",
"is_bool",
"(",
"res",
")",
"or",
"(",
"is_scalar",
"(",
"res",
")",
"and",
"isna",
"(",
"res",
")",
")",
":",
"if",
"res",
"and",
"notna",
"(",
"res",
")",
":",
"indices",
".",
"append",
"(",
"self",
".",
"_get_index",
"(",
"name",
")",
")",
"else",
":",
"# non scalars aren't allowed",
"raise",
"TypeError",
"(",
"\"filter function returned a %s, \"",
"\"but expected a scalar bool\"",
"%",
"type",
"(",
"res",
")",
".",
"__name__",
")",
"return",
"self",
".",
"_apply_filter",
"(",
"indices",
",",
"dropna",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SeriesGroupBy._wrap_output | common agg/transform wrapping logic | pandas/core/groupby/generic.py | def _wrap_output(self, output, index, names=None):
""" common agg/transform wrapping logic """
output = output[self._selection_name]
if names is not None:
return DataFrame(output, index=index, columns=names)
else:
name = self._selection_name
if name is None:
name = self._selected_obj.name
return Series(output, index=index, name=name) | def _wrap_output(self, output, index, names=None):
""" common agg/transform wrapping logic """
output = output[self._selection_name]
if names is not None:
return DataFrame(output, index=index, columns=names)
else:
name = self._selection_name
if name is None:
name = self._selected_obj.name
return Series(output, index=index, name=name) | [
"common",
"agg",
"/",
"transform",
"wrapping",
"logic"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L825-L835 | [
"def",
"_wrap_output",
"(",
"self",
",",
"output",
",",
"index",
",",
"names",
"=",
"None",
")",
":",
"output",
"=",
"output",
"[",
"self",
".",
"_selection_name",
"]",
"if",
"names",
"is",
"not",
"None",
":",
"return",
"DataFrame",
"(",
"output",
",",
"index",
"=",
"index",
",",
"columns",
"=",
"names",
")",
"else",
":",
"name",
"=",
"self",
".",
"_selection_name",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"_selected_obj",
".",
"name",
"return",
"Series",
"(",
"output",
",",
"index",
"=",
"index",
",",
"name",
"=",
"name",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SeriesGroupBy._transform_fast | fast version of transform, only applicable to
builtin/cythonizable functions | pandas/core/groupby/generic.py | def _transform_fast(self, func, func_nm):
"""
fast version of transform, only applicable to
builtin/cythonizable functions
"""
if isinstance(func, str):
func = getattr(self, func)
ids, _, ngroup = self.grouper.group_info
cast = self._transform_should_cast(func_nm)
out = algorithms.take_1d(func()._values, ids)
if cast:
out = self._try_cast(out, self.obj)
return Series(out, index=self.obj.index, name=self.obj.name) | def _transform_fast(self, func, func_nm):
"""
fast version of transform, only applicable to
builtin/cythonizable functions
"""
if isinstance(func, str):
func = getattr(self, func)
ids, _, ngroup = self.grouper.group_info
cast = self._transform_should_cast(func_nm)
out = algorithms.take_1d(func()._values, ids)
if cast:
out = self._try_cast(out, self.obj)
return Series(out, index=self.obj.index, name=self.obj.name) | [
"fast",
"version",
"of",
"transform",
"only",
"applicable",
"to",
"builtin",
"/",
"cythonizable",
"functions"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L934-L947 | [
"def",
"_transform_fast",
"(",
"self",
",",
"func",
",",
"func_nm",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"str",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"func",
")",
"ids",
",",
"_",
",",
"ngroup",
"=",
"self",
".",
"grouper",
".",
"group_info",
"cast",
"=",
"self",
".",
"_transform_should_cast",
"(",
"func_nm",
")",
"out",
"=",
"algorithms",
".",
"take_1d",
"(",
"func",
"(",
")",
".",
"_values",
",",
"ids",
")",
"if",
"cast",
":",
"out",
"=",
"self",
".",
"_try_cast",
"(",
"out",
",",
"self",
".",
"obj",
")",
"return",
"Series",
"(",
"out",
",",
"index",
"=",
"self",
".",
"obj",
".",
"index",
",",
"name",
"=",
"self",
".",
"obj",
".",
"name",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SeriesGroupBy.filter | Return a copy of a Series excluding elements from groups that
do not satisfy the boolean criterion specified by func.
Parameters
----------
func : function
To apply to each group. Should return True or False.
dropna : Drop groups that do not pass the filter. True by default;
if False, groups that evaluate False are filled with NaNs.
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : [1, 2, 3, 4, 5, 6],
... 'C' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
>>> df.groupby('A').B.filter(lambda x: x.mean() > 3.)
1 2
3 4
5 6
Name: B, dtype: int64
Returns
-------
filtered : Series | pandas/core/groupby/generic.py | def filter(self, func, dropna=True, *args, **kwargs): # noqa
"""
Return a copy of a Series excluding elements from groups that
do not satisfy the boolean criterion specified by func.
Parameters
----------
func : function
To apply to each group. Should return True or False.
dropna : Drop groups that do not pass the filter. True by default;
if False, groups that evaluate False are filled with NaNs.
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : [1, 2, 3, 4, 5, 6],
... 'C' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
>>> df.groupby('A').B.filter(lambda x: x.mean() > 3.)
1 2
3 4
5 6
Name: B, dtype: int64
Returns
-------
filtered : Series
"""
if isinstance(func, str):
wrapper = lambda x: getattr(x, func)(*args, **kwargs)
else:
wrapper = lambda x: func(x, *args, **kwargs)
# Interpret np.nan as False.
def true_and_notna(x, *args, **kwargs):
b = wrapper(x, *args, **kwargs)
return b and notna(b)
try:
indices = [self._get_index(name) for name, group in self
if true_and_notna(group)]
except ValueError:
raise TypeError("the filter must return a boolean result")
except TypeError:
raise TypeError("the filter must return a boolean result")
filtered = self._apply_filter(indices, dropna)
return filtered | def filter(self, func, dropna=True, *args, **kwargs): # noqa
"""
Return a copy of a Series excluding elements from groups that
do not satisfy the boolean criterion specified by func.
Parameters
----------
func : function
To apply to each group. Should return True or False.
dropna : Drop groups that do not pass the filter. True by default;
if False, groups that evaluate False are filled with NaNs.
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : [1, 2, 3, 4, 5, 6],
... 'C' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
>>> df.groupby('A').B.filter(lambda x: x.mean() > 3.)
1 2
3 4
5 6
Name: B, dtype: int64
Returns
-------
filtered : Series
"""
if isinstance(func, str):
wrapper = lambda x: getattr(x, func)(*args, **kwargs)
else:
wrapper = lambda x: func(x, *args, **kwargs)
# Interpret np.nan as False.
def true_and_notna(x, *args, **kwargs):
b = wrapper(x, *args, **kwargs)
return b and notna(b)
try:
indices = [self._get_index(name) for name, group in self
if true_and_notna(group)]
except ValueError:
raise TypeError("the filter must return a boolean result")
except TypeError:
raise TypeError("the filter must return a boolean result")
filtered = self._apply_filter(indices, dropna)
return filtered | [
"Return",
"a",
"copy",
"of",
"a",
"Series",
"excluding",
"elements",
"from",
"groups",
"that",
"do",
"not",
"satisfy",
"the",
"boolean",
"criterion",
"specified",
"by",
"func",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L949-L997 | [
"def",
"filter",
"(",
"self",
",",
"func",
",",
"dropna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa",
"if",
"isinstance",
"(",
"func",
",",
"str",
")",
":",
"wrapper",
"=",
"lambda",
"x",
":",
"getattr",
"(",
"x",
",",
"func",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"wrapper",
"=",
"lambda",
"x",
":",
"func",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Interpret np.nan as False.",
"def",
"true_and_notna",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"b",
"=",
"wrapper",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"b",
"and",
"notna",
"(",
"b",
")",
"try",
":",
"indices",
"=",
"[",
"self",
".",
"_get_index",
"(",
"name",
")",
"for",
"name",
",",
"group",
"in",
"self",
"if",
"true_and_notna",
"(",
"group",
")",
"]",
"except",
"ValueError",
":",
"raise",
"TypeError",
"(",
"\"the filter must return a boolean result\"",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"the filter must return a boolean result\"",
")",
"filtered",
"=",
"self",
".",
"_apply_filter",
"(",
"indices",
",",
"dropna",
")",
"return",
"filtered"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SeriesGroupBy.nunique | Return number of unique elements in the group. | pandas/core/groupby/generic.py | def nunique(self, dropna=True):
"""
Return number of unique elements in the group.
"""
ids, _, _ = self.grouper.group_info
val = self.obj.get_values()
try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtypes
msg = 'val.dtype must be object, got {}'.format(val.dtype)
assert val.dtype == object, msg
val, _ = algorithms.factorize(val, sort=False)
sorter = np.lexsort((val, ids))
_isna = lambda a: a == -1
else:
_isna = isna
ids, val = ids[sorter], val[sorter]
# group boundaries are where group ids change
# unique observations are where sorted values change
idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]]
inc = np.r_[1, val[1:] != val[:-1]]
# 1st item of each group is a new unique observation
mask = _isna(val)
if dropna:
inc[idx] = 1
inc[mask] = 0
else:
inc[mask & np.r_[False, mask[:-1]]] = 0
inc[idx] = 1
out = np.add.reduceat(inc, idx).astype('int64', copy=False)
if len(ids):
# NaN/NaT group exists if the head of ids is -1,
# so remove it from res and exclude its index from idx
if ids[0] == -1:
res = out[1:]
idx = idx[np.flatnonzero(idx)]
else:
res = out
else:
res = out[1:]
ri = self.grouper.result_index
# we might have duplications among the bins
if len(res) != len(ri):
res, out = np.zeros(len(ri), dtype=out.dtype), res
res[ids[idx]] = out
return Series(res,
index=ri,
name=self._selection_name) | def nunique(self, dropna=True):
"""
Return number of unique elements in the group.
"""
ids, _, _ = self.grouper.group_info
val = self.obj.get_values()
try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtypes
msg = 'val.dtype must be object, got {}'.format(val.dtype)
assert val.dtype == object, msg
val, _ = algorithms.factorize(val, sort=False)
sorter = np.lexsort((val, ids))
_isna = lambda a: a == -1
else:
_isna = isna
ids, val = ids[sorter], val[sorter]
# group boundaries are where group ids change
# unique observations are where sorted values change
idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]]
inc = np.r_[1, val[1:] != val[:-1]]
# 1st item of each group is a new unique observation
mask = _isna(val)
if dropna:
inc[idx] = 1
inc[mask] = 0
else:
inc[mask & np.r_[False, mask[:-1]]] = 0
inc[idx] = 1
out = np.add.reduceat(inc, idx).astype('int64', copy=False)
if len(ids):
# NaN/NaT group exists if the head of ids is -1,
# so remove it from res and exclude its index from idx
if ids[0] == -1:
res = out[1:]
idx = idx[np.flatnonzero(idx)]
else:
res = out
else:
res = out[1:]
ri = self.grouper.result_index
# we might have duplications among the bins
if len(res) != len(ri):
res, out = np.zeros(len(ri), dtype=out.dtype), res
res[ids[idx]] = out
return Series(res,
index=ri,
name=self._selection_name) | [
"Return",
"number",
"of",
"unique",
"elements",
"in",
"the",
"group",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L999-L1054 | [
"def",
"nunique",
"(",
"self",
",",
"dropna",
"=",
"True",
")",
":",
"ids",
",",
"_",
",",
"_",
"=",
"self",
".",
"grouper",
".",
"group_info",
"val",
"=",
"self",
".",
"obj",
".",
"get_values",
"(",
")",
"try",
":",
"sorter",
"=",
"np",
".",
"lexsort",
"(",
"(",
"val",
",",
"ids",
")",
")",
"except",
"TypeError",
":",
"# catches object dtypes",
"msg",
"=",
"'val.dtype must be object, got {}'",
".",
"format",
"(",
"val",
".",
"dtype",
")",
"assert",
"val",
".",
"dtype",
"==",
"object",
",",
"msg",
"val",
",",
"_",
"=",
"algorithms",
".",
"factorize",
"(",
"val",
",",
"sort",
"=",
"False",
")",
"sorter",
"=",
"np",
".",
"lexsort",
"(",
"(",
"val",
",",
"ids",
")",
")",
"_isna",
"=",
"lambda",
"a",
":",
"a",
"==",
"-",
"1",
"else",
":",
"_isna",
"=",
"isna",
"ids",
",",
"val",
"=",
"ids",
"[",
"sorter",
"]",
",",
"val",
"[",
"sorter",
"]",
"# group boundaries are where group ids change",
"# unique observations are where sorted values change",
"idx",
"=",
"np",
".",
"r_",
"[",
"0",
",",
"1",
"+",
"np",
".",
"nonzero",
"(",
"ids",
"[",
"1",
":",
"]",
"!=",
"ids",
"[",
":",
"-",
"1",
"]",
")",
"[",
"0",
"]",
"]",
"inc",
"=",
"np",
".",
"r_",
"[",
"1",
",",
"val",
"[",
"1",
":",
"]",
"!=",
"val",
"[",
":",
"-",
"1",
"]",
"]",
"# 1st item of each group is a new unique observation",
"mask",
"=",
"_isna",
"(",
"val",
")",
"if",
"dropna",
":",
"inc",
"[",
"idx",
"]",
"=",
"1",
"inc",
"[",
"mask",
"]",
"=",
"0",
"else",
":",
"inc",
"[",
"mask",
"&",
"np",
".",
"r_",
"[",
"False",
",",
"mask",
"[",
":",
"-",
"1",
"]",
"]",
"]",
"=",
"0",
"inc",
"[",
"idx",
"]",
"=",
"1",
"out",
"=",
"np",
".",
"add",
".",
"reduceat",
"(",
"inc",
",",
"idx",
")",
".",
"astype",
"(",
"'int64'",
",",
"copy",
"=",
"False",
")",
"if",
"len",
"(",
"ids",
")",
":",
"# NaN/NaT group exists if the head of ids is -1,",
"# so remove it from res and exclude its index from idx",
"if",
"ids",
"[",
"0",
"]",
"==",
"-",
"1",
":",
"res",
"=",
"out",
"[",
"1",
":",
"]",
"idx",
"=",
"idx",
"[",
"np",
".",
"flatnonzero",
"(",
"idx",
")",
"]",
"else",
":",
"res",
"=",
"out",
"else",
":",
"res",
"=",
"out",
"[",
"1",
":",
"]",
"ri",
"=",
"self",
".",
"grouper",
".",
"result_index",
"# we might have duplications among the bins",
"if",
"len",
"(",
"res",
")",
"!=",
"len",
"(",
"ri",
")",
":",
"res",
",",
"out",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"ri",
")",
",",
"dtype",
"=",
"out",
".",
"dtype",
")",
",",
"res",
"res",
"[",
"ids",
"[",
"idx",
"]",
"]",
"=",
"out",
"return",
"Series",
"(",
"res",
",",
"index",
"=",
"ri",
",",
"name",
"=",
"self",
".",
"_selection_name",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SeriesGroupBy.count | Compute count of group, excluding missing values | pandas/core/groupby/generic.py | def count(self):
""" Compute count of group, excluding missing values """
ids, _, ngroups = self.grouper.group_info
val = self.obj.get_values()
mask = (ids != -1) & ~isna(val)
ids = ensure_platform_int(ids)
minlength = ngroups or 0
out = np.bincount(ids[mask], minlength=minlength)
return Series(out,
index=self.grouper.result_index,
name=self._selection_name,
dtype='int64') | def count(self):
""" Compute count of group, excluding missing values """
ids, _, ngroups = self.grouper.group_info
val = self.obj.get_values()
mask = (ids != -1) & ~isna(val)
ids = ensure_platform_int(ids)
minlength = ngroups or 0
out = np.bincount(ids[mask], minlength=minlength)
return Series(out,
index=self.grouper.result_index,
name=self._selection_name,
dtype='int64') | [
"Compute",
"count",
"of",
"group",
"excluding",
"missing",
"values"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L1183-L1196 | [
"def",
"count",
"(",
"self",
")",
":",
"ids",
",",
"_",
",",
"ngroups",
"=",
"self",
".",
"grouper",
".",
"group_info",
"val",
"=",
"self",
".",
"obj",
".",
"get_values",
"(",
")",
"mask",
"=",
"(",
"ids",
"!=",
"-",
"1",
")",
"&",
"~",
"isna",
"(",
"val",
")",
"ids",
"=",
"ensure_platform_int",
"(",
"ids",
")",
"minlength",
"=",
"ngroups",
"or",
"0",
"out",
"=",
"np",
".",
"bincount",
"(",
"ids",
"[",
"mask",
"]",
",",
"minlength",
"=",
"minlength",
")",
"return",
"Series",
"(",
"out",
",",
"index",
"=",
"self",
".",
"grouper",
".",
"result_index",
",",
"name",
"=",
"self",
".",
"_selection_name",
",",
"dtype",
"=",
"'int64'",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SeriesGroupBy.pct_change | Calcuate pct_change of each value to previous entry in group | pandas/core/groupby/generic.py | def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None):
"""Calcuate pct_change of each value to previous entry in group"""
# TODO: Remove this conditional when #23918 is fixed
if freq:
return self.apply(lambda x: x.pct_change(periods=periods,
fill_method=fill_method,
limit=limit, freq=freq))
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.labels)
shifted = fill_grp.shift(periods=periods, freq=freq)
return (filled / shifted) - 1 | def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None):
"""Calcuate pct_change of each value to previous entry in group"""
# TODO: Remove this conditional when #23918 is fixed
if freq:
return self.apply(lambda x: x.pct_change(periods=periods,
fill_method=fill_method,
limit=limit, freq=freq))
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.labels)
shifted = fill_grp.shift(periods=periods, freq=freq)
return (filled / shifted) - 1 | [
"Calcuate",
"pct_change",
"of",
"each",
"value",
"to",
"previous",
"entry",
"in",
"group"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L1202-L1213 | [
"def",
"pct_change",
"(",
"self",
",",
"periods",
"=",
"1",
",",
"fill_method",
"=",
"'pad'",
",",
"limit",
"=",
"None",
",",
"freq",
"=",
"None",
")",
":",
"# TODO: Remove this conditional when #23918 is fixed",
"if",
"freq",
":",
"return",
"self",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
".",
"pct_change",
"(",
"periods",
"=",
"periods",
",",
"fill_method",
"=",
"fill_method",
",",
"limit",
"=",
"limit",
",",
"freq",
"=",
"freq",
")",
")",
"filled",
"=",
"getattr",
"(",
"self",
",",
"fill_method",
")",
"(",
"limit",
"=",
"limit",
")",
"fill_grp",
"=",
"filled",
".",
"groupby",
"(",
"self",
".",
"grouper",
".",
"labels",
")",
"shifted",
"=",
"fill_grp",
".",
"shift",
"(",
"periods",
"=",
"periods",
",",
"freq",
"=",
"freq",
")",
"return",
"(",
"filled",
"/",
"shifted",
")",
"-",
"1"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DataFrameGroupBy._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/groupby/generic.py | def _gotitem(self, key, ndim, subset=None):
"""
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 ndim == 2:
if subset is None:
subset = self.obj
return DataFrameGroupBy(subset, self.grouper, selection=key,
grouper=self.grouper,
exclusions=self.exclusions,
as_index=self.as_index,
observed=self.observed)
elif ndim == 1:
if subset is None:
subset = self.obj[key]
return SeriesGroupBy(subset, selection=key,
grouper=self.grouper)
raise AssertionError("invalid ndim for _gotitem") | def _gotitem(self, key, ndim, subset=None):
"""
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 ndim == 2:
if subset is None:
subset = self.obj
return DataFrameGroupBy(subset, self.grouper, selection=key,
grouper=self.grouper,
exclusions=self.exclusions,
as_index=self.as_index,
observed=self.observed)
elif ndim == 1:
if subset is None:
subset = self.obj[key]
return SeriesGroupBy(subset, selection=key,
grouper=self.grouper)
raise AssertionError("invalid ndim for _gotitem") | [
"sub",
"-",
"classes",
"to",
"define",
"return",
"a",
"sliced",
"object"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L1297-L1325 | [
"def",
"_gotitem",
"(",
"self",
",",
"key",
",",
"ndim",
",",
"subset",
"=",
"None",
")",
":",
"if",
"ndim",
"==",
"2",
":",
"if",
"subset",
"is",
"None",
":",
"subset",
"=",
"self",
".",
"obj",
"return",
"DataFrameGroupBy",
"(",
"subset",
",",
"self",
".",
"grouper",
",",
"selection",
"=",
"key",
",",
"grouper",
"=",
"self",
".",
"grouper",
",",
"exclusions",
"=",
"self",
".",
"exclusions",
",",
"as_index",
"=",
"self",
".",
"as_index",
",",
"observed",
"=",
"self",
".",
"observed",
")",
"elif",
"ndim",
"==",
"1",
":",
"if",
"subset",
"is",
"None",
":",
"subset",
"=",
"self",
".",
"obj",
"[",
"key",
"]",
"return",
"SeriesGroupBy",
"(",
"subset",
",",
"selection",
"=",
"key",
",",
"grouper",
"=",
"self",
".",
"grouper",
")",
"raise",
"AssertionError",
"(",
"\"invalid ndim for _gotitem\"",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DataFrameGroupBy._reindex_output | If we have categorical groupers, then we want to make sure that
we have a fully reindex-output to the levels. These may have not
participated in the groupings (e.g. may have all been
nan groups);
This can re-expand the output space | pandas/core/groupby/generic.py | def _reindex_output(self, result):
"""
If we have categorical groupers, then we want to make sure that
we have a fully reindex-output to the levels. These may have not
participated in the groupings (e.g. may have all been
nan groups);
This can re-expand the output space
"""
# we need to re-expand the output space to accomodate all values
# whether observed or not in the cartesian product of our groupes
groupings = self.grouper.groupings
if groupings is None:
return result
elif len(groupings) == 1:
return result
# if we only care about the observed values
# we are done
elif self.observed:
return result
# reindexing only applies to a Categorical grouper
elif not any(isinstance(ping.grouper, (Categorical, CategoricalIndex))
for ping in groupings):
return result
levels_list = [ping.group_index for ping in groupings]
index, _ = MultiIndex.from_product(
levels_list, names=self.grouper.names).sortlevel()
if self.as_index:
d = {self.obj._get_axis_name(self.axis): index, 'copy': False}
return result.reindex(**d)
# GH 13204
# Here, the categorical in-axis groupers, which need to be fully
# expanded, are columns in `result`. An idea is to do:
# result = result.set_index(self.grouper.names)
# .reindex(index).reset_index()
# but special care has to be taken because of possible not-in-axis
# groupers.
# So, we manually select and drop the in-axis grouper columns,
# reindex `result`, and then reset the in-axis grouper columns.
# Select in-axis groupers
in_axis_grps = ((i, ping.name) for (i, ping)
in enumerate(groupings) if ping.in_axis)
g_nums, g_names = zip(*in_axis_grps)
result = result.drop(labels=list(g_names), axis=1)
# Set a temp index and reindex (possibly expanding)
result = result.set_index(self.grouper.result_index
).reindex(index, copy=False)
# Reset in-axis grouper columns
# (using level numbers `g_nums` because level names may not be unique)
result = result.reset_index(level=g_nums)
return result.reset_index(drop=True) | def _reindex_output(self, result):
"""
If we have categorical groupers, then we want to make sure that
we have a fully reindex-output to the levels. These may have not
participated in the groupings (e.g. may have all been
nan groups);
This can re-expand the output space
"""
# we need to re-expand the output space to accomodate all values
# whether observed or not in the cartesian product of our groupes
groupings = self.grouper.groupings
if groupings is None:
return result
elif len(groupings) == 1:
return result
# if we only care about the observed values
# we are done
elif self.observed:
return result
# reindexing only applies to a Categorical grouper
elif not any(isinstance(ping.grouper, (Categorical, CategoricalIndex))
for ping in groupings):
return result
levels_list = [ping.group_index for ping in groupings]
index, _ = MultiIndex.from_product(
levels_list, names=self.grouper.names).sortlevel()
if self.as_index:
d = {self.obj._get_axis_name(self.axis): index, 'copy': False}
return result.reindex(**d)
# GH 13204
# Here, the categorical in-axis groupers, which need to be fully
# expanded, are columns in `result`. An idea is to do:
# result = result.set_index(self.grouper.names)
# .reindex(index).reset_index()
# but special care has to be taken because of possible not-in-axis
# groupers.
# So, we manually select and drop the in-axis grouper columns,
# reindex `result`, and then reset the in-axis grouper columns.
# Select in-axis groupers
in_axis_grps = ((i, ping.name) for (i, ping)
in enumerate(groupings) if ping.in_axis)
g_nums, g_names = zip(*in_axis_grps)
result = result.drop(labels=list(g_names), axis=1)
# Set a temp index and reindex (possibly expanding)
result = result.set_index(self.grouper.result_index
).reindex(index, copy=False)
# Reset in-axis grouper columns
# (using level numbers `g_nums` because level names may not be unique)
result = result.reset_index(level=g_nums)
return result.reset_index(drop=True) | [
"If",
"we",
"have",
"categorical",
"groupers",
"then",
"we",
"want",
"to",
"make",
"sure",
"that",
"we",
"have",
"a",
"fully",
"reindex",
"-",
"output",
"to",
"the",
"levels",
".",
"These",
"may",
"have",
"not",
"participated",
"in",
"the",
"groupings",
"(",
"e",
".",
"g",
".",
"may",
"have",
"all",
"been",
"nan",
"groups",
")",
";"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L1395-L1456 | [
"def",
"_reindex_output",
"(",
"self",
",",
"result",
")",
":",
"# we need to re-expand the output space to accomodate all values",
"# whether observed or not in the cartesian product of our groupes",
"groupings",
"=",
"self",
".",
"grouper",
".",
"groupings",
"if",
"groupings",
"is",
"None",
":",
"return",
"result",
"elif",
"len",
"(",
"groupings",
")",
"==",
"1",
":",
"return",
"result",
"# if we only care about the observed values",
"# we are done",
"elif",
"self",
".",
"observed",
":",
"return",
"result",
"# reindexing only applies to a Categorical grouper",
"elif",
"not",
"any",
"(",
"isinstance",
"(",
"ping",
".",
"grouper",
",",
"(",
"Categorical",
",",
"CategoricalIndex",
")",
")",
"for",
"ping",
"in",
"groupings",
")",
":",
"return",
"result",
"levels_list",
"=",
"[",
"ping",
".",
"group_index",
"for",
"ping",
"in",
"groupings",
"]",
"index",
",",
"_",
"=",
"MultiIndex",
".",
"from_product",
"(",
"levels_list",
",",
"names",
"=",
"self",
".",
"grouper",
".",
"names",
")",
".",
"sortlevel",
"(",
")",
"if",
"self",
".",
"as_index",
":",
"d",
"=",
"{",
"self",
".",
"obj",
".",
"_get_axis_name",
"(",
"self",
".",
"axis",
")",
":",
"index",
",",
"'copy'",
":",
"False",
"}",
"return",
"result",
".",
"reindex",
"(",
"*",
"*",
"d",
")",
"# GH 13204",
"# Here, the categorical in-axis groupers, which need to be fully",
"# expanded, are columns in `result`. An idea is to do:",
"# result = result.set_index(self.grouper.names)",
"# .reindex(index).reset_index()",
"# but special care has to be taken because of possible not-in-axis",
"# groupers.",
"# So, we manually select and drop the in-axis grouper columns,",
"# reindex `result`, and then reset the in-axis grouper columns.",
"# Select in-axis groupers",
"in_axis_grps",
"=",
"(",
"(",
"i",
",",
"ping",
".",
"name",
")",
"for",
"(",
"i",
",",
"ping",
")",
"in",
"enumerate",
"(",
"groupings",
")",
"if",
"ping",
".",
"in_axis",
")",
"g_nums",
",",
"g_names",
"=",
"zip",
"(",
"*",
"in_axis_grps",
")",
"result",
"=",
"result",
".",
"drop",
"(",
"labels",
"=",
"list",
"(",
"g_names",
")",
",",
"axis",
"=",
"1",
")",
"# Set a temp index and reindex (possibly expanding)",
"result",
"=",
"result",
".",
"set_index",
"(",
"self",
".",
"grouper",
".",
"result_index",
")",
".",
"reindex",
"(",
"index",
",",
"copy",
"=",
"False",
")",
"# Reset in-axis grouper columns",
"# (using level numbers `g_nums` because level names may not be unique)",
"result",
"=",
"result",
".",
"reset_index",
"(",
"level",
"=",
"g_nums",
")",
"return",
"result",
".",
"reset_index",
"(",
"drop",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DataFrameGroupBy._fill | Overridden method to join grouped columns in output | pandas/core/groupby/generic.py | def _fill(self, direction, limit=None):
"""Overridden method to join grouped columns in output"""
res = super()._fill(direction, limit=limit)
output = OrderedDict(
(grp.name, grp.grouper) for grp in self.grouper.groupings)
from pandas import concat
return concat((self._wrap_transformed_output(output), res), axis=1) | def _fill(self, direction, limit=None):
"""Overridden method to join grouped columns in output"""
res = super()._fill(direction, limit=limit)
output = OrderedDict(
(grp.name, grp.grouper) for grp in self.grouper.groupings)
from pandas import concat
return concat((self._wrap_transformed_output(output), res), axis=1) | [
"Overridden",
"method",
"to",
"join",
"grouped",
"columns",
"in",
"output"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L1472-L1479 | [
"def",
"_fill",
"(",
"self",
",",
"direction",
",",
"limit",
"=",
"None",
")",
":",
"res",
"=",
"super",
"(",
")",
".",
"_fill",
"(",
"direction",
",",
"limit",
"=",
"limit",
")",
"output",
"=",
"OrderedDict",
"(",
"(",
"grp",
".",
"name",
",",
"grp",
".",
"grouper",
")",
"for",
"grp",
"in",
"self",
".",
"grouper",
".",
"groupings",
")",
"from",
"pandas",
"import",
"concat",
"return",
"concat",
"(",
"(",
"self",
".",
"_wrap_transformed_output",
"(",
"output",
")",
",",
"res",
")",
",",
"axis",
"=",
"1",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DataFrameGroupBy.count | Compute count of group, excluding missing values | pandas/core/groupby/generic.py | def count(self):
""" Compute count of group, excluding missing values """
from pandas.core.dtypes.missing import _isna_ndarraylike as _isna
data, _ = self._get_data_to_aggregate()
ids, _, ngroups = self.grouper.group_info
mask = ids != -1
val = ((mask & ~_isna(np.atleast_2d(blk.get_values())))
for blk in data.blocks)
loc = (blk.mgr_locs for blk in data.blocks)
counter = partial(
lib.count_level_2d, labels=ids, max_bin=ngroups, axis=1)
blk = map(make_block, map(counter, val), loc)
return self._wrap_agged_blocks(data.items, list(blk)) | def count(self):
""" Compute count of group, excluding missing values """
from pandas.core.dtypes.missing import _isna_ndarraylike as _isna
data, _ = self._get_data_to_aggregate()
ids, _, ngroups = self.grouper.group_info
mask = ids != -1
val = ((mask & ~_isna(np.atleast_2d(blk.get_values())))
for blk in data.blocks)
loc = (blk.mgr_locs for blk in data.blocks)
counter = partial(
lib.count_level_2d, labels=ids, max_bin=ngroups, axis=1)
blk = map(make_block, map(counter, val), loc)
return self._wrap_agged_blocks(data.items, list(blk)) | [
"Compute",
"count",
"of",
"group",
"excluding",
"missing",
"values"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L1481-L1497 | [
"def",
"count",
"(",
"self",
")",
":",
"from",
"pandas",
".",
"core",
".",
"dtypes",
".",
"missing",
"import",
"_isna_ndarraylike",
"as",
"_isna",
"data",
",",
"_",
"=",
"self",
".",
"_get_data_to_aggregate",
"(",
")",
"ids",
",",
"_",
",",
"ngroups",
"=",
"self",
".",
"grouper",
".",
"group_info",
"mask",
"=",
"ids",
"!=",
"-",
"1",
"val",
"=",
"(",
"(",
"mask",
"&",
"~",
"_isna",
"(",
"np",
".",
"atleast_2d",
"(",
"blk",
".",
"get_values",
"(",
")",
")",
")",
")",
"for",
"blk",
"in",
"data",
".",
"blocks",
")",
"loc",
"=",
"(",
"blk",
".",
"mgr_locs",
"for",
"blk",
"in",
"data",
".",
"blocks",
")",
"counter",
"=",
"partial",
"(",
"lib",
".",
"count_level_2d",
",",
"labels",
"=",
"ids",
",",
"max_bin",
"=",
"ngroups",
",",
"axis",
"=",
"1",
")",
"blk",
"=",
"map",
"(",
"make_block",
",",
"map",
"(",
"counter",
",",
"val",
")",
",",
"loc",
")",
"return",
"self",
".",
"_wrap_agged_blocks",
"(",
"data",
".",
"items",
",",
"list",
"(",
"blk",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DataFrameGroupBy.nunique | Return DataFrame with number of distinct observations per group for
each column.
.. versionadded:: 0.20.0
Parameters
----------
dropna : boolean, default True
Don't include NaN in the counts.
Returns
-------
nunique: DataFrame
Examples
--------
>>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam',
... 'ham', 'ham'],
... 'value1': [1, 5, 5, 2, 5, 5],
... 'value2': list('abbaxy')})
>>> df
id value1 value2
0 spam 1 a
1 egg 5 b
2 egg 5 b
3 spam 2 a
4 ham 5 x
5 ham 5 y
>>> df.groupby('id').nunique()
id value1 value2
id
egg 1 1 1
ham 1 1 2
spam 1 2 1
Check for rows with the same id but conflicting values:
>>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any())
id value1 value2
0 spam 1 a
3 spam 2 a
4 ham 5 x
5 ham 5 y | pandas/core/groupby/generic.py | def nunique(self, dropna=True):
"""
Return DataFrame with number of distinct observations per group for
each column.
.. versionadded:: 0.20.0
Parameters
----------
dropna : boolean, default True
Don't include NaN in the counts.
Returns
-------
nunique: DataFrame
Examples
--------
>>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam',
... 'ham', 'ham'],
... 'value1': [1, 5, 5, 2, 5, 5],
... 'value2': list('abbaxy')})
>>> df
id value1 value2
0 spam 1 a
1 egg 5 b
2 egg 5 b
3 spam 2 a
4 ham 5 x
5 ham 5 y
>>> df.groupby('id').nunique()
id value1 value2
id
egg 1 1 1
ham 1 1 2
spam 1 2 1
Check for rows with the same id but conflicting values:
>>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any())
id value1 value2
0 spam 1 a
3 spam 2 a
4 ham 5 x
5 ham 5 y
"""
obj = self._selected_obj
def groupby_series(obj, col=None):
return SeriesGroupBy(obj,
selection=col,
grouper=self.grouper).nunique(dropna=dropna)
if isinstance(obj, Series):
results = groupby_series(obj)
else:
from pandas.core.reshape.concat import concat
results = [groupby_series(obj[col], col) for col in obj.columns]
results = concat(results, axis=1)
results.columns.names = obj.columns.names
if not self.as_index:
results.index = ibase.default_index(len(results))
return results | def nunique(self, dropna=True):
"""
Return DataFrame with number of distinct observations per group for
each column.
.. versionadded:: 0.20.0
Parameters
----------
dropna : boolean, default True
Don't include NaN in the counts.
Returns
-------
nunique: DataFrame
Examples
--------
>>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam',
... 'ham', 'ham'],
... 'value1': [1, 5, 5, 2, 5, 5],
... 'value2': list('abbaxy')})
>>> df
id value1 value2
0 spam 1 a
1 egg 5 b
2 egg 5 b
3 spam 2 a
4 ham 5 x
5 ham 5 y
>>> df.groupby('id').nunique()
id value1 value2
id
egg 1 1 1
ham 1 1 2
spam 1 2 1
Check for rows with the same id but conflicting values:
>>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any())
id value1 value2
0 spam 1 a
3 spam 2 a
4 ham 5 x
5 ham 5 y
"""
obj = self._selected_obj
def groupby_series(obj, col=None):
return SeriesGroupBy(obj,
selection=col,
grouper=self.grouper).nunique(dropna=dropna)
if isinstance(obj, Series):
results = groupby_series(obj)
else:
from pandas.core.reshape.concat import concat
results = [groupby_series(obj[col], col) for col in obj.columns]
results = concat(results, axis=1)
results.columns.names = obj.columns.names
if not self.as_index:
results.index = ibase.default_index(len(results))
return results | [
"Return",
"DataFrame",
"with",
"number",
"of",
"distinct",
"observations",
"per",
"group",
"for",
"each",
"column",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/generic.py#L1499-L1564 | [
"def",
"nunique",
"(",
"self",
",",
"dropna",
"=",
"True",
")",
":",
"obj",
"=",
"self",
".",
"_selected_obj",
"def",
"groupby_series",
"(",
"obj",
",",
"col",
"=",
"None",
")",
":",
"return",
"SeriesGroupBy",
"(",
"obj",
",",
"selection",
"=",
"col",
",",
"grouper",
"=",
"self",
".",
"grouper",
")",
".",
"nunique",
"(",
"dropna",
"=",
"dropna",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Series",
")",
":",
"results",
"=",
"groupby_series",
"(",
"obj",
")",
"else",
":",
"from",
"pandas",
".",
"core",
".",
"reshape",
".",
"concat",
"import",
"concat",
"results",
"=",
"[",
"groupby_series",
"(",
"obj",
"[",
"col",
"]",
",",
"col",
")",
"for",
"col",
"in",
"obj",
".",
"columns",
"]",
"results",
"=",
"concat",
"(",
"results",
",",
"axis",
"=",
"1",
")",
"results",
".",
"columns",
".",
"names",
"=",
"obj",
".",
"columns",
".",
"names",
"if",
"not",
"self",
".",
"as_index",
":",
"results",
".",
"index",
"=",
"ibase",
".",
"default_index",
"(",
"len",
"(",
"results",
")",
")",
"return",
"results"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | extract_array | Extract the ndarray or ExtensionArray from a Series or Index.
For all other types, `obj` is just returned as is.
Parameters
----------
obj : object
For Series / Index, the underlying ExtensionArray is unboxed.
For Numpy-backed ExtensionArrays, the ndarray is extracted.
extract_numpy : bool, default False
Whether to extract the ndarray from a PandasArray
Returns
-------
arr : object
Examples
--------
>>> extract_array(pd.Series(['a', 'b', 'c'], dtype='category'))
[a, b, c]
Categories (3, object): [a, b, c]
Other objects like lists, arrays, and DataFrames are just passed through.
>>> extract_array([1, 2, 3])
[1, 2, 3]
For an ndarray-backed Series / Index a PandasArray is returned.
>>> extract_array(pd.Series([1, 2, 3]))
<PandasArray>
[1, 2, 3]
Length: 3, dtype: int64
To extract all the way down to the ndarray, pass ``extract_numpy=True``.
>>> extract_array(pd.Series([1, 2, 3]), extract_numpy=True)
array([1, 2, 3]) | pandas/core/internals/arrays.py | def extract_array(obj, extract_numpy=False):
"""
Extract the ndarray or ExtensionArray from a Series or Index.
For all other types, `obj` is just returned as is.
Parameters
----------
obj : object
For Series / Index, the underlying ExtensionArray is unboxed.
For Numpy-backed ExtensionArrays, the ndarray is extracted.
extract_numpy : bool, default False
Whether to extract the ndarray from a PandasArray
Returns
-------
arr : object
Examples
--------
>>> extract_array(pd.Series(['a', 'b', 'c'], dtype='category'))
[a, b, c]
Categories (3, object): [a, b, c]
Other objects like lists, arrays, and DataFrames are just passed through.
>>> extract_array([1, 2, 3])
[1, 2, 3]
For an ndarray-backed Series / Index a PandasArray is returned.
>>> extract_array(pd.Series([1, 2, 3]))
<PandasArray>
[1, 2, 3]
Length: 3, dtype: int64
To extract all the way down to the ndarray, pass ``extract_numpy=True``.
>>> extract_array(pd.Series([1, 2, 3]), extract_numpy=True)
array([1, 2, 3])
"""
if isinstance(obj, (ABCIndexClass, ABCSeries)):
obj = obj.array
if extract_numpy and isinstance(obj, ABCPandasArray):
obj = obj.to_numpy()
return obj | def extract_array(obj, extract_numpy=False):
"""
Extract the ndarray or ExtensionArray from a Series or Index.
For all other types, `obj` is just returned as is.
Parameters
----------
obj : object
For Series / Index, the underlying ExtensionArray is unboxed.
For Numpy-backed ExtensionArrays, the ndarray is extracted.
extract_numpy : bool, default False
Whether to extract the ndarray from a PandasArray
Returns
-------
arr : object
Examples
--------
>>> extract_array(pd.Series(['a', 'b', 'c'], dtype='category'))
[a, b, c]
Categories (3, object): [a, b, c]
Other objects like lists, arrays, and DataFrames are just passed through.
>>> extract_array([1, 2, 3])
[1, 2, 3]
For an ndarray-backed Series / Index a PandasArray is returned.
>>> extract_array(pd.Series([1, 2, 3]))
<PandasArray>
[1, 2, 3]
Length: 3, dtype: int64
To extract all the way down to the ndarray, pass ``extract_numpy=True``.
>>> extract_array(pd.Series([1, 2, 3]), extract_numpy=True)
array([1, 2, 3])
"""
if isinstance(obj, (ABCIndexClass, ABCSeries)):
obj = obj.array
if extract_numpy and isinstance(obj, ABCPandasArray):
obj = obj.to_numpy()
return obj | [
"Extract",
"the",
"ndarray",
"or",
"ExtensionArray",
"from",
"a",
"Series",
"or",
"Index",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/arrays.py#L7-L55 | [
"def",
"extract_array",
"(",
"obj",
",",
"extract_numpy",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"ABCIndexClass",
",",
"ABCSeries",
")",
")",
":",
"obj",
"=",
"obj",
".",
"array",
"if",
"extract_numpy",
"and",
"isinstance",
"(",
"obj",
",",
"ABCPandasArray",
")",
":",
"obj",
"=",
"obj",
".",
"to_numpy",
"(",
")",
"return",
"obj"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | flatten | Flatten an arbitrarily nested sequence.
Parameters
----------
l : sequence
The non string sequence to flatten
Notes
-----
This doesn't consider strings sequences.
Returns
-------
flattened : generator | pandas/core/common.py | def flatten(l):
"""
Flatten an arbitrarily nested sequence.
Parameters
----------
l : sequence
The non string sequence to flatten
Notes
-----
This doesn't consider strings sequences.
Returns
-------
flattened : generator
"""
for el in l:
if _iterable_not_string(el):
for s in flatten(el):
yield s
else:
yield el | def flatten(l):
"""
Flatten an arbitrarily nested sequence.
Parameters
----------
l : sequence
The non string sequence to flatten
Notes
-----
This doesn't consider strings sequences.
Returns
-------
flattened : generator
"""
for el in l:
if _iterable_not_string(el):
for s in flatten(el):
yield s
else:
yield el | [
"Flatten",
"an",
"arbitrarily",
"nested",
"sequence",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L35-L57 | [
"def",
"flatten",
"(",
"l",
")",
":",
"for",
"el",
"in",
"l",
":",
"if",
"_iterable_not_string",
"(",
"el",
")",
":",
"for",
"s",
"in",
"flatten",
"(",
"el",
")",
":",
"yield",
"s",
"else",
":",
"yield",
"el"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | is_bool_indexer | Check whether `key` is a valid boolean indexer.
Parameters
----------
key : Any
Only list-likes may be considered boolean indexers.
All other types are not considered a boolean indexer.
For array-like input, boolean ndarrays or ExtensionArrays
with ``_is_boolean`` set are considered boolean indexers.
Returns
-------
bool
Raises
------
ValueError
When the array is an object-dtype ndarray or ExtensionArray
and contains missing values. | pandas/core/common.py | def is_bool_indexer(key: Any) -> bool:
"""
Check whether `key` is a valid boolean indexer.
Parameters
----------
key : Any
Only list-likes may be considered boolean indexers.
All other types are not considered a boolean indexer.
For array-like input, boolean ndarrays or ExtensionArrays
with ``_is_boolean`` set are considered boolean indexers.
Returns
-------
bool
Raises
------
ValueError
When the array is an object-dtype ndarray or ExtensionArray
and contains missing values.
"""
na_msg = 'cannot index with vector containing NA / NaN values'
if (isinstance(key, (ABCSeries, np.ndarray, ABCIndex)) or
(is_array_like(key) and is_extension_array_dtype(key.dtype))):
if key.dtype == np.object_:
key = np.asarray(values_from_object(key))
if not lib.is_bool_array(key):
if isna(key).any():
raise ValueError(na_msg)
return False
return True
elif is_bool_dtype(key.dtype):
# an ndarray with bool-dtype by definition has no missing values.
# So we only need to check for NAs in ExtensionArrays
if is_extension_array_dtype(key.dtype):
if np.any(key.isna()):
raise ValueError(na_msg)
return True
elif isinstance(key, list):
try:
arr = np.asarray(key)
return arr.dtype == np.bool_ and len(arr) == len(key)
except TypeError: # pragma: no cover
return False
return False | def is_bool_indexer(key: Any) -> bool:
"""
Check whether `key` is a valid boolean indexer.
Parameters
----------
key : Any
Only list-likes may be considered boolean indexers.
All other types are not considered a boolean indexer.
For array-like input, boolean ndarrays or ExtensionArrays
with ``_is_boolean`` set are considered boolean indexers.
Returns
-------
bool
Raises
------
ValueError
When the array is an object-dtype ndarray or ExtensionArray
and contains missing values.
"""
na_msg = 'cannot index with vector containing NA / NaN values'
if (isinstance(key, (ABCSeries, np.ndarray, ABCIndex)) or
(is_array_like(key) and is_extension_array_dtype(key.dtype))):
if key.dtype == np.object_:
key = np.asarray(values_from_object(key))
if not lib.is_bool_array(key):
if isna(key).any():
raise ValueError(na_msg)
return False
return True
elif is_bool_dtype(key.dtype):
# an ndarray with bool-dtype by definition has no missing values.
# So we only need to check for NAs in ExtensionArrays
if is_extension_array_dtype(key.dtype):
if np.any(key.isna()):
raise ValueError(na_msg)
return True
elif isinstance(key, list):
try:
arr = np.asarray(key)
return arr.dtype == np.bool_ and len(arr) == len(key)
except TypeError: # pragma: no cover
return False
return False | [
"Check",
"whether",
"key",
"is",
"a",
"valid",
"boolean",
"indexer",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L95-L142 | [
"def",
"is_bool_indexer",
"(",
"key",
":",
"Any",
")",
"->",
"bool",
":",
"na_msg",
"=",
"'cannot index with vector containing NA / NaN values'",
"if",
"(",
"isinstance",
"(",
"key",
",",
"(",
"ABCSeries",
",",
"np",
".",
"ndarray",
",",
"ABCIndex",
")",
")",
"or",
"(",
"is_array_like",
"(",
"key",
")",
"and",
"is_extension_array_dtype",
"(",
"key",
".",
"dtype",
")",
")",
")",
":",
"if",
"key",
".",
"dtype",
"==",
"np",
".",
"object_",
":",
"key",
"=",
"np",
".",
"asarray",
"(",
"values_from_object",
"(",
"key",
")",
")",
"if",
"not",
"lib",
".",
"is_bool_array",
"(",
"key",
")",
":",
"if",
"isna",
"(",
"key",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"na_msg",
")",
"return",
"False",
"return",
"True",
"elif",
"is_bool_dtype",
"(",
"key",
".",
"dtype",
")",
":",
"# an ndarray with bool-dtype by definition has no missing values.",
"# So we only need to check for NAs in ExtensionArrays",
"if",
"is_extension_array_dtype",
"(",
"key",
".",
"dtype",
")",
":",
"if",
"np",
".",
"any",
"(",
"key",
".",
"isna",
"(",
")",
")",
":",
"raise",
"ValueError",
"(",
"na_msg",
")",
"return",
"True",
"elif",
"isinstance",
"(",
"key",
",",
"list",
")",
":",
"try",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"key",
")",
"return",
"arr",
".",
"dtype",
"==",
"np",
".",
"bool_",
"and",
"len",
"(",
"arr",
")",
"==",
"len",
"(",
"key",
")",
"except",
"TypeError",
":",
"# pragma: no cover",
"return",
"False",
"return",
"False"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | cast_scalar_indexer | To avoid numpy DeprecationWarnings, cast float to integer where valid.
Parameters
----------
val : scalar
Returns
-------
outval : scalar | pandas/core/common.py | def cast_scalar_indexer(val):
"""
To avoid numpy DeprecationWarnings, cast float to integer where valid.
Parameters
----------
val : scalar
Returns
-------
outval : scalar
"""
# assumes lib.is_scalar(val)
if lib.is_float(val) and val == int(val):
return int(val)
return val | def cast_scalar_indexer(val):
"""
To avoid numpy DeprecationWarnings, cast float to integer where valid.
Parameters
----------
val : scalar
Returns
-------
outval : scalar
"""
# assumes lib.is_scalar(val)
if lib.is_float(val) and val == int(val):
return int(val)
return val | [
"To",
"avoid",
"numpy",
"DeprecationWarnings",
"cast",
"float",
"to",
"integer",
"where",
"valid",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L145-L160 | [
"def",
"cast_scalar_indexer",
"(",
"val",
")",
":",
"# assumes lib.is_scalar(val)",
"if",
"lib",
".",
"is_float",
"(",
"val",
")",
"and",
"val",
"==",
"int",
"(",
"val",
")",
":",
"return",
"int",
"(",
"val",
")",
"return",
"val"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | index_labels_to_array | Transform label or iterable of labels to array, for use in Index.
Parameters
----------
dtype : dtype
If specified, use as dtype of the resulting array, otherwise infer.
Returns
-------
array | pandas/core/common.py | def index_labels_to_array(labels, dtype=None):
"""
Transform label or iterable of labels to array, for use in Index.
Parameters
----------
dtype : dtype
If specified, use as dtype of the resulting array, otherwise infer.
Returns
-------
array
"""
if isinstance(labels, (str, tuple)):
labels = [labels]
if not isinstance(labels, (list, np.ndarray)):
try:
labels = list(labels)
except TypeError: # non-iterable
labels = [labels]
labels = asarray_tuplesafe(labels, dtype=dtype)
return labels | def index_labels_to_array(labels, dtype=None):
"""
Transform label or iterable of labels to array, for use in Index.
Parameters
----------
dtype : dtype
If specified, use as dtype of the resulting array, otherwise infer.
Returns
-------
array
"""
if isinstance(labels, (str, tuple)):
labels = [labels]
if not isinstance(labels, (list, np.ndarray)):
try:
labels = list(labels)
except TypeError: # non-iterable
labels = [labels]
labels = asarray_tuplesafe(labels, dtype=dtype)
return labels | [
"Transform",
"label",
"or",
"iterable",
"of",
"labels",
"to",
"array",
"for",
"use",
"in",
"Index",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L259-L283 | [
"def",
"index_labels_to_array",
"(",
"labels",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"labels",
",",
"(",
"str",
",",
"tuple",
")",
")",
":",
"labels",
"=",
"[",
"labels",
"]",
"if",
"not",
"isinstance",
"(",
"labels",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"try",
":",
"labels",
"=",
"list",
"(",
"labels",
")",
"except",
"TypeError",
":",
"# non-iterable",
"labels",
"=",
"[",
"labels",
"]",
"labels",
"=",
"asarray_tuplesafe",
"(",
"labels",
",",
"dtype",
"=",
"dtype",
")",
"return",
"labels"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | is_null_slice | We have a null slice. | pandas/core/common.py | def is_null_slice(obj):
"""
We have a null slice.
"""
return (isinstance(obj, slice) and obj.start is None and
obj.stop is None and obj.step is None) | def is_null_slice(obj):
"""
We have a null slice.
"""
return (isinstance(obj, slice) and obj.start is None and
obj.stop is None and obj.step is None) | [
"We",
"have",
"a",
"null",
"slice",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L292-L297 | [
"def",
"is_null_slice",
"(",
"obj",
")",
":",
"return",
"(",
"isinstance",
"(",
"obj",
",",
"slice",
")",
"and",
"obj",
".",
"start",
"is",
"None",
"and",
"obj",
".",
"stop",
"is",
"None",
"and",
"obj",
".",
"step",
"is",
"None",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | is_full_slice | We have a full length slice. | pandas/core/common.py | def is_full_slice(obj, l):
"""
We have a full length slice.
"""
return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and
obj.step is None) | def is_full_slice(obj, l):
"""
We have a full length slice.
"""
return (isinstance(obj, slice) and obj.start == 0 and obj.stop == l and
obj.step is None) | [
"We",
"have",
"a",
"full",
"length",
"slice",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L308-L313 | [
"def",
"is_full_slice",
"(",
"obj",
",",
"l",
")",
":",
"return",
"(",
"isinstance",
"(",
"obj",
",",
"slice",
")",
"and",
"obj",
".",
"start",
"==",
"0",
"and",
"obj",
".",
"stop",
"==",
"l",
"and",
"obj",
".",
"step",
"is",
"None",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | apply_if_callable | Evaluate possibly callable input using obj and kwargs if it is callable,
otherwise return as it is.
Parameters
----------
maybe_callable : possibly a callable
obj : NDFrame
**kwargs | pandas/core/common.py | def apply_if_callable(maybe_callable, obj, **kwargs):
"""
Evaluate possibly callable input using obj and kwargs if it is callable,
otherwise return as it is.
Parameters
----------
maybe_callable : possibly a callable
obj : NDFrame
**kwargs
"""
if callable(maybe_callable):
return maybe_callable(obj, **kwargs)
return maybe_callable | def apply_if_callable(maybe_callable, obj, **kwargs):
"""
Evaluate possibly callable input using obj and kwargs if it is callable,
otherwise return as it is.
Parameters
----------
maybe_callable : possibly a callable
obj : NDFrame
**kwargs
"""
if callable(maybe_callable):
return maybe_callable(obj, **kwargs)
return maybe_callable | [
"Evaluate",
"possibly",
"callable",
"input",
"using",
"obj",
"and",
"kwargs",
"if",
"it",
"is",
"callable",
"otherwise",
"return",
"as",
"it",
"is",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L333-L348 | [
"def",
"apply_if_callable",
"(",
"maybe_callable",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"maybe_callable",
")",
":",
"return",
"maybe_callable",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
"return",
"maybe_callable"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | standardize_mapping | Helper function to standardize a supplied mapping.
.. versionadded:: 0.21.0
Parameters
----------
into : instance or subclass of collections.abc.Mapping
Must be a class, an initialized collections.defaultdict,
or an instance of a collections.abc.Mapping subclass.
Returns
-------
mapping : a collections.abc.Mapping subclass or other constructor
a callable object that can accept an iterator to create
the desired Mapping.
See Also
--------
DataFrame.to_dict
Series.to_dict | pandas/core/common.py | def standardize_mapping(into):
"""
Helper function to standardize a supplied mapping.
.. versionadded:: 0.21.0
Parameters
----------
into : instance or subclass of collections.abc.Mapping
Must be a class, an initialized collections.defaultdict,
or an instance of a collections.abc.Mapping subclass.
Returns
-------
mapping : a collections.abc.Mapping subclass or other constructor
a callable object that can accept an iterator to create
the desired Mapping.
See Also
--------
DataFrame.to_dict
Series.to_dict
"""
if not inspect.isclass(into):
if isinstance(into, collections.defaultdict):
return partial(
collections.defaultdict, into.default_factory)
into = type(into)
if not issubclass(into, abc.Mapping):
raise TypeError('unsupported type: {into}'.format(into=into))
elif into == collections.defaultdict:
raise TypeError(
'to_dict() only accepts initialized defaultdicts')
return into | def standardize_mapping(into):
"""
Helper function to standardize a supplied mapping.
.. versionadded:: 0.21.0
Parameters
----------
into : instance or subclass of collections.abc.Mapping
Must be a class, an initialized collections.defaultdict,
or an instance of a collections.abc.Mapping subclass.
Returns
-------
mapping : a collections.abc.Mapping subclass or other constructor
a callable object that can accept an iterator to create
the desired Mapping.
See Also
--------
DataFrame.to_dict
Series.to_dict
"""
if not inspect.isclass(into):
if isinstance(into, collections.defaultdict):
return partial(
collections.defaultdict, into.default_factory)
into = type(into)
if not issubclass(into, abc.Mapping):
raise TypeError('unsupported type: {into}'.format(into=into))
elif into == collections.defaultdict:
raise TypeError(
'to_dict() only accepts initialized defaultdicts')
return into | [
"Helper",
"function",
"to",
"standardize",
"a",
"supplied",
"mapping",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L368-L401 | [
"def",
"standardize_mapping",
"(",
"into",
")",
":",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"into",
")",
":",
"if",
"isinstance",
"(",
"into",
",",
"collections",
".",
"defaultdict",
")",
":",
"return",
"partial",
"(",
"collections",
".",
"defaultdict",
",",
"into",
".",
"default_factory",
")",
"into",
"=",
"type",
"(",
"into",
")",
"if",
"not",
"issubclass",
"(",
"into",
",",
"abc",
".",
"Mapping",
")",
":",
"raise",
"TypeError",
"(",
"'unsupported type: {into}'",
".",
"format",
"(",
"into",
"=",
"into",
")",
")",
"elif",
"into",
"==",
"collections",
".",
"defaultdict",
":",
"raise",
"TypeError",
"(",
"'to_dict() only accepts initialized defaultdicts'",
")",
"return",
"into"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | random_state | Helper function for processing random_state arguments.
Parameters
----------
state : int, np.random.RandomState, None.
If receives an int, passes to np.random.RandomState() as seed.
If receives an np.random.RandomState object, just returns object.
If receives `None`, returns np.random.
If receives anything else, raises an informative ValueError.
Default None.
Returns
-------
np.random.RandomState | pandas/core/common.py | def random_state(state=None):
"""
Helper function for processing random_state arguments.
Parameters
----------
state : int, np.random.RandomState, None.
If receives an int, passes to np.random.RandomState() as seed.
If receives an np.random.RandomState object, just returns object.
If receives `None`, returns np.random.
If receives anything else, raises an informative ValueError.
Default None.
Returns
-------
np.random.RandomState
"""
if is_integer(state):
return np.random.RandomState(state)
elif isinstance(state, np.random.RandomState):
return state
elif state is None:
return np.random
else:
raise ValueError("random_state must be an integer, a numpy "
"RandomState, or None") | def random_state(state=None):
"""
Helper function for processing random_state arguments.
Parameters
----------
state : int, np.random.RandomState, None.
If receives an int, passes to np.random.RandomState() as seed.
If receives an np.random.RandomState object, just returns object.
If receives `None`, returns np.random.
If receives anything else, raises an informative ValueError.
Default None.
Returns
-------
np.random.RandomState
"""
if is_integer(state):
return np.random.RandomState(state)
elif isinstance(state, np.random.RandomState):
return state
elif state is None:
return np.random
else:
raise ValueError("random_state must be an integer, a numpy "
"RandomState, or None") | [
"Helper",
"function",
"for",
"processing",
"random_state",
"arguments",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L404-L430 | [
"def",
"random_state",
"(",
"state",
"=",
"None",
")",
":",
"if",
"is_integer",
"(",
"state",
")",
":",
"return",
"np",
".",
"random",
".",
"RandomState",
"(",
"state",
")",
"elif",
"isinstance",
"(",
"state",
",",
"np",
".",
"random",
".",
"RandomState",
")",
":",
"return",
"state",
"elif",
"state",
"is",
"None",
":",
"return",
"np",
".",
"random",
"else",
":",
"raise",
"ValueError",
"(",
"\"random_state must be an integer, a numpy \"",
"\"RandomState, or None\"",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _pipe | Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple.
Parameters
----------
func : callable or tuple of (callable, string)
Function to apply to this object or, alternatively, a
``(callable, data_keyword)`` tuple where ``data_keyword`` is a
string indicating the keyword of `callable`` that expects the
object.
args : iterable, optional
positional arguments passed into ``func``.
kwargs : dict, optional
a dictionary of keyword arguments passed into ``func``.
Returns
-------
object : the return type of ``func``. | pandas/core/common.py | def _pipe(obj, func, *args, **kwargs):
"""
Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple.
Parameters
----------
func : callable or tuple of (callable, string)
Function to apply to this object or, alternatively, a
``(callable, data_keyword)`` tuple where ``data_keyword`` is a
string indicating the keyword of `callable`` that expects the
object.
args : iterable, optional
positional arguments passed into ``func``.
kwargs : dict, optional
a dictionary of keyword arguments passed into ``func``.
Returns
-------
object : the return type of ``func``.
"""
if isinstance(func, tuple):
func, target = func
if target in kwargs:
msg = '%s is both the pipe target and a keyword argument' % target
raise ValueError(msg)
kwargs[target] = obj
return func(*args, **kwargs)
else:
return func(obj, *args, **kwargs) | def _pipe(obj, func, *args, **kwargs):
"""
Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple.
Parameters
----------
func : callable or tuple of (callable, string)
Function to apply to this object or, alternatively, a
``(callable, data_keyword)`` tuple where ``data_keyword`` is a
string indicating the keyword of `callable`` that expects the
object.
args : iterable, optional
positional arguments passed into ``func``.
kwargs : dict, optional
a dictionary of keyword arguments passed into ``func``.
Returns
-------
object : the return type of ``func``.
"""
if isinstance(func, tuple):
func, target = func
if target in kwargs:
msg = '%s is both the pipe target and a keyword argument' % target
raise ValueError(msg)
kwargs[target] = obj
return func(*args, **kwargs)
else:
return func(obj, *args, **kwargs) | [
"Apply",
"a",
"function",
"func",
"to",
"object",
"obj",
"either",
"by",
"passing",
"obj",
"as",
"the",
"first",
"argument",
"to",
"the",
"function",
"or",
"in",
"the",
"case",
"that",
"the",
"func",
"is",
"a",
"tuple",
"interpret",
"the",
"first",
"element",
"of",
"the",
"tuple",
"as",
"a",
"function",
"and",
"pass",
"the",
"obj",
"to",
"that",
"function",
"as",
"a",
"keyword",
"argument",
"whose",
"key",
"is",
"the",
"value",
"of",
"the",
"second",
"element",
"of",
"the",
"tuple",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L433-L465 | [
"def",
"_pipe",
"(",
"obj",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"tuple",
")",
":",
"func",
",",
"target",
"=",
"func",
"if",
"target",
"in",
"kwargs",
":",
"msg",
"=",
"'%s is both the pipe target and a keyword argument'",
"%",
"target",
"raise",
"ValueError",
"(",
"msg",
")",
"kwargs",
"[",
"target",
"]",
"=",
"obj",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"func",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_rename_function | Returns a function that will map names/labels, dependent if mapper
is a dict, Series or just a function. | pandas/core/common.py | def _get_rename_function(mapper):
"""
Returns a function that will map names/labels, dependent if mapper
is a dict, Series or just a function.
"""
if isinstance(mapper, (abc.Mapping, ABCSeries)):
def f(x):
if x in mapper:
return mapper[x]
else:
return x
else:
f = mapper
return f | def _get_rename_function(mapper):
"""
Returns a function that will map names/labels, dependent if mapper
is a dict, Series or just a function.
"""
if isinstance(mapper, (abc.Mapping, ABCSeries)):
def f(x):
if x in mapper:
return mapper[x]
else:
return x
else:
f = mapper
return f | [
"Returns",
"a",
"function",
"that",
"will",
"map",
"names",
"/",
"labels",
"dependent",
"if",
"mapper",
"is",
"a",
"dict",
"Series",
"or",
"just",
"a",
"function",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/common.py#L468-L483 | [
"def",
"_get_rename_function",
"(",
"mapper",
")",
":",
"if",
"isinstance",
"(",
"mapper",
",",
"(",
"abc",
".",
"Mapping",
",",
"ABCSeries",
")",
")",
":",
"def",
"f",
"(",
"x",
")",
":",
"if",
"x",
"in",
"mapper",
":",
"return",
"mapper",
"[",
"x",
"]",
"else",
":",
"return",
"x",
"else",
":",
"f",
"=",
"mapper",
"return",
"f"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_fill_value | return the correct fill value for the dtype of the values | pandas/core/nanops.py | def _get_fill_value(dtype, fill_value=None, fill_value_typ=None):
""" return the correct fill value for the dtype of the values """
if fill_value is not None:
return fill_value
if _na_ok_dtype(dtype):
if fill_value_typ is None:
return np.nan
else:
if fill_value_typ == '+inf':
return np.inf
else:
return -np.inf
else:
if fill_value_typ is None:
return tslibs.iNaT
else:
if fill_value_typ == '+inf':
# need the max int here
return _int64_max
else:
return tslibs.iNaT | def _get_fill_value(dtype, fill_value=None, fill_value_typ=None):
""" return the correct fill value for the dtype of the values """
if fill_value is not None:
return fill_value
if _na_ok_dtype(dtype):
if fill_value_typ is None:
return np.nan
else:
if fill_value_typ == '+inf':
return np.inf
else:
return -np.inf
else:
if fill_value_typ is None:
return tslibs.iNaT
else:
if fill_value_typ == '+inf':
# need the max int here
return _int64_max
else:
return tslibs.iNaT | [
"return",
"the",
"correct",
"fill",
"value",
"for",
"the",
"dtype",
"of",
"the",
"values"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L180-L200 | [
"def",
"_get_fill_value",
"(",
"dtype",
",",
"fill_value",
"=",
"None",
",",
"fill_value_typ",
"=",
"None",
")",
":",
"if",
"fill_value",
"is",
"not",
"None",
":",
"return",
"fill_value",
"if",
"_na_ok_dtype",
"(",
"dtype",
")",
":",
"if",
"fill_value_typ",
"is",
"None",
":",
"return",
"np",
".",
"nan",
"else",
":",
"if",
"fill_value_typ",
"==",
"'+inf'",
":",
"return",
"np",
".",
"inf",
"else",
":",
"return",
"-",
"np",
".",
"inf",
"else",
":",
"if",
"fill_value_typ",
"is",
"None",
":",
"return",
"tslibs",
".",
"iNaT",
"else",
":",
"if",
"fill_value_typ",
"==",
"'+inf'",
":",
"# need the max int here",
"return",
"_int64_max",
"else",
":",
"return",
"tslibs",
".",
"iNaT"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_values | utility to get the values view, mask, dtype
if necessary copy and mask using the specified fill_value
copy = True will force the copy | pandas/core/nanops.py | def _get_values(values, skipna, fill_value=None, fill_value_typ=None,
isfinite=False, copy=True, mask=None):
""" utility to get the values view, mask, dtype
if necessary copy and mask using the specified fill_value
copy = True will force the copy
"""
if is_datetime64tz_dtype(values):
# com.values_from_object returns M8[ns] dtype instead of tz-aware,
# so this case must be handled separately from the rest
dtype = values.dtype
values = getattr(values, "_values", values)
else:
values = com.values_from_object(values)
dtype = values.dtype
if mask is None:
if isfinite:
mask = _isfinite(values)
else:
mask = isna(values)
if is_datetime_or_timedelta_dtype(values) or is_datetime64tz_dtype(values):
# changing timedelta64/datetime64 to int64 needs to happen after
# finding `mask` above
values = getattr(values, "asi8", values)
values = values.view(np.int64)
dtype_ok = _na_ok_dtype(dtype)
# get our fill value (in case we need to provide an alternative
# dtype for it)
fill_value = _get_fill_value(dtype, fill_value=fill_value,
fill_value_typ=fill_value_typ)
if skipna:
if copy:
values = values.copy()
if dtype_ok:
np.putmask(values, mask, fill_value)
# promote if needed
else:
values, changed = maybe_upcast_putmask(values, mask, fill_value)
elif copy:
values = values.copy()
# return a platform independent precision dtype
dtype_max = dtype
if is_integer_dtype(dtype) or is_bool_dtype(dtype):
dtype_max = np.int64
elif is_float_dtype(dtype):
dtype_max = np.float64
return values, mask, dtype, dtype_max, fill_value | def _get_values(values, skipna, fill_value=None, fill_value_typ=None,
isfinite=False, copy=True, mask=None):
""" utility to get the values view, mask, dtype
if necessary copy and mask using the specified fill_value
copy = True will force the copy
"""
if is_datetime64tz_dtype(values):
# com.values_from_object returns M8[ns] dtype instead of tz-aware,
# so this case must be handled separately from the rest
dtype = values.dtype
values = getattr(values, "_values", values)
else:
values = com.values_from_object(values)
dtype = values.dtype
if mask is None:
if isfinite:
mask = _isfinite(values)
else:
mask = isna(values)
if is_datetime_or_timedelta_dtype(values) or is_datetime64tz_dtype(values):
# changing timedelta64/datetime64 to int64 needs to happen after
# finding `mask` above
values = getattr(values, "asi8", values)
values = values.view(np.int64)
dtype_ok = _na_ok_dtype(dtype)
# get our fill value (in case we need to provide an alternative
# dtype for it)
fill_value = _get_fill_value(dtype, fill_value=fill_value,
fill_value_typ=fill_value_typ)
if skipna:
if copy:
values = values.copy()
if dtype_ok:
np.putmask(values, mask, fill_value)
# promote if needed
else:
values, changed = maybe_upcast_putmask(values, mask, fill_value)
elif copy:
values = values.copy()
# return a platform independent precision dtype
dtype_max = dtype
if is_integer_dtype(dtype) or is_bool_dtype(dtype):
dtype_max = np.int64
elif is_float_dtype(dtype):
dtype_max = np.float64
return values, mask, dtype, dtype_max, fill_value | [
"utility",
"to",
"get",
"the",
"values",
"view",
"mask",
"dtype",
"if",
"necessary",
"copy",
"and",
"mask",
"using",
"the",
"specified",
"fill_value",
"copy",
"=",
"True",
"will",
"force",
"the",
"copy"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L203-L258 | [
"def",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"fill_value",
"=",
"None",
",",
"fill_value_typ",
"=",
"None",
",",
"isfinite",
"=",
"False",
",",
"copy",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"if",
"is_datetime64tz_dtype",
"(",
"values",
")",
":",
"# com.values_from_object returns M8[ns] dtype instead of tz-aware,",
"# so this case must be handled separately from the rest",
"dtype",
"=",
"values",
".",
"dtype",
"values",
"=",
"getattr",
"(",
"values",
",",
"\"_values\"",
",",
"values",
")",
"else",
":",
"values",
"=",
"com",
".",
"values_from_object",
"(",
"values",
")",
"dtype",
"=",
"values",
".",
"dtype",
"if",
"mask",
"is",
"None",
":",
"if",
"isfinite",
":",
"mask",
"=",
"_isfinite",
"(",
"values",
")",
"else",
":",
"mask",
"=",
"isna",
"(",
"values",
")",
"if",
"is_datetime_or_timedelta_dtype",
"(",
"values",
")",
"or",
"is_datetime64tz_dtype",
"(",
"values",
")",
":",
"# changing timedelta64/datetime64 to int64 needs to happen after",
"# finding `mask` above",
"values",
"=",
"getattr",
"(",
"values",
",",
"\"asi8\"",
",",
"values",
")",
"values",
"=",
"values",
".",
"view",
"(",
"np",
".",
"int64",
")",
"dtype_ok",
"=",
"_na_ok_dtype",
"(",
"dtype",
")",
"# get our fill value (in case we need to provide an alternative",
"# dtype for it)",
"fill_value",
"=",
"_get_fill_value",
"(",
"dtype",
",",
"fill_value",
"=",
"fill_value",
",",
"fill_value_typ",
"=",
"fill_value_typ",
")",
"if",
"skipna",
":",
"if",
"copy",
":",
"values",
"=",
"values",
".",
"copy",
"(",
")",
"if",
"dtype_ok",
":",
"np",
".",
"putmask",
"(",
"values",
",",
"mask",
",",
"fill_value",
")",
"# promote if needed",
"else",
":",
"values",
",",
"changed",
"=",
"maybe_upcast_putmask",
"(",
"values",
",",
"mask",
",",
"fill_value",
")",
"elif",
"copy",
":",
"values",
"=",
"values",
".",
"copy",
"(",
")",
"# return a platform independent precision dtype",
"dtype_max",
"=",
"dtype",
"if",
"is_integer_dtype",
"(",
"dtype",
")",
"or",
"is_bool_dtype",
"(",
"dtype",
")",
":",
"dtype_max",
"=",
"np",
".",
"int64",
"elif",
"is_float_dtype",
"(",
"dtype",
")",
":",
"dtype_max",
"=",
"np",
".",
"float64",
"return",
"values",
",",
"mask",
",",
"dtype",
",",
"dtype_max",
",",
"fill_value"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _wrap_results | wrap our results if needed | pandas/core/nanops.py | def _wrap_results(result, dtype, fill_value=None):
""" wrap our results if needed """
if is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
if fill_value is None:
# GH#24293
fill_value = iNaT
if not isinstance(result, np.ndarray):
tz = getattr(dtype, 'tz', None)
assert not isna(fill_value), "Expected non-null fill_value"
if result == fill_value:
result = np.nan
result = tslibs.Timestamp(result, tz=tz)
else:
result = result.view(dtype)
elif is_timedelta64_dtype(dtype):
if not isinstance(result, np.ndarray):
if result == fill_value:
result = np.nan
# raise if we have a timedelta64[ns] which is too large
if np.fabs(result) > _int64_max:
raise ValueError("overflow in timedelta operation")
result = tslibs.Timedelta(result, unit='ns')
else:
result = result.astype('i8').view(dtype)
return result | def _wrap_results(result, dtype, fill_value=None):
""" wrap our results if needed """
if is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
if fill_value is None:
# GH#24293
fill_value = iNaT
if not isinstance(result, np.ndarray):
tz = getattr(dtype, 'tz', None)
assert not isna(fill_value), "Expected non-null fill_value"
if result == fill_value:
result = np.nan
result = tslibs.Timestamp(result, tz=tz)
else:
result = result.view(dtype)
elif is_timedelta64_dtype(dtype):
if not isinstance(result, np.ndarray):
if result == fill_value:
result = np.nan
# raise if we have a timedelta64[ns] which is too large
if np.fabs(result) > _int64_max:
raise ValueError("overflow in timedelta operation")
result = tslibs.Timedelta(result, unit='ns')
else:
result = result.astype('i8').view(dtype)
return result | [
"wrap",
"our",
"results",
"if",
"needed"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L276-L304 | [
"def",
"_wrap_results",
"(",
"result",
",",
"dtype",
",",
"fill_value",
"=",
"None",
")",
":",
"if",
"is_datetime64_dtype",
"(",
"dtype",
")",
"or",
"is_datetime64tz_dtype",
"(",
"dtype",
")",
":",
"if",
"fill_value",
"is",
"None",
":",
"# GH#24293",
"fill_value",
"=",
"iNaT",
"if",
"not",
"isinstance",
"(",
"result",
",",
"np",
".",
"ndarray",
")",
":",
"tz",
"=",
"getattr",
"(",
"dtype",
",",
"'tz'",
",",
"None",
")",
"assert",
"not",
"isna",
"(",
"fill_value",
")",
",",
"\"Expected non-null fill_value\"",
"if",
"result",
"==",
"fill_value",
":",
"result",
"=",
"np",
".",
"nan",
"result",
"=",
"tslibs",
".",
"Timestamp",
"(",
"result",
",",
"tz",
"=",
"tz",
")",
"else",
":",
"result",
"=",
"result",
".",
"view",
"(",
"dtype",
")",
"elif",
"is_timedelta64_dtype",
"(",
"dtype",
")",
":",
"if",
"not",
"isinstance",
"(",
"result",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"result",
"==",
"fill_value",
":",
"result",
"=",
"np",
".",
"nan",
"# raise if we have a timedelta64[ns] which is too large",
"if",
"np",
".",
"fabs",
"(",
"result",
")",
">",
"_int64_max",
":",
"raise",
"ValueError",
"(",
"\"overflow in timedelta operation\"",
")",
"result",
"=",
"tslibs",
".",
"Timedelta",
"(",
"result",
",",
"unit",
"=",
"'ns'",
")",
"else",
":",
"result",
"=",
"result",
".",
"astype",
"(",
"'i8'",
")",
".",
"view",
"(",
"dtype",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _na_for_min_count | Return the missing value for `values`
Parameters
----------
values : ndarray
axis : int or None
axis for the reduction
Returns
-------
result : scalar or ndarray
For 1-D values, returns a scalar of the correct missing type.
For 2-D values, returns a 1-D array where each element is missing. | pandas/core/nanops.py | def _na_for_min_count(values, axis):
"""Return the missing value for `values`
Parameters
----------
values : ndarray
axis : int or None
axis for the reduction
Returns
-------
result : scalar or ndarray
For 1-D values, returns a scalar of the correct missing type.
For 2-D values, returns a 1-D array where each element is missing.
"""
# we either return np.nan or pd.NaT
if is_numeric_dtype(values):
values = values.astype('float64')
fill_value = na_value_for_dtype(values.dtype)
if values.ndim == 1:
return fill_value
else:
result_shape = (values.shape[:axis] +
values.shape[axis + 1:])
result = np.empty(result_shape, dtype=values.dtype)
result.fill(fill_value)
return result | def _na_for_min_count(values, axis):
"""Return the missing value for `values`
Parameters
----------
values : ndarray
axis : int or None
axis for the reduction
Returns
-------
result : scalar or ndarray
For 1-D values, returns a scalar of the correct missing type.
For 2-D values, returns a 1-D array where each element is missing.
"""
# we either return np.nan or pd.NaT
if is_numeric_dtype(values):
values = values.astype('float64')
fill_value = na_value_for_dtype(values.dtype)
if values.ndim == 1:
return fill_value
else:
result_shape = (values.shape[:axis] +
values.shape[axis + 1:])
result = np.empty(result_shape, dtype=values.dtype)
result.fill(fill_value)
return result | [
"Return",
"the",
"missing",
"value",
"for",
"values"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L307-L334 | [
"def",
"_na_for_min_count",
"(",
"values",
",",
"axis",
")",
":",
"# we either return np.nan or pd.NaT",
"if",
"is_numeric_dtype",
"(",
"values",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"'float64'",
")",
"fill_value",
"=",
"na_value_for_dtype",
"(",
"values",
".",
"dtype",
")",
"if",
"values",
".",
"ndim",
"==",
"1",
":",
"return",
"fill_value",
"else",
":",
"result_shape",
"=",
"(",
"values",
".",
"shape",
"[",
":",
"axis",
"]",
"+",
"values",
".",
"shape",
"[",
"axis",
"+",
"1",
":",
"]",
")",
"result",
"=",
"np",
".",
"empty",
"(",
"result_shape",
",",
"dtype",
"=",
"values",
".",
"dtype",
")",
"result",
".",
"fill",
"(",
"fill_value",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanany | Check if any elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis : int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : bool
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2])
>>> nanops.nanany(s)
True
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([np.nan])
>>> nanops.nanany(s)
False | pandas/core/nanops.py | def nanany(values, axis=None, skipna=True, mask=None):
"""
Check if any elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis : int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : bool
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2])
>>> nanops.nanany(s)
True
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([np.nan])
>>> nanops.nanany(s)
False
"""
values, mask, dtype, _, _ = _get_values(values, skipna, False, copy=skipna,
mask=mask)
return values.any(axis) | def nanany(values, axis=None, skipna=True, mask=None):
"""
Check if any elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis : int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : bool
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2])
>>> nanops.nanany(s)
True
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([np.nan])
>>> nanops.nanany(s)
False
"""
values, mask, dtype, _, _ = _get_values(values, skipna, False, copy=skipna,
mask=mask)
return values.any(axis) | [
"Check",
"if",
"any",
"elements",
"along",
"an",
"axis",
"evaluate",
"to",
"True",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L337-L367 | [
"def",
"nanany",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"values",
",",
"mask",
",",
"dtype",
",",
"_",
",",
"_",
"=",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"False",
",",
"copy",
"=",
"skipna",
",",
"mask",
"=",
"mask",
")",
"return",
"values",
".",
"any",
"(",
"axis",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanall | Check if all elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : bool
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nanall(s)
True
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 0])
>>> nanops.nanall(s)
False | pandas/core/nanops.py | def nanall(values, axis=None, skipna=True, mask=None):
"""
Check if all elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : bool
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nanall(s)
True
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 0])
>>> nanops.nanall(s)
False
"""
values, mask, dtype, _, _ = _get_values(values, skipna, True, copy=skipna,
mask=mask)
return values.all(axis) | def nanall(values, axis=None, skipna=True, mask=None):
"""
Check if all elements along an axis evaluate to True.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : bool
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nanall(s)
True
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 0])
>>> nanops.nanall(s)
False
"""
values, mask, dtype, _, _ = _get_values(values, skipna, True, copy=skipna,
mask=mask)
return values.all(axis) | [
"Check",
"if",
"all",
"elements",
"along",
"an",
"axis",
"evaluate",
"to",
"True",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L370-L400 | [
"def",
"nanall",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"values",
",",
"mask",
",",
"dtype",
",",
"_",
",",
"_",
"=",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"True",
",",
"copy",
"=",
"skipna",
",",
"mask",
"=",
"mask",
")",
"return",
"values",
".",
"all",
"(",
"axis",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nansum | Sum the elements along an axis ignoring NaNs
Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
min_count: int, default 0
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : dtype
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nansum(s)
3.0 | pandas/core/nanops.py | def nansum(values, axis=None, skipna=True, min_count=0, mask=None):
"""
Sum the elements along an axis ignoring NaNs
Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
min_count: int, default 0
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : dtype
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nansum(s)
3.0
"""
values, mask, dtype, dtype_max, _ = _get_values(values,
skipna, 0, mask=mask)
dtype_sum = dtype_max
if is_float_dtype(dtype):
dtype_sum = dtype
elif is_timedelta64_dtype(dtype):
dtype_sum = np.float64
the_sum = values.sum(axis, dtype=dtype_sum)
the_sum = _maybe_null_out(the_sum, axis, mask, min_count=min_count)
return _wrap_results(the_sum, dtype) | def nansum(values, axis=None, skipna=True, min_count=0, mask=None):
"""
Sum the elements along an axis ignoring NaNs
Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
min_count: int, default 0
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : dtype
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nansum(s)
3.0
"""
values, mask, dtype, dtype_max, _ = _get_values(values,
skipna, 0, mask=mask)
dtype_sum = dtype_max
if is_float_dtype(dtype):
dtype_sum = dtype
elif is_timedelta64_dtype(dtype):
dtype_sum = np.float64
the_sum = values.sum(axis, dtype=dtype_sum)
the_sum = _maybe_null_out(the_sum, axis, mask, min_count=min_count)
return _wrap_results(the_sum, dtype) | [
"Sum",
"the",
"elements",
"along",
"an",
"axis",
"ignoring",
"NaNs"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L404-L438 | [
"def",
"nansum",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"min_count",
"=",
"0",
",",
"mask",
"=",
"None",
")",
":",
"values",
",",
"mask",
",",
"dtype",
",",
"dtype_max",
",",
"_",
"=",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"0",
",",
"mask",
"=",
"mask",
")",
"dtype_sum",
"=",
"dtype_max",
"if",
"is_float_dtype",
"(",
"dtype",
")",
":",
"dtype_sum",
"=",
"dtype",
"elif",
"is_timedelta64_dtype",
"(",
"dtype",
")",
":",
"dtype_sum",
"=",
"np",
".",
"float64",
"the_sum",
"=",
"values",
".",
"sum",
"(",
"axis",
",",
"dtype",
"=",
"dtype_sum",
")",
"the_sum",
"=",
"_maybe_null_out",
"(",
"the_sum",
",",
"axis",
",",
"mask",
",",
"min_count",
"=",
"min_count",
")",
"return",
"_wrap_results",
"(",
"the_sum",
",",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanmean | Compute the mean of the element along an axis ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nanmean(s)
1.5 | pandas/core/nanops.py | def nanmean(values, axis=None, skipna=True, mask=None):
"""
Compute the mean of the element along an axis ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nanmean(s)
1.5
"""
values, mask, dtype, dtype_max, _ = _get_values(
values, skipna, 0, mask=mask)
dtype_sum = dtype_max
dtype_count = np.float64
if (is_integer_dtype(dtype) or is_timedelta64_dtype(dtype) or
is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype)):
dtype_sum = np.float64
elif is_float_dtype(dtype):
dtype_sum = dtype
dtype_count = dtype
count = _get_counts(mask, axis, dtype=dtype_count)
the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))
if axis is not None and getattr(the_sum, 'ndim', False):
with np.errstate(all="ignore"):
# suppress division by zero warnings
the_mean = the_sum / count
ct_mask = count == 0
if ct_mask.any():
the_mean[ct_mask] = np.nan
else:
the_mean = the_sum / count if count > 0 else np.nan
return _wrap_results(the_mean, dtype) | def nanmean(values, axis=None, skipna=True, mask=None):
"""
Compute the mean of the element along an axis ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, np.nan])
>>> nanops.nanmean(s)
1.5
"""
values, mask, dtype, dtype_max, _ = _get_values(
values, skipna, 0, mask=mask)
dtype_sum = dtype_max
dtype_count = np.float64
if (is_integer_dtype(dtype) or is_timedelta64_dtype(dtype) or
is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype)):
dtype_sum = np.float64
elif is_float_dtype(dtype):
dtype_sum = dtype
dtype_count = dtype
count = _get_counts(mask, axis, dtype=dtype_count)
the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))
if axis is not None and getattr(the_sum, 'ndim', False):
with np.errstate(all="ignore"):
# suppress division by zero warnings
the_mean = the_sum / count
ct_mask = count == 0
if ct_mask.any():
the_mean[ct_mask] = np.nan
else:
the_mean = the_sum / count if count > 0 else np.nan
return _wrap_results(the_mean, dtype) | [
"Compute",
"the",
"mean",
"of",
"the",
"element",
"along",
"an",
"axis",
"ignoring",
"NaNs"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L443-L491 | [
"def",
"nanmean",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"values",
",",
"mask",
",",
"dtype",
",",
"dtype_max",
",",
"_",
"=",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"0",
",",
"mask",
"=",
"mask",
")",
"dtype_sum",
"=",
"dtype_max",
"dtype_count",
"=",
"np",
".",
"float64",
"if",
"(",
"is_integer_dtype",
"(",
"dtype",
")",
"or",
"is_timedelta64_dtype",
"(",
"dtype",
")",
"or",
"is_datetime64_dtype",
"(",
"dtype",
")",
"or",
"is_datetime64tz_dtype",
"(",
"dtype",
")",
")",
":",
"dtype_sum",
"=",
"np",
".",
"float64",
"elif",
"is_float_dtype",
"(",
"dtype",
")",
":",
"dtype_sum",
"=",
"dtype",
"dtype_count",
"=",
"dtype",
"count",
"=",
"_get_counts",
"(",
"mask",
",",
"axis",
",",
"dtype",
"=",
"dtype_count",
")",
"the_sum",
"=",
"_ensure_numeric",
"(",
"values",
".",
"sum",
"(",
"axis",
",",
"dtype",
"=",
"dtype_sum",
")",
")",
"if",
"axis",
"is",
"not",
"None",
"and",
"getattr",
"(",
"the_sum",
",",
"'ndim'",
",",
"False",
")",
":",
"with",
"np",
".",
"errstate",
"(",
"all",
"=",
"\"ignore\"",
")",
":",
"# suppress division by zero warnings",
"the_mean",
"=",
"the_sum",
"/",
"count",
"ct_mask",
"=",
"count",
"==",
"0",
"if",
"ct_mask",
".",
"any",
"(",
")",
":",
"the_mean",
"[",
"ct_mask",
"]",
"=",
"np",
".",
"nan",
"else",
":",
"the_mean",
"=",
"the_sum",
"/",
"count",
"if",
"count",
">",
"0",
"else",
"np",
".",
"nan",
"return",
"_wrap_results",
"(",
"the_mean",
",",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanmedian | Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 2])
>>> nanops.nanmedian(s)
2.0 | pandas/core/nanops.py | def nanmedian(values, axis=None, skipna=True, mask=None):
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 2])
>>> nanops.nanmedian(s)
2.0
"""
def get_median(x):
mask = notna(x)
if not skipna and not mask.all():
return np.nan
return np.nanmedian(x[mask])
values, mask, dtype, dtype_max, _ = _get_values(values, skipna, mask=mask)
if not is_float_dtype(values):
values = values.astype('f8')
values[mask] = np.nan
if axis is None:
values = values.ravel()
notempty = values.size
# an array from a frame
if values.ndim > 1:
# there's a non-empty array to apply over otherwise numpy raises
if notempty:
if not skipna:
return _wrap_results(
np.apply_along_axis(get_median, axis, values), dtype)
# fastpath for the skipna case
return _wrap_results(np.nanmedian(values, axis), dtype)
# must return the correct shape, but median is not defined for the
# empty set so return nans of shape "everything but the passed axis"
# since "axis" is where the reduction would occur if we had a nonempty
# array
shp = np.array(values.shape)
dims = np.arange(values.ndim)
ret = np.empty(shp[dims != axis])
ret.fill(np.nan)
return _wrap_results(ret, dtype)
# otherwise return a scalar value
return _wrap_results(get_median(values) if notempty else np.nan, dtype) | def nanmedian(values, axis=None, skipna=True, mask=None):
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 2])
>>> nanops.nanmedian(s)
2.0
"""
def get_median(x):
mask = notna(x)
if not skipna and not mask.all():
return np.nan
return np.nanmedian(x[mask])
values, mask, dtype, dtype_max, _ = _get_values(values, skipna, mask=mask)
if not is_float_dtype(values):
values = values.astype('f8')
values[mask] = np.nan
if axis is None:
values = values.ravel()
notempty = values.size
# an array from a frame
if values.ndim > 1:
# there's a non-empty array to apply over otherwise numpy raises
if notempty:
if not skipna:
return _wrap_results(
np.apply_along_axis(get_median, axis, values), dtype)
# fastpath for the skipna case
return _wrap_results(np.nanmedian(values, axis), dtype)
# must return the correct shape, but median is not defined for the
# empty set so return nans of shape "everything but the passed axis"
# since "axis" is where the reduction would occur if we had a nonempty
# array
shp = np.array(values.shape)
dims = np.arange(values.ndim)
ret = np.empty(shp[dims != axis])
ret.fill(np.nan)
return _wrap_results(ret, dtype)
# otherwise return a scalar value
return _wrap_results(get_median(values) if notempty else np.nan, dtype) | [
"Parameters",
"----------",
"values",
":",
"ndarray",
"axis",
":",
"int",
"optional",
"skipna",
":",
"bool",
"default",
"True",
"mask",
":",
"ndarray",
"[",
"bool",
"]",
"optional",
"nan",
"-",
"mask",
"if",
"known"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L496-L558 | [
"def",
"nanmedian",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"def",
"get_median",
"(",
"x",
")",
":",
"mask",
"=",
"notna",
"(",
"x",
")",
"if",
"not",
"skipna",
"and",
"not",
"mask",
".",
"all",
"(",
")",
":",
"return",
"np",
".",
"nan",
"return",
"np",
".",
"nanmedian",
"(",
"x",
"[",
"mask",
"]",
")",
"values",
",",
"mask",
",",
"dtype",
",",
"dtype_max",
",",
"_",
"=",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"mask",
"=",
"mask",
")",
"if",
"not",
"is_float_dtype",
"(",
"values",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"'f8'",
")",
"values",
"[",
"mask",
"]",
"=",
"np",
".",
"nan",
"if",
"axis",
"is",
"None",
":",
"values",
"=",
"values",
".",
"ravel",
"(",
")",
"notempty",
"=",
"values",
".",
"size",
"# an array from a frame",
"if",
"values",
".",
"ndim",
">",
"1",
":",
"# there's a non-empty array to apply over otherwise numpy raises",
"if",
"notempty",
":",
"if",
"not",
"skipna",
":",
"return",
"_wrap_results",
"(",
"np",
".",
"apply_along_axis",
"(",
"get_median",
",",
"axis",
",",
"values",
")",
",",
"dtype",
")",
"# fastpath for the skipna case",
"return",
"_wrap_results",
"(",
"np",
".",
"nanmedian",
"(",
"values",
",",
"axis",
")",
",",
"dtype",
")",
"# must return the correct shape, but median is not defined for the",
"# empty set so return nans of shape \"everything but the passed axis\"",
"# since \"axis\" is where the reduction would occur if we had a nonempty",
"# array",
"shp",
"=",
"np",
".",
"array",
"(",
"values",
".",
"shape",
")",
"dims",
"=",
"np",
".",
"arange",
"(",
"values",
".",
"ndim",
")",
"ret",
"=",
"np",
".",
"empty",
"(",
"shp",
"[",
"dims",
"!=",
"axis",
"]",
")",
"ret",
".",
"fill",
"(",
"np",
".",
"nan",
")",
"return",
"_wrap_results",
"(",
"ret",
",",
"dtype",
")",
"# otherwise return a scalar value",
"return",
"_wrap_results",
"(",
"get_median",
"(",
"values",
")",
"if",
"notempty",
"else",
"np",
".",
"nan",
",",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanstd | Compute the standard deviation along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nanstd(s)
1.0 | pandas/core/nanops.py | def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the standard deviation along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nanstd(s)
1.0
"""
result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof,
mask=mask))
return _wrap_results(result, values.dtype) | def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the standard deviation along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nanstd(s)
1.0
"""
result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof,
mask=mask))
return _wrap_results(result, values.dtype) | [
"Compute",
"the",
"standard",
"deviation",
"along",
"given",
"axis",
"while",
"ignoring",
"NaNs"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L581-L611 | [
"def",
"nanstd",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"ddof",
"=",
"1",
",",
"mask",
"=",
"None",
")",
":",
"result",
"=",
"np",
".",
"sqrt",
"(",
"nanvar",
"(",
"values",
",",
"axis",
"=",
"axis",
",",
"skipna",
"=",
"skipna",
",",
"ddof",
"=",
"ddof",
",",
"mask",
"=",
"mask",
")",
")",
"return",
"_wrap_results",
"(",
"result",
",",
"values",
".",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanvar | Compute the variance along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nanvar(s)
1.0 | pandas/core/nanops.py | def nanvar(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the variance along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nanvar(s)
1.0
"""
values = com.values_from_object(values)
dtype = values.dtype
if mask is None:
mask = isna(values)
if is_any_int_dtype(values):
values = values.astype('f8')
values[mask] = np.nan
if is_float_dtype(values):
count, d = _get_counts_nanvar(mask, axis, ddof, values.dtype)
else:
count, d = _get_counts_nanvar(mask, axis, ddof)
if skipna:
values = values.copy()
np.putmask(values, mask, 0)
# xref GH10242
# Compute variance via two-pass algorithm, which is stable against
# cancellation errors and relatively accurate for small numbers of
# observations.
#
# See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
avg = _ensure_numeric(values.sum(axis=axis, dtype=np.float64)) / count
if axis is not None:
avg = np.expand_dims(avg, axis)
sqr = _ensure_numeric((avg - values) ** 2)
np.putmask(sqr, mask, 0)
result = sqr.sum(axis=axis, dtype=np.float64) / d
# Return variance as np.float64 (the datatype used in the accumulator),
# unless we were dealing with a float array, in which case use the same
# precision as the original values array.
if is_float_dtype(dtype):
result = result.astype(dtype)
return _wrap_results(result, values.dtype) | def nanvar(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the variance along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nanvar(s)
1.0
"""
values = com.values_from_object(values)
dtype = values.dtype
if mask is None:
mask = isna(values)
if is_any_int_dtype(values):
values = values.astype('f8')
values[mask] = np.nan
if is_float_dtype(values):
count, d = _get_counts_nanvar(mask, axis, ddof, values.dtype)
else:
count, d = _get_counts_nanvar(mask, axis, ddof)
if skipna:
values = values.copy()
np.putmask(values, mask, 0)
# xref GH10242
# Compute variance via two-pass algorithm, which is stable against
# cancellation errors and relatively accurate for small numbers of
# observations.
#
# See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
avg = _ensure_numeric(values.sum(axis=axis, dtype=np.float64)) / count
if axis is not None:
avg = np.expand_dims(avg, axis)
sqr = _ensure_numeric((avg - values) ** 2)
np.putmask(sqr, mask, 0)
result = sqr.sum(axis=axis, dtype=np.float64) / d
# Return variance as np.float64 (the datatype used in the accumulator),
# unless we were dealing with a float array, in which case use the same
# precision as the original values array.
if is_float_dtype(dtype):
result = result.astype(dtype)
return _wrap_results(result, values.dtype) | [
"Compute",
"the",
"variance",
"along",
"given",
"axis",
"while",
"ignoring",
"NaNs"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L616-L679 | [
"def",
"nanvar",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"ddof",
"=",
"1",
",",
"mask",
"=",
"None",
")",
":",
"values",
"=",
"com",
".",
"values_from_object",
"(",
"values",
")",
"dtype",
"=",
"values",
".",
"dtype",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"isna",
"(",
"values",
")",
"if",
"is_any_int_dtype",
"(",
"values",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"'f8'",
")",
"values",
"[",
"mask",
"]",
"=",
"np",
".",
"nan",
"if",
"is_float_dtype",
"(",
"values",
")",
":",
"count",
",",
"d",
"=",
"_get_counts_nanvar",
"(",
"mask",
",",
"axis",
",",
"ddof",
",",
"values",
".",
"dtype",
")",
"else",
":",
"count",
",",
"d",
"=",
"_get_counts_nanvar",
"(",
"mask",
",",
"axis",
",",
"ddof",
")",
"if",
"skipna",
":",
"values",
"=",
"values",
".",
"copy",
"(",
")",
"np",
".",
"putmask",
"(",
"values",
",",
"mask",
",",
"0",
")",
"# xref GH10242",
"# Compute variance via two-pass algorithm, which is stable against",
"# cancellation errors and relatively accurate for small numbers of",
"# observations.",
"#",
"# See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance",
"avg",
"=",
"_ensure_numeric",
"(",
"values",
".",
"sum",
"(",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
")",
"/",
"count",
"if",
"axis",
"is",
"not",
"None",
":",
"avg",
"=",
"np",
".",
"expand_dims",
"(",
"avg",
",",
"axis",
")",
"sqr",
"=",
"_ensure_numeric",
"(",
"(",
"avg",
"-",
"values",
")",
"**",
"2",
")",
"np",
".",
"putmask",
"(",
"sqr",
",",
"mask",
",",
"0",
")",
"result",
"=",
"sqr",
".",
"sum",
"(",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"/",
"d",
"# Return variance as np.float64 (the datatype used in the accumulator),",
"# unless we were dealing with a float array, in which case use the same",
"# precision as the original values array.",
"if",
"is_float_dtype",
"(",
"dtype",
")",
":",
"result",
"=",
"result",
".",
"astype",
"(",
"dtype",
")",
"return",
"_wrap_results",
"(",
"result",
",",
"values",
".",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nansem | Compute the standard error in the mean along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nansem(s)
0.5773502691896258 | pandas/core/nanops.py | def nansem(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the standard error in the mean along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nansem(s)
0.5773502691896258
"""
# This checks if non-numeric-like data is passed with numeric_only=False
# and raises a TypeError otherwise
nanvar(values, axis, skipna, ddof=ddof, mask=mask)
if mask is None:
mask = isna(values)
if not is_float_dtype(values.dtype):
values = values.astype('f8')
count, _ = _get_counts_nanvar(mask, axis, ddof, values.dtype)
var = nanvar(values, axis, skipna, ddof=ddof)
return np.sqrt(var) / np.sqrt(count) | def nansem(values, axis=None, skipna=True, ddof=1, mask=None):
"""
Compute the standard error in the mean along given axis while ignoring NaNs
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 2, 3])
>>> nanops.nansem(s)
0.5773502691896258
"""
# This checks if non-numeric-like data is passed with numeric_only=False
# and raises a TypeError otherwise
nanvar(values, axis, skipna, ddof=ddof, mask=mask)
if mask is None:
mask = isna(values)
if not is_float_dtype(values.dtype):
values = values.astype('f8')
count, _ = _get_counts_nanvar(mask, axis, ddof, values.dtype)
var = nanvar(values, axis, skipna, ddof=ddof)
return np.sqrt(var) / np.sqrt(count) | [
"Compute",
"the",
"standard",
"error",
"in",
"the",
"mean",
"along",
"given",
"axis",
"while",
"ignoring",
"NaNs"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L683-L723 | [
"def",
"nansem",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"ddof",
"=",
"1",
",",
"mask",
"=",
"None",
")",
":",
"# This checks if non-numeric-like data is passed with numeric_only=False",
"# and raises a TypeError otherwise",
"nanvar",
"(",
"values",
",",
"axis",
",",
"skipna",
",",
"ddof",
"=",
"ddof",
",",
"mask",
"=",
"mask",
")",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"isna",
"(",
"values",
")",
"if",
"not",
"is_float_dtype",
"(",
"values",
".",
"dtype",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"'f8'",
")",
"count",
",",
"_",
"=",
"_get_counts_nanvar",
"(",
"mask",
",",
"axis",
",",
"ddof",
",",
"values",
".",
"dtype",
")",
"var",
"=",
"nanvar",
"(",
"values",
",",
"axis",
",",
"skipna",
",",
"ddof",
"=",
"ddof",
")",
"return",
"np",
".",
"sqrt",
"(",
"var",
")",
"/",
"np",
".",
"sqrt",
"(",
"count",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanargmax | Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
--------
result : int
The index of max value in specified axis or -1 in the NA case
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan, 4])
>>> nanops.nanargmax(s)
4 | pandas/core/nanops.py | def nanargmax(values, axis=None, skipna=True, mask=None):
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
--------
result : int
The index of max value in specified axis or -1 in the NA case
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan, 4])
>>> nanops.nanargmax(s)
4
"""
values, mask, dtype, _, _ = _get_values(
values, skipna, fill_value_typ='-inf', mask=mask)
result = values.argmax(axis)
result = _maybe_arg_null_out(result, axis, mask, skipna)
return result | def nanargmax(values, axis=None, skipna=True, mask=None):
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
--------
result : int
The index of max value in specified axis or -1 in the NA case
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan, 4])
>>> nanops.nanargmax(s)
4
"""
values, mask, dtype, _, _ = _get_values(
values, skipna, fill_value_typ='-inf', mask=mask)
result = values.argmax(axis)
result = _maybe_arg_null_out(result, axis, mask, skipna)
return result | [
"Parameters",
"----------",
"values",
":",
"ndarray",
"axis",
":",
"int",
"optional",
"skipna",
":",
"bool",
"default",
"True",
"mask",
":",
"ndarray",
"[",
"bool",
"]",
"optional",
"nan",
"-",
"mask",
"if",
"known"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L756-L782 | [
"def",
"nanargmax",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"values",
",",
"mask",
",",
"dtype",
",",
"_",
",",
"_",
"=",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"fill_value_typ",
"=",
"'-inf'",
",",
"mask",
"=",
"mask",
")",
"result",
"=",
"values",
".",
"argmax",
"(",
"axis",
")",
"result",
"=",
"_maybe_arg_null_out",
"(",
"result",
",",
"axis",
",",
"mask",
",",
"skipna",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanargmin | Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
--------
result : int
The index of min value in specified axis or -1 in the NA case
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan, 4])
>>> nanops.nanargmin(s)
0 | pandas/core/nanops.py | def nanargmin(values, axis=None, skipna=True, mask=None):
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
--------
result : int
The index of min value in specified axis or -1 in the NA case
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan, 4])
>>> nanops.nanargmin(s)
0
"""
values, mask, dtype, _, _ = _get_values(
values, skipna, fill_value_typ='+inf', mask=mask)
result = values.argmin(axis)
result = _maybe_arg_null_out(result, axis, mask, skipna)
return result | def nanargmin(values, axis=None, skipna=True, mask=None):
"""
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
--------
result : int
The index of min value in specified axis or -1 in the NA case
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan, 4])
>>> nanops.nanargmin(s)
0
"""
values, mask, dtype, _, _ = _get_values(
values, skipna, fill_value_typ='+inf', mask=mask)
result = values.argmin(axis)
result = _maybe_arg_null_out(result, axis, mask, skipna)
return result | [
"Parameters",
"----------",
"values",
":",
"ndarray",
"axis",
":",
"int",
"optional",
"skipna",
":",
"bool",
"default",
"True",
"mask",
":",
"ndarray",
"[",
"bool",
"]",
"optional",
"nan",
"-",
"mask",
"if",
"known"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L786-L812 | [
"def",
"nanargmin",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"values",
",",
"mask",
",",
"dtype",
",",
"_",
",",
"_",
"=",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"fill_value_typ",
"=",
"'+inf'",
",",
"mask",
"=",
"mask",
")",
"result",
"=",
"values",
".",
"argmin",
"(",
"axis",
")",
"result",
"=",
"_maybe_arg_null_out",
"(",
"result",
",",
"axis",
",",
"mask",
",",
"skipna",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanskew | Compute the sample skewness.
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G1. The algorithm computes this coefficient directly
from the second and third central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1,np.nan, 1, 2])
>>> nanops.nanskew(s)
1.7320508075688787 | pandas/core/nanops.py | def nanskew(values, axis=None, skipna=True, mask=None):
""" Compute the sample skewness.
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G1. The algorithm computes this coefficient directly
from the second and third central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1,np.nan, 1, 2])
>>> nanops.nanskew(s)
1.7320508075688787
"""
values = com.values_from_object(values)
if mask is None:
mask = isna(values)
if not is_float_dtype(values.dtype):
values = values.astype('f8')
count = _get_counts(mask, axis)
else:
count = _get_counts(mask, axis, dtype=values.dtype)
if skipna:
values = values.copy()
np.putmask(values, mask, 0)
mean = values.sum(axis, dtype=np.float64) / count
if axis is not None:
mean = np.expand_dims(mean, axis)
adjusted = values - mean
if skipna:
np.putmask(adjusted, mask, 0)
adjusted2 = adjusted ** 2
adjusted3 = adjusted2 * adjusted
m2 = adjusted2.sum(axis, dtype=np.float64)
m3 = adjusted3.sum(axis, dtype=np.float64)
# floating point error
#
# #18044 in _libs/windows.pyx calc_skew follow this behavior
# to fix the fperr to treat m2 <1e-14 as zero
m2 = _zero_out_fperr(m2)
m3 = _zero_out_fperr(m3)
with np.errstate(invalid='ignore', divide='ignore'):
result = (count * (count - 1) ** 0.5 / (count - 2)) * (m3 / m2 ** 1.5)
dtype = values.dtype
if is_float_dtype(dtype):
result = result.astype(dtype)
if isinstance(result, np.ndarray):
result = np.where(m2 == 0, 0, result)
result[count < 3] = np.nan
return result
else:
result = 0 if m2 == 0 else result
if count < 3:
return np.nan
return result | def nanskew(values, axis=None, skipna=True, mask=None):
""" Compute the sample skewness.
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G1. The algorithm computes this coefficient directly
from the second and third central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1,np.nan, 1, 2])
>>> nanops.nanskew(s)
1.7320508075688787
"""
values = com.values_from_object(values)
if mask is None:
mask = isna(values)
if not is_float_dtype(values.dtype):
values = values.astype('f8')
count = _get_counts(mask, axis)
else:
count = _get_counts(mask, axis, dtype=values.dtype)
if skipna:
values = values.copy()
np.putmask(values, mask, 0)
mean = values.sum(axis, dtype=np.float64) / count
if axis is not None:
mean = np.expand_dims(mean, axis)
adjusted = values - mean
if skipna:
np.putmask(adjusted, mask, 0)
adjusted2 = adjusted ** 2
adjusted3 = adjusted2 * adjusted
m2 = adjusted2.sum(axis, dtype=np.float64)
m3 = adjusted3.sum(axis, dtype=np.float64)
# floating point error
#
# #18044 in _libs/windows.pyx calc_skew follow this behavior
# to fix the fperr to treat m2 <1e-14 as zero
m2 = _zero_out_fperr(m2)
m3 = _zero_out_fperr(m3)
with np.errstate(invalid='ignore', divide='ignore'):
result = (count * (count - 1) ** 0.5 / (count - 2)) * (m3 / m2 ** 1.5)
dtype = values.dtype
if is_float_dtype(dtype):
result = result.astype(dtype)
if isinstance(result, np.ndarray):
result = np.where(m2 == 0, 0, result)
result[count < 3] = np.nan
return result
else:
result = 0 if m2 == 0 else result
if count < 3:
return np.nan
return result | [
"Compute",
"the",
"sample",
"skewness",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L816-L891 | [
"def",
"nanskew",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"values",
"=",
"com",
".",
"values_from_object",
"(",
"values",
")",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"isna",
"(",
"values",
")",
"if",
"not",
"is_float_dtype",
"(",
"values",
".",
"dtype",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"'f8'",
")",
"count",
"=",
"_get_counts",
"(",
"mask",
",",
"axis",
")",
"else",
":",
"count",
"=",
"_get_counts",
"(",
"mask",
",",
"axis",
",",
"dtype",
"=",
"values",
".",
"dtype",
")",
"if",
"skipna",
":",
"values",
"=",
"values",
".",
"copy",
"(",
")",
"np",
".",
"putmask",
"(",
"values",
",",
"mask",
",",
"0",
")",
"mean",
"=",
"values",
".",
"sum",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"/",
"count",
"if",
"axis",
"is",
"not",
"None",
":",
"mean",
"=",
"np",
".",
"expand_dims",
"(",
"mean",
",",
"axis",
")",
"adjusted",
"=",
"values",
"-",
"mean",
"if",
"skipna",
":",
"np",
".",
"putmask",
"(",
"adjusted",
",",
"mask",
",",
"0",
")",
"adjusted2",
"=",
"adjusted",
"**",
"2",
"adjusted3",
"=",
"adjusted2",
"*",
"adjusted",
"m2",
"=",
"adjusted2",
".",
"sum",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"m3",
"=",
"adjusted3",
".",
"sum",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"# floating point error",
"#",
"# #18044 in _libs/windows.pyx calc_skew follow this behavior",
"# to fix the fperr to treat m2 <1e-14 as zero",
"m2",
"=",
"_zero_out_fperr",
"(",
"m2",
")",
"m3",
"=",
"_zero_out_fperr",
"(",
"m3",
")",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
",",
"divide",
"=",
"'ignore'",
")",
":",
"result",
"=",
"(",
"count",
"*",
"(",
"count",
"-",
"1",
")",
"**",
"0.5",
"/",
"(",
"count",
"-",
"2",
")",
")",
"*",
"(",
"m3",
"/",
"m2",
"**",
"1.5",
")",
"dtype",
"=",
"values",
".",
"dtype",
"if",
"is_float_dtype",
"(",
"dtype",
")",
":",
"result",
"=",
"result",
".",
"astype",
"(",
"dtype",
")",
"if",
"isinstance",
"(",
"result",
",",
"np",
".",
"ndarray",
")",
":",
"result",
"=",
"np",
".",
"where",
"(",
"m2",
"==",
"0",
",",
"0",
",",
"result",
")",
"result",
"[",
"count",
"<",
"3",
"]",
"=",
"np",
".",
"nan",
"return",
"result",
"else",
":",
"result",
"=",
"0",
"if",
"m2",
"==",
"0",
"else",
"result",
"if",
"count",
"<",
"3",
":",
"return",
"np",
".",
"nan",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nankurt | Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1,np.nan, 1, 3, 2])
>>> nanops.nankurt(s)
-1.2892561983471076 | pandas/core/nanops.py | def nankurt(values, axis=None, skipna=True, mask=None):
"""
Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1,np.nan, 1, 3, 2])
>>> nanops.nankurt(s)
-1.2892561983471076
"""
values = com.values_from_object(values)
if mask is None:
mask = isna(values)
if not is_float_dtype(values.dtype):
values = values.astype('f8')
count = _get_counts(mask, axis)
else:
count = _get_counts(mask, axis, dtype=values.dtype)
if skipna:
values = values.copy()
np.putmask(values, mask, 0)
mean = values.sum(axis, dtype=np.float64) / count
if axis is not None:
mean = np.expand_dims(mean, axis)
adjusted = values - mean
if skipna:
np.putmask(adjusted, mask, 0)
adjusted2 = adjusted ** 2
adjusted4 = adjusted2 ** 2
m2 = adjusted2.sum(axis, dtype=np.float64)
m4 = adjusted4.sum(axis, dtype=np.float64)
with np.errstate(invalid='ignore', divide='ignore'):
adj = 3 * (count - 1) ** 2 / ((count - 2) * (count - 3))
numer = count * (count + 1) * (count - 1) * m4
denom = (count - 2) * (count - 3) * m2 ** 2
# floating point error
#
# #18044 in _libs/windows.pyx calc_kurt follow this behavior
# to fix the fperr to treat denom <1e-14 as zero
numer = _zero_out_fperr(numer)
denom = _zero_out_fperr(denom)
if not isinstance(denom, np.ndarray):
# if ``denom`` is a scalar, check these corner cases first before
# doing division
if count < 4:
return np.nan
if denom == 0:
return 0
with np.errstate(invalid='ignore', divide='ignore'):
result = numer / denom - adj
dtype = values.dtype
if is_float_dtype(dtype):
result = result.astype(dtype)
if isinstance(result, np.ndarray):
result = np.where(denom == 0, 0, result)
result[count < 4] = np.nan
return result | def nankurt(values, axis=None, skipna=True, mask=None):
"""
Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1,np.nan, 1, 3, 2])
>>> nanops.nankurt(s)
-1.2892561983471076
"""
values = com.values_from_object(values)
if mask is None:
mask = isna(values)
if not is_float_dtype(values.dtype):
values = values.astype('f8')
count = _get_counts(mask, axis)
else:
count = _get_counts(mask, axis, dtype=values.dtype)
if skipna:
values = values.copy()
np.putmask(values, mask, 0)
mean = values.sum(axis, dtype=np.float64) / count
if axis is not None:
mean = np.expand_dims(mean, axis)
adjusted = values - mean
if skipna:
np.putmask(adjusted, mask, 0)
adjusted2 = adjusted ** 2
adjusted4 = adjusted2 ** 2
m2 = adjusted2.sum(axis, dtype=np.float64)
m4 = adjusted4.sum(axis, dtype=np.float64)
with np.errstate(invalid='ignore', divide='ignore'):
adj = 3 * (count - 1) ** 2 / ((count - 2) * (count - 3))
numer = count * (count + 1) * (count - 1) * m4
denom = (count - 2) * (count - 3) * m2 ** 2
# floating point error
#
# #18044 in _libs/windows.pyx calc_kurt follow this behavior
# to fix the fperr to treat denom <1e-14 as zero
numer = _zero_out_fperr(numer)
denom = _zero_out_fperr(denom)
if not isinstance(denom, np.ndarray):
# if ``denom`` is a scalar, check these corner cases first before
# doing division
if count < 4:
return np.nan
if denom == 0:
return 0
with np.errstate(invalid='ignore', divide='ignore'):
result = numer / denom - adj
dtype = values.dtype
if is_float_dtype(dtype):
result = result.astype(dtype)
if isinstance(result, np.ndarray):
result = np.where(denom == 0, 0, result)
result[count < 4] = np.nan
return result | [
"Compute",
"the",
"sample",
"excess",
"kurtosis"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L895-L980 | [
"def",
"nankurt",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"values",
"=",
"com",
".",
"values_from_object",
"(",
"values",
")",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"isna",
"(",
"values",
")",
"if",
"not",
"is_float_dtype",
"(",
"values",
".",
"dtype",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"'f8'",
")",
"count",
"=",
"_get_counts",
"(",
"mask",
",",
"axis",
")",
"else",
":",
"count",
"=",
"_get_counts",
"(",
"mask",
",",
"axis",
",",
"dtype",
"=",
"values",
".",
"dtype",
")",
"if",
"skipna",
":",
"values",
"=",
"values",
".",
"copy",
"(",
")",
"np",
".",
"putmask",
"(",
"values",
",",
"mask",
",",
"0",
")",
"mean",
"=",
"values",
".",
"sum",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"/",
"count",
"if",
"axis",
"is",
"not",
"None",
":",
"mean",
"=",
"np",
".",
"expand_dims",
"(",
"mean",
",",
"axis",
")",
"adjusted",
"=",
"values",
"-",
"mean",
"if",
"skipna",
":",
"np",
".",
"putmask",
"(",
"adjusted",
",",
"mask",
",",
"0",
")",
"adjusted2",
"=",
"adjusted",
"**",
"2",
"adjusted4",
"=",
"adjusted2",
"**",
"2",
"m2",
"=",
"adjusted2",
".",
"sum",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"m4",
"=",
"adjusted4",
".",
"sum",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
",",
"divide",
"=",
"'ignore'",
")",
":",
"adj",
"=",
"3",
"*",
"(",
"count",
"-",
"1",
")",
"**",
"2",
"/",
"(",
"(",
"count",
"-",
"2",
")",
"*",
"(",
"count",
"-",
"3",
")",
")",
"numer",
"=",
"count",
"*",
"(",
"count",
"+",
"1",
")",
"*",
"(",
"count",
"-",
"1",
")",
"*",
"m4",
"denom",
"=",
"(",
"count",
"-",
"2",
")",
"*",
"(",
"count",
"-",
"3",
")",
"*",
"m2",
"**",
"2",
"# floating point error",
"#",
"# #18044 in _libs/windows.pyx calc_kurt follow this behavior",
"# to fix the fperr to treat denom <1e-14 as zero",
"numer",
"=",
"_zero_out_fperr",
"(",
"numer",
")",
"denom",
"=",
"_zero_out_fperr",
"(",
"denom",
")",
"if",
"not",
"isinstance",
"(",
"denom",
",",
"np",
".",
"ndarray",
")",
":",
"# if ``denom`` is a scalar, check these corner cases first before",
"# doing division",
"if",
"count",
"<",
"4",
":",
"return",
"np",
".",
"nan",
"if",
"denom",
"==",
"0",
":",
"return",
"0",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
",",
"divide",
"=",
"'ignore'",
")",
":",
"result",
"=",
"numer",
"/",
"denom",
"-",
"adj",
"dtype",
"=",
"values",
".",
"dtype",
"if",
"is_float_dtype",
"(",
"dtype",
")",
":",
"result",
"=",
"result",
".",
"astype",
"(",
"dtype",
")",
"if",
"isinstance",
"(",
"result",
",",
"np",
".",
"ndarray",
")",
":",
"result",
"=",
"np",
".",
"where",
"(",
"denom",
"==",
"0",
",",
"0",
",",
"result",
")",
"result",
"[",
"count",
"<",
"4",
"]",
"=",
"np",
".",
"nan",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanprod | Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
min_count: int, default 0
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : dtype
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan])
>>> nanops.nanprod(s)
6.0
Returns
--------
The product of all elements on a given axis. ( NaNs are treated as 1) | pandas/core/nanops.py | def nanprod(values, axis=None, skipna=True, min_count=0, mask=None):
"""
Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
min_count: int, default 0
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : dtype
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan])
>>> nanops.nanprod(s)
6.0
Returns
--------
The product of all elements on a given axis. ( NaNs are treated as 1)
"""
if mask is None:
mask = isna(values)
if skipna and not is_any_int_dtype(values):
values = values.copy()
values[mask] = 1
result = values.prod(axis)
return _maybe_null_out(result, axis, mask, min_count=min_count) | def nanprod(values, axis=None, skipna=True, min_count=0, mask=None):
"""
Parameters
----------
values : ndarray[dtype]
axis: int, optional
skipna : bool, default True
min_count: int, default 0
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : dtype
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, 2, 3, np.nan])
>>> nanops.nanprod(s)
6.0
Returns
--------
The product of all elements on a given axis. ( NaNs are treated as 1)
"""
if mask is None:
mask = isna(values)
if skipna and not is_any_int_dtype(values):
values = values.copy()
values[mask] = 1
result = values.prod(axis)
return _maybe_null_out(result, axis, mask, min_count=min_count) | [
"Parameters",
"----------",
"values",
":",
"ndarray",
"[",
"dtype",
"]",
"axis",
":",
"int",
"optional",
"skipna",
":",
"bool",
"default",
"True",
"min_count",
":",
"int",
"default",
"0",
"mask",
":",
"ndarray",
"[",
"bool",
"]",
"optional",
"nan",
"-",
"mask",
"if",
"known"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L984-L1016 | [
"def",
"nanprod",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"min_count",
"=",
"0",
",",
"mask",
"=",
"None",
")",
":",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"isna",
"(",
"values",
")",
"if",
"skipna",
"and",
"not",
"is_any_int_dtype",
"(",
"values",
")",
":",
"values",
"=",
"values",
".",
"copy",
"(",
")",
"values",
"[",
"mask",
"]",
"=",
"1",
"result",
"=",
"values",
".",
"prod",
"(",
"axis",
")",
"return",
"_maybe_null_out",
"(",
"result",
",",
"axis",
",",
"mask",
",",
"min_count",
"=",
"min_count",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nancorr | a, b: ndarrays | pandas/core/nanops.py | def nancorr(a, b, method='pearson', min_periods=None):
"""
a, b: ndarrays
"""
if len(a) != len(b):
raise AssertionError('Operands to nancorr must have same size')
if min_periods is None:
min_periods = 1
valid = notna(a) & notna(b)
if not valid.all():
a = a[valid]
b = b[valid]
if len(a) < min_periods:
return np.nan
f = get_corr_func(method)
return f(a, b) | def nancorr(a, b, method='pearson', min_periods=None):
"""
a, b: ndarrays
"""
if len(a) != len(b):
raise AssertionError('Operands to nancorr must have same size')
if min_periods is None:
min_periods = 1
valid = notna(a) & notna(b)
if not valid.all():
a = a[valid]
b = b[valid]
if len(a) < min_periods:
return np.nan
f = get_corr_func(method)
return f(a, b) | [
"a",
"b",
":",
"ndarrays"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L1083-L1102 | [
"def",
"nancorr",
"(",
"a",
",",
"b",
",",
"method",
"=",
"'pearson'",
",",
"min_periods",
"=",
"None",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"raise",
"AssertionError",
"(",
"'Operands to nancorr must have same size'",
")",
"if",
"min_periods",
"is",
"None",
":",
"min_periods",
"=",
"1",
"valid",
"=",
"notna",
"(",
"a",
")",
"&",
"notna",
"(",
"b",
")",
"if",
"not",
"valid",
".",
"all",
"(",
")",
":",
"a",
"=",
"a",
"[",
"valid",
"]",
"b",
"=",
"b",
"[",
"valid",
"]",
"if",
"len",
"(",
"a",
")",
"<",
"min_periods",
":",
"return",
"np",
".",
"nan",
"f",
"=",
"get_corr_func",
"(",
"method",
")",
"return",
"f",
"(",
"a",
",",
"b",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _nanpercentile_1d | Wraper for np.percentile that skips missing values, specialized to
1-dimensional case.
Parameters
----------
values : array over which to find quantiles
mask : ndarray[bool]
locations in values that should be considered missing
q : scalar or array of quantile indices to find
na_value : scalar
value to return for empty or all-null values
interpolation : str
Returns
-------
quantiles : scalar or array | pandas/core/nanops.py | def _nanpercentile_1d(values, mask, q, na_value, interpolation):
"""
Wraper for np.percentile that skips missing values, specialized to
1-dimensional case.
Parameters
----------
values : array over which to find quantiles
mask : ndarray[bool]
locations in values that should be considered missing
q : scalar or array of quantile indices to find
na_value : scalar
value to return for empty or all-null values
interpolation : str
Returns
-------
quantiles : scalar or array
"""
# mask is Union[ExtensionArray, ndarray]
values = values[~mask]
if len(values) == 0:
if lib.is_scalar(q):
return na_value
else:
return np.array([na_value] * len(q),
dtype=values.dtype)
return np.percentile(values, q, interpolation=interpolation) | def _nanpercentile_1d(values, mask, q, na_value, interpolation):
"""
Wraper for np.percentile that skips missing values, specialized to
1-dimensional case.
Parameters
----------
values : array over which to find quantiles
mask : ndarray[bool]
locations in values that should be considered missing
q : scalar or array of quantile indices to find
na_value : scalar
value to return for empty or all-null values
interpolation : str
Returns
-------
quantiles : scalar or array
"""
# mask is Union[ExtensionArray, ndarray]
values = values[~mask]
if len(values) == 0:
if lib.is_scalar(q):
return na_value
else:
return np.array([na_value] * len(q),
dtype=values.dtype)
return np.percentile(values, q, interpolation=interpolation) | [
"Wraper",
"for",
"np",
".",
"percentile",
"that",
"skips",
"missing",
"values",
"specialized",
"to",
"1",
"-",
"dimensional",
"case",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L1203-L1232 | [
"def",
"_nanpercentile_1d",
"(",
"values",
",",
"mask",
",",
"q",
",",
"na_value",
",",
"interpolation",
")",
":",
"# mask is Union[ExtensionArray, ndarray]",
"values",
"=",
"values",
"[",
"~",
"mask",
"]",
"if",
"len",
"(",
"values",
")",
"==",
"0",
":",
"if",
"lib",
".",
"is_scalar",
"(",
"q",
")",
":",
"return",
"na_value",
"else",
":",
"return",
"np",
".",
"array",
"(",
"[",
"na_value",
"]",
"*",
"len",
"(",
"q",
")",
",",
"dtype",
"=",
"values",
".",
"dtype",
")",
"return",
"np",
".",
"percentile",
"(",
"values",
",",
"q",
",",
"interpolation",
"=",
"interpolation",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | nanpercentile | Wraper for np.percentile that skips missing values.
Parameters
----------
values : array over which to find quantiles
q : scalar or array of quantile indices to find
axis : {0, 1}
na_value : scalar
value to return for empty or all-null values
mask : ndarray[bool]
locations in values that should be considered missing
ndim : {1, 2}
interpolation : str
Returns
-------
quantiles : scalar or array | pandas/core/nanops.py | def nanpercentile(values, q, axis, na_value, mask, ndim, interpolation):
"""
Wraper for np.percentile that skips missing values.
Parameters
----------
values : array over which to find quantiles
q : scalar or array of quantile indices to find
axis : {0, 1}
na_value : scalar
value to return for empty or all-null values
mask : ndarray[bool]
locations in values that should be considered missing
ndim : {1, 2}
interpolation : str
Returns
-------
quantiles : scalar or array
"""
if not lib.is_scalar(mask) and mask.any():
if ndim == 1:
return _nanpercentile_1d(values, mask, q, na_value,
interpolation=interpolation)
else:
# for nonconsolidatable blocks mask is 1D, but values 2D
if mask.ndim < values.ndim:
mask = mask.reshape(values.shape)
if axis == 0:
values = values.T
mask = mask.T
result = [_nanpercentile_1d(val, m, q, na_value,
interpolation=interpolation)
for (val, m) in zip(list(values), list(mask))]
result = np.array(result, dtype=values.dtype, copy=False).T
return result
else:
return np.percentile(values, q, axis=axis, interpolation=interpolation) | def nanpercentile(values, q, axis, na_value, mask, ndim, interpolation):
"""
Wraper for np.percentile that skips missing values.
Parameters
----------
values : array over which to find quantiles
q : scalar or array of quantile indices to find
axis : {0, 1}
na_value : scalar
value to return for empty or all-null values
mask : ndarray[bool]
locations in values that should be considered missing
ndim : {1, 2}
interpolation : str
Returns
-------
quantiles : scalar or array
"""
if not lib.is_scalar(mask) and mask.any():
if ndim == 1:
return _nanpercentile_1d(values, mask, q, na_value,
interpolation=interpolation)
else:
# for nonconsolidatable blocks mask is 1D, but values 2D
if mask.ndim < values.ndim:
mask = mask.reshape(values.shape)
if axis == 0:
values = values.T
mask = mask.T
result = [_nanpercentile_1d(val, m, q, na_value,
interpolation=interpolation)
for (val, m) in zip(list(values), list(mask))]
result = np.array(result, dtype=values.dtype, copy=False).T
return result
else:
return np.percentile(values, q, axis=axis, interpolation=interpolation) | [
"Wraper",
"for",
"np",
".",
"percentile",
"that",
"skips",
"missing",
"values",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L1235-L1272 | [
"def",
"nanpercentile",
"(",
"values",
",",
"q",
",",
"axis",
",",
"na_value",
",",
"mask",
",",
"ndim",
",",
"interpolation",
")",
":",
"if",
"not",
"lib",
".",
"is_scalar",
"(",
"mask",
")",
"and",
"mask",
".",
"any",
"(",
")",
":",
"if",
"ndim",
"==",
"1",
":",
"return",
"_nanpercentile_1d",
"(",
"values",
",",
"mask",
",",
"q",
",",
"na_value",
",",
"interpolation",
"=",
"interpolation",
")",
"else",
":",
"# for nonconsolidatable blocks mask is 1D, but values 2D",
"if",
"mask",
".",
"ndim",
"<",
"values",
".",
"ndim",
":",
"mask",
"=",
"mask",
".",
"reshape",
"(",
"values",
".",
"shape",
")",
"if",
"axis",
"==",
"0",
":",
"values",
"=",
"values",
".",
"T",
"mask",
"=",
"mask",
".",
"T",
"result",
"=",
"[",
"_nanpercentile_1d",
"(",
"val",
",",
"m",
",",
"q",
",",
"na_value",
",",
"interpolation",
"=",
"interpolation",
")",
"for",
"(",
"val",
",",
"m",
")",
"in",
"zip",
"(",
"list",
"(",
"values",
")",
",",
"list",
"(",
"mask",
")",
")",
"]",
"result",
"=",
"np",
".",
"array",
"(",
"result",
",",
"dtype",
"=",
"values",
".",
"dtype",
",",
"copy",
"=",
"False",
")",
".",
"T",
"return",
"result",
"else",
":",
"return",
"np",
".",
"percentile",
"(",
"values",
",",
"q",
",",
"axis",
"=",
"axis",
",",
"interpolation",
"=",
"interpolation",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | HTMLFormatter.write_th | Method for writting a formatted <th> cell.
If col_space is set on the formatter then that is used for
the value of min-width.
Parameters
----------
s : object
The data to be written inside the cell.
header : boolean, default False
Set to True if the <th> is for use inside <thead>. This will
cause min-width to be set if there is one.
indent : int, default 0
The indentation level of the cell.
tags : string, default None
Tags to include in the cell.
Returns
-------
A written <th> cell. | pandas/io/formats/html.py | def write_th(self, s, header=False, indent=0, tags=None):
"""
Method for writting a formatted <th> cell.
If col_space is set on the formatter then that is used for
the value of min-width.
Parameters
----------
s : object
The data to be written inside the cell.
header : boolean, default False
Set to True if the <th> is for use inside <thead>. This will
cause min-width to be set if there is one.
indent : int, default 0
The indentation level of the cell.
tags : string, default None
Tags to include in the cell.
Returns
-------
A written <th> cell.
"""
if header and self.fmt.col_space is not None:
tags = (tags or "")
tags += ('style="min-width: {colspace};"'
.format(colspace=self.fmt.col_space))
return self._write_cell(s, kind='th', indent=indent, tags=tags) | def write_th(self, s, header=False, indent=0, tags=None):
"""
Method for writting a formatted <th> cell.
If col_space is set on the formatter then that is used for
the value of min-width.
Parameters
----------
s : object
The data to be written inside the cell.
header : boolean, default False
Set to True if the <th> is for use inside <thead>. This will
cause min-width to be set if there is one.
indent : int, default 0
The indentation level of the cell.
tags : string, default None
Tags to include in the cell.
Returns
-------
A written <th> cell.
"""
if header and self.fmt.col_space is not None:
tags = (tags or "")
tags += ('style="min-width: {colspace};"'
.format(colspace=self.fmt.col_space))
return self._write_cell(s, kind='th', indent=indent, tags=tags) | [
"Method",
"for",
"writting",
"a",
"formatted",
"<th",
">",
"cell",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/formats/html.py#L90-L118 | [
"def",
"write_th",
"(",
"self",
",",
"s",
",",
"header",
"=",
"False",
",",
"indent",
"=",
"0",
",",
"tags",
"=",
"None",
")",
":",
"if",
"header",
"and",
"self",
".",
"fmt",
".",
"col_space",
"is",
"not",
"None",
":",
"tags",
"=",
"(",
"tags",
"or",
"\"\"",
")",
"tags",
"+=",
"(",
"'style=\"min-width: {colspace};\"'",
".",
"format",
"(",
"colspace",
"=",
"self",
".",
"fmt",
".",
"col_space",
")",
")",
"return",
"self",
".",
"_write_cell",
"(",
"s",
",",
"kind",
"=",
"'th'",
",",
"indent",
"=",
"indent",
",",
"tags",
"=",
"tags",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | read_clipboard | r"""
Read text from clipboard and pass to read_csv. See read_csv for the
full argument list
Parameters
----------
sep : str, default '\s+'
A string or regex delimiter. The default of '\s+' denotes
one or more whitespace characters.
Returns
-------
parsed : DataFrame | pandas/io/clipboards.py | def read_clipboard(sep=r'\s+', **kwargs): # pragma: no cover
r"""
Read text from clipboard and pass to read_csv. See read_csv for the
full argument list
Parameters
----------
sep : str, default '\s+'
A string or regex delimiter. The default of '\s+' denotes
one or more whitespace characters.
Returns
-------
parsed : DataFrame
"""
encoding = kwargs.pop('encoding', 'utf-8')
# only utf-8 is valid for passed value because that's what clipboard
# supports
if encoding is not None and encoding.lower().replace('-', '') != 'utf8':
raise NotImplementedError(
'reading from clipboard only supports utf-8 encoding')
from pandas.io.clipboard import clipboard_get
from pandas.io.parsers import read_csv
text = clipboard_get()
# Try to decode (if needed, as "text" might already be a string here).
try:
text = text.decode(kwargs.get('encoding')
or get_option('display.encoding'))
except AttributeError:
pass
# Excel copies into clipboard with \t separation
# inspect no more then the 10 first lines, if they
# all contain an equal number (>0) of tabs, infer
# that this came from excel and set 'sep' accordingly
lines = text[:10000].split('\n')[:-1][:10]
# Need to remove leading white space, since read_csv
# accepts:
# a b
# 0 1 2
# 1 3 4
counts = {x.lstrip().count('\t') for x in lines}
if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0:
sep = '\t'
# Edge case where sep is specified to be None, return to default
if sep is None and kwargs.get('delim_whitespace') is None:
sep = r'\s+'
# Regex separator currently only works with python engine.
# Default to python if separator is multi-character (regex)
if len(sep) > 1 and kwargs.get('engine') is None:
kwargs['engine'] = 'python'
elif len(sep) > 1 and kwargs.get('engine') == 'c':
warnings.warn('read_clipboard with regex separator does not work'
' properly with c engine')
return read_csv(StringIO(text), sep=sep, **kwargs) | def read_clipboard(sep=r'\s+', **kwargs): # pragma: no cover
r"""
Read text from clipboard and pass to read_csv. See read_csv for the
full argument list
Parameters
----------
sep : str, default '\s+'
A string or regex delimiter. The default of '\s+' denotes
one or more whitespace characters.
Returns
-------
parsed : DataFrame
"""
encoding = kwargs.pop('encoding', 'utf-8')
# only utf-8 is valid for passed value because that's what clipboard
# supports
if encoding is not None and encoding.lower().replace('-', '') != 'utf8':
raise NotImplementedError(
'reading from clipboard only supports utf-8 encoding')
from pandas.io.clipboard import clipboard_get
from pandas.io.parsers import read_csv
text = clipboard_get()
# Try to decode (if needed, as "text" might already be a string here).
try:
text = text.decode(kwargs.get('encoding')
or get_option('display.encoding'))
except AttributeError:
pass
# Excel copies into clipboard with \t separation
# inspect no more then the 10 first lines, if they
# all contain an equal number (>0) of tabs, infer
# that this came from excel and set 'sep' accordingly
lines = text[:10000].split('\n')[:-1][:10]
# Need to remove leading white space, since read_csv
# accepts:
# a b
# 0 1 2
# 1 3 4
counts = {x.lstrip().count('\t') for x in lines}
if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0:
sep = '\t'
# Edge case where sep is specified to be None, return to default
if sep is None and kwargs.get('delim_whitespace') is None:
sep = r'\s+'
# Regex separator currently only works with python engine.
# Default to python if separator is multi-character (regex)
if len(sep) > 1 and kwargs.get('engine') is None:
kwargs['engine'] = 'python'
elif len(sep) > 1 and kwargs.get('engine') == 'c':
warnings.warn('read_clipboard with regex separator does not work'
' properly with c engine')
return read_csv(StringIO(text), sep=sep, **kwargs) | [
"r",
"Read",
"text",
"from",
"clipboard",
"and",
"pass",
"to",
"read_csv",
".",
"See",
"read_csv",
"for",
"the",
"full",
"argument",
"list"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/clipboards.py#L10-L72 | [
"def",
"read_clipboard",
"(",
"sep",
"=",
"r'\\s+'",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"encoding",
"=",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"'utf-8'",
")",
"# only utf-8 is valid for passed value because that's what clipboard",
"# supports",
"if",
"encoding",
"is",
"not",
"None",
"and",
"encoding",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"!=",
"'utf8'",
":",
"raise",
"NotImplementedError",
"(",
"'reading from clipboard only supports utf-8 encoding'",
")",
"from",
"pandas",
".",
"io",
".",
"clipboard",
"import",
"clipboard_get",
"from",
"pandas",
".",
"io",
".",
"parsers",
"import",
"read_csv",
"text",
"=",
"clipboard_get",
"(",
")",
"# Try to decode (if needed, as \"text\" might already be a string here).",
"try",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"kwargs",
".",
"get",
"(",
"'encoding'",
")",
"or",
"get_option",
"(",
"'display.encoding'",
")",
")",
"except",
"AttributeError",
":",
"pass",
"# Excel copies into clipboard with \\t separation",
"# inspect no more then the 10 first lines, if they",
"# all contain an equal number (>0) of tabs, infer",
"# that this came from excel and set 'sep' accordingly",
"lines",
"=",
"text",
"[",
":",
"10000",
"]",
".",
"split",
"(",
"'\\n'",
")",
"[",
":",
"-",
"1",
"]",
"[",
":",
"10",
"]",
"# Need to remove leading white space, since read_csv",
"# accepts:",
"# a b",
"# 0 1 2",
"# 1 3 4",
"counts",
"=",
"{",
"x",
".",
"lstrip",
"(",
")",
".",
"count",
"(",
"'\\t'",
")",
"for",
"x",
"in",
"lines",
"}",
"if",
"len",
"(",
"lines",
")",
">",
"1",
"and",
"len",
"(",
"counts",
")",
"==",
"1",
"and",
"counts",
".",
"pop",
"(",
")",
"!=",
"0",
":",
"sep",
"=",
"'\\t'",
"# Edge case where sep is specified to be None, return to default",
"if",
"sep",
"is",
"None",
"and",
"kwargs",
".",
"get",
"(",
"'delim_whitespace'",
")",
"is",
"None",
":",
"sep",
"=",
"r'\\s+'",
"# Regex separator currently only works with python engine.",
"# Default to python if separator is multi-character (regex)",
"if",
"len",
"(",
"sep",
")",
">",
"1",
"and",
"kwargs",
".",
"get",
"(",
"'engine'",
")",
"is",
"None",
":",
"kwargs",
"[",
"'engine'",
"]",
"=",
"'python'",
"elif",
"len",
"(",
"sep",
")",
">",
"1",
"and",
"kwargs",
".",
"get",
"(",
"'engine'",
")",
"==",
"'c'",
":",
"warnings",
".",
"warn",
"(",
"'read_clipboard with regex separator does not work'",
"' properly with c engine'",
")",
"return",
"read_csv",
"(",
"StringIO",
"(",
"text",
")",
",",
"sep",
"=",
"sep",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | to_clipboard | Attempt to write text representation of object to the system clipboard
The clipboard can be then pasted into Excel for example.
Parameters
----------
obj : the object to write to the clipboard
excel : boolean, defaults to True
if True, use the provided separator, writing in a csv
format for allowing easy pasting into excel.
if False, write a string representation of the object
to the clipboard
sep : optional, defaults to tab
other keywords are passed to to_csv
Notes
-----
Requirements for your platform
- Linux: xclip, or xsel (with gtk or PyQt4 modules)
- Windows:
- OS X: | pandas/io/clipboards.py | def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover
"""
Attempt to write text representation of object to the system clipboard
The clipboard can be then pasted into Excel for example.
Parameters
----------
obj : the object to write to the clipboard
excel : boolean, defaults to True
if True, use the provided separator, writing in a csv
format for allowing easy pasting into excel.
if False, write a string representation of the object
to the clipboard
sep : optional, defaults to tab
other keywords are passed to to_csv
Notes
-----
Requirements for your platform
- Linux: xclip, or xsel (with gtk or PyQt4 modules)
- Windows:
- OS X:
"""
encoding = kwargs.pop('encoding', 'utf-8')
# testing if an invalid encoding is passed to clipboard
if encoding is not None and encoding.lower().replace('-', '') != 'utf8':
raise ValueError('clipboard only supports utf-8 encoding')
from pandas.io.clipboard import clipboard_set
if excel is None:
excel = True
if excel:
try:
if sep is None:
sep = '\t'
buf = StringIO()
# clipboard_set (pyperclip) expects unicode
obj.to_csv(buf, sep=sep, encoding='utf-8', **kwargs)
text = buf.getvalue()
clipboard_set(text)
return
except TypeError:
warnings.warn('to_clipboard in excel mode requires a single '
'character separator.')
elif sep is not None:
warnings.warn('to_clipboard with excel=False ignores the sep argument')
if isinstance(obj, ABCDataFrame):
# str(df) has various unhelpful defaults, like truncation
with option_context('display.max_colwidth', 999999):
objstr = obj.to_string(**kwargs)
else:
objstr = str(obj)
clipboard_set(objstr) | def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover
"""
Attempt to write text representation of object to the system clipboard
The clipboard can be then pasted into Excel for example.
Parameters
----------
obj : the object to write to the clipboard
excel : boolean, defaults to True
if True, use the provided separator, writing in a csv
format for allowing easy pasting into excel.
if False, write a string representation of the object
to the clipboard
sep : optional, defaults to tab
other keywords are passed to to_csv
Notes
-----
Requirements for your platform
- Linux: xclip, or xsel (with gtk or PyQt4 modules)
- Windows:
- OS X:
"""
encoding = kwargs.pop('encoding', 'utf-8')
# testing if an invalid encoding is passed to clipboard
if encoding is not None and encoding.lower().replace('-', '') != 'utf8':
raise ValueError('clipboard only supports utf-8 encoding')
from pandas.io.clipboard import clipboard_set
if excel is None:
excel = True
if excel:
try:
if sep is None:
sep = '\t'
buf = StringIO()
# clipboard_set (pyperclip) expects unicode
obj.to_csv(buf, sep=sep, encoding='utf-8', **kwargs)
text = buf.getvalue()
clipboard_set(text)
return
except TypeError:
warnings.warn('to_clipboard in excel mode requires a single '
'character separator.')
elif sep is not None:
warnings.warn('to_clipboard with excel=False ignores the sep argument')
if isinstance(obj, ABCDataFrame):
# str(df) has various unhelpful defaults, like truncation
with option_context('display.max_colwidth', 999999):
objstr = obj.to_string(**kwargs)
else:
objstr = str(obj)
clipboard_set(objstr) | [
"Attempt",
"to",
"write",
"text",
"representation",
"of",
"object",
"to",
"the",
"system",
"clipboard",
"The",
"clipboard",
"can",
"be",
"then",
"pasted",
"into",
"Excel",
"for",
"example",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/clipboards.py#L75-L132 | [
"def",
"to_clipboard",
"(",
"obj",
",",
"excel",
"=",
"True",
",",
"sep",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"encoding",
"=",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"'utf-8'",
")",
"# testing if an invalid encoding is passed to clipboard",
"if",
"encoding",
"is",
"not",
"None",
"and",
"encoding",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"!=",
"'utf8'",
":",
"raise",
"ValueError",
"(",
"'clipboard only supports utf-8 encoding'",
")",
"from",
"pandas",
".",
"io",
".",
"clipboard",
"import",
"clipboard_set",
"if",
"excel",
"is",
"None",
":",
"excel",
"=",
"True",
"if",
"excel",
":",
"try",
":",
"if",
"sep",
"is",
"None",
":",
"sep",
"=",
"'\\t'",
"buf",
"=",
"StringIO",
"(",
")",
"# clipboard_set (pyperclip) expects unicode",
"obj",
".",
"to_csv",
"(",
"buf",
",",
"sep",
"=",
"sep",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"*",
"kwargs",
")",
"text",
"=",
"buf",
".",
"getvalue",
"(",
")",
"clipboard_set",
"(",
"text",
")",
"return",
"except",
"TypeError",
":",
"warnings",
".",
"warn",
"(",
"'to_clipboard in excel mode requires a single '",
"'character separator.'",
")",
"elif",
"sep",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"'to_clipboard with excel=False ignores the sep argument'",
")",
"if",
"isinstance",
"(",
"obj",
",",
"ABCDataFrame",
")",
":",
"# str(df) has various unhelpful defaults, like truncation",
"with",
"option_context",
"(",
"'display.max_colwidth'",
",",
"999999",
")",
":",
"objstr",
"=",
"obj",
".",
"to_string",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"objstr",
"=",
"str",
"(",
"obj",
")",
"clipboard_set",
"(",
"objstr",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_skiprows | Get an iterator given an integer, slice or container.
Parameters
----------
skiprows : int, slice, container
The iterator to use to skip rows; can also be a slice.
Raises
------
TypeError
* If `skiprows` is not a slice, integer, or Container
Returns
-------
it : iterable
A proper iterator to use to skip rows of a DataFrame. | pandas/io/html.py | def _get_skiprows(skiprows):
"""Get an iterator given an integer, slice or container.
Parameters
----------
skiprows : int, slice, container
The iterator to use to skip rows; can also be a slice.
Raises
------
TypeError
* If `skiprows` is not a slice, integer, or Container
Returns
-------
it : iterable
A proper iterator to use to skip rows of a DataFrame.
"""
if isinstance(skiprows, slice):
return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
return skiprows
elif skiprows is None:
return 0
raise TypeError('%r is not a valid type for skipping rows' %
type(skiprows).__name__) | def _get_skiprows(skiprows):
"""Get an iterator given an integer, slice or container.
Parameters
----------
skiprows : int, slice, container
The iterator to use to skip rows; can also be a slice.
Raises
------
TypeError
* If `skiprows` is not a slice, integer, or Container
Returns
-------
it : iterable
A proper iterator to use to skip rows of a DataFrame.
"""
if isinstance(skiprows, slice):
return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
return skiprows
elif skiprows is None:
return 0
raise TypeError('%r is not a valid type for skipping rows' %
type(skiprows).__name__) | [
"Get",
"an",
"iterator",
"given",
"an",
"integer",
"slice",
"or",
"container",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L85-L110 | [
"def",
"_get_skiprows",
"(",
"skiprows",
")",
":",
"if",
"isinstance",
"(",
"skiprows",
",",
"slice",
")",
":",
"return",
"lrange",
"(",
"skiprows",
".",
"start",
"or",
"0",
",",
"skiprows",
".",
"stop",
",",
"skiprows",
".",
"step",
"or",
"1",
")",
"elif",
"isinstance",
"(",
"skiprows",
",",
"numbers",
".",
"Integral",
")",
"or",
"is_list_like",
"(",
"skiprows",
")",
":",
"return",
"skiprows",
"elif",
"skiprows",
"is",
"None",
":",
"return",
"0",
"raise",
"TypeError",
"(",
"'%r is not a valid type for skipping rows'",
"%",
"type",
"(",
"skiprows",
")",
".",
"__name__",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _read | Try to read from a url, file or string.
Parameters
----------
obj : str, unicode, or file-like
Returns
-------
raw_text : str | pandas/io/html.py | def _read(obj):
"""Try to read from a url, file or string.
Parameters
----------
obj : str, unicode, or file-like
Returns
-------
raw_text : str
"""
if _is_url(obj):
with urlopen(obj) as url:
text = url.read()
elif hasattr(obj, 'read'):
text = obj.read()
elif isinstance(obj, (str, bytes)):
text = obj
try:
if os.path.isfile(text):
with open(text, 'rb') as f:
return f.read()
except (TypeError, ValueError):
pass
else:
raise TypeError("Cannot read object of type %r" % type(obj).__name__)
return text | def _read(obj):
"""Try to read from a url, file or string.
Parameters
----------
obj : str, unicode, or file-like
Returns
-------
raw_text : str
"""
if _is_url(obj):
with urlopen(obj) as url:
text = url.read()
elif hasattr(obj, 'read'):
text = obj.read()
elif isinstance(obj, (str, bytes)):
text = obj
try:
if os.path.isfile(text):
with open(text, 'rb') as f:
return f.read()
except (TypeError, ValueError):
pass
else:
raise TypeError("Cannot read object of type %r" % type(obj).__name__)
return text | [
"Try",
"to",
"read",
"from",
"a",
"url",
"file",
"or",
"string",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L113-L139 | [
"def",
"_read",
"(",
"obj",
")",
":",
"if",
"_is_url",
"(",
"obj",
")",
":",
"with",
"urlopen",
"(",
"obj",
")",
"as",
"url",
":",
"text",
"=",
"url",
".",
"read",
"(",
")",
"elif",
"hasattr",
"(",
"obj",
",",
"'read'",
")",
":",
"text",
"=",
"obj",
".",
"read",
"(",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"text",
"=",
"obj",
"try",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"text",
")",
":",
"with",
"open",
"(",
"text",
",",
"'rb'",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"else",
":",
"raise",
"TypeError",
"(",
"\"Cannot read object of type %r\"",
"%",
"type",
"(",
"obj",
")",
".",
"__name__",
")",
"return",
"text"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _build_xpath_expr | Build an xpath expression to simulate bs4's ability to pass in kwargs to
search for attributes when using the lxml parser.
Parameters
----------
attrs : dict
A dict of HTML attributes. These are NOT checked for validity.
Returns
-------
expr : unicode
An XPath expression that checks for the given HTML attributes. | pandas/io/html.py | def _build_xpath_expr(attrs):
"""Build an xpath expression to simulate bs4's ability to pass in kwargs to
search for attributes when using the lxml parser.
Parameters
----------
attrs : dict
A dict of HTML attributes. These are NOT checked for validity.
Returns
-------
expr : unicode
An XPath expression that checks for the given HTML attributes.
"""
# give class attribute as class_ because class is a python keyword
if 'class_' in attrs:
attrs['class'] = attrs.pop('class_')
s = ["@{key}={val!r}".format(key=k, val=v) for k, v in attrs.items()]
return '[{expr}]'.format(expr=' and '.join(s)) | def _build_xpath_expr(attrs):
"""Build an xpath expression to simulate bs4's ability to pass in kwargs to
search for attributes when using the lxml parser.
Parameters
----------
attrs : dict
A dict of HTML attributes. These are NOT checked for validity.
Returns
-------
expr : unicode
An XPath expression that checks for the given HTML attributes.
"""
# give class attribute as class_ because class is a python keyword
if 'class_' in attrs:
attrs['class'] = attrs.pop('class_')
s = ["@{key}={val!r}".format(key=k, val=v) for k, v in attrs.items()]
return '[{expr}]'.format(expr=' and '.join(s)) | [
"Build",
"an",
"xpath",
"expression",
"to",
"simulate",
"bs4",
"s",
"ability",
"to",
"pass",
"in",
"kwargs",
"to",
"search",
"for",
"attributes",
"when",
"using",
"the",
"lxml",
"parser",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L601-L620 | [
"def",
"_build_xpath_expr",
"(",
"attrs",
")",
":",
"# give class attribute as class_ because class is a python keyword",
"if",
"'class_'",
"in",
"attrs",
":",
"attrs",
"[",
"'class'",
"]",
"=",
"attrs",
".",
"pop",
"(",
"'class_'",
")",
"s",
"=",
"[",
"\"@{key}={val!r}\"",
".",
"format",
"(",
"key",
"=",
"k",
",",
"val",
"=",
"v",
")",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"items",
"(",
")",
"]",
"return",
"'[{expr}]'",
".",
"format",
"(",
"expr",
"=",
"' and '",
".",
"join",
"(",
"s",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _parser_dispatch | Choose the parser based on the input flavor.
Parameters
----------
flavor : str
The type of parser to use. This must be a valid backend.
Returns
-------
cls : _HtmlFrameParser subclass
The parser class based on the requested input flavor.
Raises
------
ValueError
* If `flavor` is not a valid backend.
ImportError
* If you do not have the requested `flavor` | pandas/io/html.py | def _parser_dispatch(flavor):
"""Choose the parser based on the input flavor.
Parameters
----------
flavor : str
The type of parser to use. This must be a valid backend.
Returns
-------
cls : _HtmlFrameParser subclass
The parser class based on the requested input flavor.
Raises
------
ValueError
* If `flavor` is not a valid backend.
ImportError
* If you do not have the requested `flavor`
"""
valid_parsers = list(_valid_parsers.keys())
if flavor not in valid_parsers:
raise ValueError('{invalid!r} is not a valid flavor, valid flavors '
'are {valid}'
.format(invalid=flavor, valid=valid_parsers))
if flavor in ('bs4', 'html5lib'):
if not _HAS_HTML5LIB:
raise ImportError("html5lib not found, please install it")
if not _HAS_BS4:
raise ImportError(
"BeautifulSoup4 (bs4) not found, please install it")
import bs4
if LooseVersion(bs4.__version__) <= LooseVersion('4.2.0'):
raise ValueError("A minimum version of BeautifulSoup 4.2.1 "
"is required")
else:
if not _HAS_LXML:
raise ImportError("lxml not found, please install it")
return _valid_parsers[flavor] | def _parser_dispatch(flavor):
"""Choose the parser based on the input flavor.
Parameters
----------
flavor : str
The type of parser to use. This must be a valid backend.
Returns
-------
cls : _HtmlFrameParser subclass
The parser class based on the requested input flavor.
Raises
------
ValueError
* If `flavor` is not a valid backend.
ImportError
* If you do not have the requested `flavor`
"""
valid_parsers = list(_valid_parsers.keys())
if flavor not in valid_parsers:
raise ValueError('{invalid!r} is not a valid flavor, valid flavors '
'are {valid}'
.format(invalid=flavor, valid=valid_parsers))
if flavor in ('bs4', 'html5lib'):
if not _HAS_HTML5LIB:
raise ImportError("html5lib not found, please install it")
if not _HAS_BS4:
raise ImportError(
"BeautifulSoup4 (bs4) not found, please install it")
import bs4
if LooseVersion(bs4.__version__) <= LooseVersion('4.2.0'):
raise ValueError("A minimum version of BeautifulSoup 4.2.1 "
"is required")
else:
if not _HAS_LXML:
raise ImportError("lxml not found, please install it")
return _valid_parsers[flavor] | [
"Choose",
"the",
"parser",
"based",
"on",
"the",
"input",
"flavor",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L806-L846 | [
"def",
"_parser_dispatch",
"(",
"flavor",
")",
":",
"valid_parsers",
"=",
"list",
"(",
"_valid_parsers",
".",
"keys",
"(",
")",
")",
"if",
"flavor",
"not",
"in",
"valid_parsers",
":",
"raise",
"ValueError",
"(",
"'{invalid!r} is not a valid flavor, valid flavors '",
"'are {valid}'",
".",
"format",
"(",
"invalid",
"=",
"flavor",
",",
"valid",
"=",
"valid_parsers",
")",
")",
"if",
"flavor",
"in",
"(",
"'bs4'",
",",
"'html5lib'",
")",
":",
"if",
"not",
"_HAS_HTML5LIB",
":",
"raise",
"ImportError",
"(",
"\"html5lib not found, please install it\"",
")",
"if",
"not",
"_HAS_BS4",
":",
"raise",
"ImportError",
"(",
"\"BeautifulSoup4 (bs4) not found, please install it\"",
")",
"import",
"bs4",
"if",
"LooseVersion",
"(",
"bs4",
".",
"__version__",
")",
"<=",
"LooseVersion",
"(",
"'4.2.0'",
")",
":",
"raise",
"ValueError",
"(",
"\"A minimum version of BeautifulSoup 4.2.1 \"",
"\"is required\"",
")",
"else",
":",
"if",
"not",
"_HAS_LXML",
":",
"raise",
"ImportError",
"(",
"\"lxml not found, please install it\"",
")",
"return",
"_valid_parsers",
"[",
"flavor",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | read_html | r"""Read HTML tables into a ``list`` of ``DataFrame`` objects.
Parameters
----------
io : str or file-like
A URL, a file-like object, or a raw string containing HTML. Note that
lxml only accepts the http, ftp and file url protocols. If you have a
URL that starts with ``'https'`` you might try removing the ``'s'``.
match : str or compiled regular expression, optional
The set of tables containing text matching this regex or string will be
returned. Unless the HTML is extremely simple you will probably need to
pass a non-empty string here. Defaults to '.+' (match any non-empty
string). The default value will return all tables contained on a page.
This value is converted to a regular expression so that there is
consistent behavior between Beautiful Soup and lxml.
flavor : str or None, container of strings
The parsing engine to use. 'bs4' and 'html5lib' are synonymous with
each other, they are both there for backwards compatibility. The
default of ``None`` tries to use ``lxml`` to parse and if that fails it
falls back on ``bs4`` + ``html5lib``.
header : int or list-like or None, optional
The row (or list of rows for a :class:`~pandas.MultiIndex`) to use to
make the columns headers.
index_col : int or list-like or None, optional
The column (or list of columns) to use to create the index.
skiprows : int or list-like or slice or None, optional
0-based. Number of rows to skip after parsing the column integer. If a
sequence of integers or a slice is given, will skip the rows indexed by
that sequence. Note that a single element sequence means 'skip the nth
row' whereas an integer means 'skip n rows'.
attrs : dict or None, optional
This is a dictionary of attributes that you can pass to use to identify
the table in the HTML. These are not checked for validity before being
passed to lxml or Beautiful Soup. However, these attributes must be
valid HTML table attributes to work correctly. For example, ::
attrs = {'id': 'table'}
is a valid attribute dictionary because the 'id' HTML tag attribute is
a valid HTML attribute for *any* HTML tag as per `this document
<http://www.w3.org/TR/html-markup/global-attributes.html>`__. ::
attrs = {'asdf': 'table'}
is *not* a valid attribute dictionary because 'asdf' is not a valid
HTML attribute even if it is a valid XML attribute. Valid HTML 4.01
table attributes can be found `here
<http://www.w3.org/TR/REC-html40/struct/tables.html#h-11.2>`__. A
working draft of the HTML 5 spec can be found `here
<http://www.w3.org/TR/html-markup/table.html>`__. It contains the
latest information on table attributes for the modern web.
parse_dates : bool, optional
See :func:`~read_csv` for more details.
tupleize_cols : bool, optional
If ``False`` try to parse multiple header rows into a
:class:`~pandas.MultiIndex`, otherwise return raw tuples. Defaults to
``False``.
.. deprecated:: 0.21.0
This argument will be removed and will always convert to MultiIndex
thousands : str, optional
Separator to use to parse thousands. Defaults to ``','``.
encoding : str or None, optional
The encoding used to decode the web page. Defaults to ``None``.``None``
preserves the previous encoding behavior, which depends on the
underlying parser library (e.g., the parser library will try to use
the encoding provided by the document).
decimal : str, default '.'
Character to recognize as decimal point (e.g. use ',' for European
data).
.. versionadded:: 0.19.0
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can
either be integers or column labels, values are functions that take one
input argument, the cell (not column) content, and return the
transformed content.
.. versionadded:: 0.19.0
na_values : iterable, default None
Custom NA values
.. versionadded:: 0.19.0
keep_default_na : bool, default True
If na_values are specified and keep_default_na is False the default NaN
values are overridden, otherwise they're appended to
.. versionadded:: 0.19.0
displayed_only : bool, default True
Whether elements with "display: none" should be parsed
.. versionadded:: 0.23.0
Returns
-------
dfs : list of DataFrames
See Also
--------
read_csv
Notes
-----
Before using this function you should read the :ref:`gotchas about the
HTML parsing libraries <io.html.gotchas>`.
Expect to do some cleanup after you call this function. For example, you
might need to manually assign column names if the column names are
converted to NaN when you pass the `header=0` argument. We try to assume as
little as possible about the structure of the table and push the
idiosyncrasies of the HTML contained in the table to the user.
This function searches for ``<table>`` elements and only for ``<tr>``
and ``<th>`` rows and ``<td>`` elements within each ``<tr>`` or ``<th>``
element in the table. ``<td>`` stands for "table data". This function
attempts to properly handle ``colspan`` and ``rowspan`` attributes.
If the function has a ``<thead>`` argument, it is used to construct
the header, otherwise the function attempts to find the header within
the body (by putting rows with only ``<th>`` elements into the header).
.. versionadded:: 0.21.0
Similar to :func:`~read_csv` the `header` argument is applied
**after** `skiprows` is applied.
This function will *always* return a list of :class:`DataFrame` *or*
it will fail, e.g., it will *not* return an empty list.
Examples
--------
See the :ref:`read_html documentation in the IO section of the docs
<io.read_html>` for some examples of reading in HTML tables. | pandas/io/html.py | def read_html(io, match='.+', flavor=None, header=None, index_col=None,
skiprows=None, attrs=None, parse_dates=False,
tupleize_cols=None, thousands=',', encoding=None,
decimal='.', converters=None, na_values=None,
keep_default_na=True, displayed_only=True):
r"""Read HTML tables into a ``list`` of ``DataFrame`` objects.
Parameters
----------
io : str or file-like
A URL, a file-like object, or a raw string containing HTML. Note that
lxml only accepts the http, ftp and file url protocols. If you have a
URL that starts with ``'https'`` you might try removing the ``'s'``.
match : str or compiled regular expression, optional
The set of tables containing text matching this regex or string will be
returned. Unless the HTML is extremely simple you will probably need to
pass a non-empty string here. Defaults to '.+' (match any non-empty
string). The default value will return all tables contained on a page.
This value is converted to a regular expression so that there is
consistent behavior between Beautiful Soup and lxml.
flavor : str or None, container of strings
The parsing engine to use. 'bs4' and 'html5lib' are synonymous with
each other, they are both there for backwards compatibility. The
default of ``None`` tries to use ``lxml`` to parse and if that fails it
falls back on ``bs4`` + ``html5lib``.
header : int or list-like or None, optional
The row (or list of rows for a :class:`~pandas.MultiIndex`) to use to
make the columns headers.
index_col : int or list-like or None, optional
The column (or list of columns) to use to create the index.
skiprows : int or list-like or slice or None, optional
0-based. Number of rows to skip after parsing the column integer. If a
sequence of integers or a slice is given, will skip the rows indexed by
that sequence. Note that a single element sequence means 'skip the nth
row' whereas an integer means 'skip n rows'.
attrs : dict or None, optional
This is a dictionary of attributes that you can pass to use to identify
the table in the HTML. These are not checked for validity before being
passed to lxml or Beautiful Soup. However, these attributes must be
valid HTML table attributes to work correctly. For example, ::
attrs = {'id': 'table'}
is a valid attribute dictionary because the 'id' HTML tag attribute is
a valid HTML attribute for *any* HTML tag as per `this document
<http://www.w3.org/TR/html-markup/global-attributes.html>`__. ::
attrs = {'asdf': 'table'}
is *not* a valid attribute dictionary because 'asdf' is not a valid
HTML attribute even if it is a valid XML attribute. Valid HTML 4.01
table attributes can be found `here
<http://www.w3.org/TR/REC-html40/struct/tables.html#h-11.2>`__. A
working draft of the HTML 5 spec can be found `here
<http://www.w3.org/TR/html-markup/table.html>`__. It contains the
latest information on table attributes for the modern web.
parse_dates : bool, optional
See :func:`~read_csv` for more details.
tupleize_cols : bool, optional
If ``False`` try to parse multiple header rows into a
:class:`~pandas.MultiIndex`, otherwise return raw tuples. Defaults to
``False``.
.. deprecated:: 0.21.0
This argument will be removed and will always convert to MultiIndex
thousands : str, optional
Separator to use to parse thousands. Defaults to ``','``.
encoding : str or None, optional
The encoding used to decode the web page. Defaults to ``None``.``None``
preserves the previous encoding behavior, which depends on the
underlying parser library (e.g., the parser library will try to use
the encoding provided by the document).
decimal : str, default '.'
Character to recognize as decimal point (e.g. use ',' for European
data).
.. versionadded:: 0.19.0
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can
either be integers or column labels, values are functions that take one
input argument, the cell (not column) content, and return the
transformed content.
.. versionadded:: 0.19.0
na_values : iterable, default None
Custom NA values
.. versionadded:: 0.19.0
keep_default_na : bool, default True
If na_values are specified and keep_default_na is False the default NaN
values are overridden, otherwise they're appended to
.. versionadded:: 0.19.0
displayed_only : bool, default True
Whether elements with "display: none" should be parsed
.. versionadded:: 0.23.0
Returns
-------
dfs : list of DataFrames
See Also
--------
read_csv
Notes
-----
Before using this function you should read the :ref:`gotchas about the
HTML parsing libraries <io.html.gotchas>`.
Expect to do some cleanup after you call this function. For example, you
might need to manually assign column names if the column names are
converted to NaN when you pass the `header=0` argument. We try to assume as
little as possible about the structure of the table and push the
idiosyncrasies of the HTML contained in the table to the user.
This function searches for ``<table>`` elements and only for ``<tr>``
and ``<th>`` rows and ``<td>`` elements within each ``<tr>`` or ``<th>``
element in the table. ``<td>`` stands for "table data". This function
attempts to properly handle ``colspan`` and ``rowspan`` attributes.
If the function has a ``<thead>`` argument, it is used to construct
the header, otherwise the function attempts to find the header within
the body (by putting rows with only ``<th>`` elements into the header).
.. versionadded:: 0.21.0
Similar to :func:`~read_csv` the `header` argument is applied
**after** `skiprows` is applied.
This function will *always* return a list of :class:`DataFrame` *or*
it will fail, e.g., it will *not* return an empty list.
Examples
--------
See the :ref:`read_html documentation in the IO section of the docs
<io.read_html>` for some examples of reading in HTML tables.
"""
_importers()
# Type check here. We don't want to parse only to fail because of an
# invalid value of an integer skiprows.
if isinstance(skiprows, numbers.Integral) and skiprows < 0:
raise ValueError('cannot skip rows starting from the end of the '
'data (you passed a negative value)')
_validate_header_arg(header)
return _parse(flavor=flavor, io=io, match=match, header=header,
index_col=index_col, skiprows=skiprows,
parse_dates=parse_dates, tupleize_cols=tupleize_cols,
thousands=thousands, attrs=attrs, encoding=encoding,
decimal=decimal, converters=converters, na_values=na_values,
keep_default_na=keep_default_na,
displayed_only=displayed_only) | def read_html(io, match='.+', flavor=None, header=None, index_col=None,
skiprows=None, attrs=None, parse_dates=False,
tupleize_cols=None, thousands=',', encoding=None,
decimal='.', converters=None, na_values=None,
keep_default_na=True, displayed_only=True):
r"""Read HTML tables into a ``list`` of ``DataFrame`` objects.
Parameters
----------
io : str or file-like
A URL, a file-like object, or a raw string containing HTML. Note that
lxml only accepts the http, ftp and file url protocols. If you have a
URL that starts with ``'https'`` you might try removing the ``'s'``.
match : str or compiled regular expression, optional
The set of tables containing text matching this regex or string will be
returned. Unless the HTML is extremely simple you will probably need to
pass a non-empty string here. Defaults to '.+' (match any non-empty
string). The default value will return all tables contained on a page.
This value is converted to a regular expression so that there is
consistent behavior between Beautiful Soup and lxml.
flavor : str or None, container of strings
The parsing engine to use. 'bs4' and 'html5lib' are synonymous with
each other, they are both there for backwards compatibility. The
default of ``None`` tries to use ``lxml`` to parse and if that fails it
falls back on ``bs4`` + ``html5lib``.
header : int or list-like or None, optional
The row (or list of rows for a :class:`~pandas.MultiIndex`) to use to
make the columns headers.
index_col : int or list-like or None, optional
The column (or list of columns) to use to create the index.
skiprows : int or list-like or slice or None, optional
0-based. Number of rows to skip after parsing the column integer. If a
sequence of integers or a slice is given, will skip the rows indexed by
that sequence. Note that a single element sequence means 'skip the nth
row' whereas an integer means 'skip n rows'.
attrs : dict or None, optional
This is a dictionary of attributes that you can pass to use to identify
the table in the HTML. These are not checked for validity before being
passed to lxml or Beautiful Soup. However, these attributes must be
valid HTML table attributes to work correctly. For example, ::
attrs = {'id': 'table'}
is a valid attribute dictionary because the 'id' HTML tag attribute is
a valid HTML attribute for *any* HTML tag as per `this document
<http://www.w3.org/TR/html-markup/global-attributes.html>`__. ::
attrs = {'asdf': 'table'}
is *not* a valid attribute dictionary because 'asdf' is not a valid
HTML attribute even if it is a valid XML attribute. Valid HTML 4.01
table attributes can be found `here
<http://www.w3.org/TR/REC-html40/struct/tables.html#h-11.2>`__. A
working draft of the HTML 5 spec can be found `here
<http://www.w3.org/TR/html-markup/table.html>`__. It contains the
latest information on table attributes for the modern web.
parse_dates : bool, optional
See :func:`~read_csv` for more details.
tupleize_cols : bool, optional
If ``False`` try to parse multiple header rows into a
:class:`~pandas.MultiIndex`, otherwise return raw tuples. Defaults to
``False``.
.. deprecated:: 0.21.0
This argument will be removed and will always convert to MultiIndex
thousands : str, optional
Separator to use to parse thousands. Defaults to ``','``.
encoding : str or None, optional
The encoding used to decode the web page. Defaults to ``None``.``None``
preserves the previous encoding behavior, which depends on the
underlying parser library (e.g., the parser library will try to use
the encoding provided by the document).
decimal : str, default '.'
Character to recognize as decimal point (e.g. use ',' for European
data).
.. versionadded:: 0.19.0
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can
either be integers or column labels, values are functions that take one
input argument, the cell (not column) content, and return the
transformed content.
.. versionadded:: 0.19.0
na_values : iterable, default None
Custom NA values
.. versionadded:: 0.19.0
keep_default_na : bool, default True
If na_values are specified and keep_default_na is False the default NaN
values are overridden, otherwise they're appended to
.. versionadded:: 0.19.0
displayed_only : bool, default True
Whether elements with "display: none" should be parsed
.. versionadded:: 0.23.0
Returns
-------
dfs : list of DataFrames
See Also
--------
read_csv
Notes
-----
Before using this function you should read the :ref:`gotchas about the
HTML parsing libraries <io.html.gotchas>`.
Expect to do some cleanup after you call this function. For example, you
might need to manually assign column names if the column names are
converted to NaN when you pass the `header=0` argument. We try to assume as
little as possible about the structure of the table and push the
idiosyncrasies of the HTML contained in the table to the user.
This function searches for ``<table>`` elements and only for ``<tr>``
and ``<th>`` rows and ``<td>`` elements within each ``<tr>`` or ``<th>``
element in the table. ``<td>`` stands for "table data". This function
attempts to properly handle ``colspan`` and ``rowspan`` attributes.
If the function has a ``<thead>`` argument, it is used to construct
the header, otherwise the function attempts to find the header within
the body (by putting rows with only ``<th>`` elements into the header).
.. versionadded:: 0.21.0
Similar to :func:`~read_csv` the `header` argument is applied
**after** `skiprows` is applied.
This function will *always* return a list of :class:`DataFrame` *or*
it will fail, e.g., it will *not* return an empty list.
Examples
--------
See the :ref:`read_html documentation in the IO section of the docs
<io.read_html>` for some examples of reading in HTML tables.
"""
_importers()
# Type check here. We don't want to parse only to fail because of an
# invalid value of an integer skiprows.
if isinstance(skiprows, numbers.Integral) and skiprows < 0:
raise ValueError('cannot skip rows starting from the end of the '
'data (you passed a negative value)')
_validate_header_arg(header)
return _parse(flavor=flavor, io=io, match=match, header=header,
index_col=index_col, skiprows=skiprows,
parse_dates=parse_dates, tupleize_cols=tupleize_cols,
thousands=thousands, attrs=attrs, encoding=encoding,
decimal=decimal, converters=converters, na_values=na_values,
keep_default_na=keep_default_na,
displayed_only=displayed_only) | [
"r",
"Read",
"HTML",
"tables",
"into",
"a",
"list",
"of",
"DataFrame",
"objects",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L921-L1088 | [
"def",
"read_html",
"(",
"io",
",",
"match",
"=",
"'.+'",
",",
"flavor",
"=",
"None",
",",
"header",
"=",
"None",
",",
"index_col",
"=",
"None",
",",
"skiprows",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"parse_dates",
"=",
"False",
",",
"tupleize_cols",
"=",
"None",
",",
"thousands",
"=",
"','",
",",
"encoding",
"=",
"None",
",",
"decimal",
"=",
"'.'",
",",
"converters",
"=",
"None",
",",
"na_values",
"=",
"None",
",",
"keep_default_na",
"=",
"True",
",",
"displayed_only",
"=",
"True",
")",
":",
"_importers",
"(",
")",
"# Type check here. We don't want to parse only to fail because of an",
"# invalid value of an integer skiprows.",
"if",
"isinstance",
"(",
"skiprows",
",",
"numbers",
".",
"Integral",
")",
"and",
"skiprows",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'cannot skip rows starting from the end of the '",
"'data (you passed a negative value)'",
")",
"_validate_header_arg",
"(",
"header",
")",
"return",
"_parse",
"(",
"flavor",
"=",
"flavor",
",",
"io",
"=",
"io",
",",
"match",
"=",
"match",
",",
"header",
"=",
"header",
",",
"index_col",
"=",
"index_col",
",",
"skiprows",
"=",
"skiprows",
",",
"parse_dates",
"=",
"parse_dates",
",",
"tupleize_cols",
"=",
"tupleize_cols",
",",
"thousands",
"=",
"thousands",
",",
"attrs",
"=",
"attrs",
",",
"encoding",
"=",
"encoding",
",",
"decimal",
"=",
"decimal",
",",
"converters",
"=",
"converters",
",",
"na_values",
"=",
"na_values",
",",
"keep_default_na",
"=",
"keep_default_na",
",",
"displayed_only",
"=",
"displayed_only",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _HtmlFrameParser.parse_tables | Parse and return all tables from the DOM.
Returns
-------
list of parsed (header, body, footer) tuples from tables. | pandas/io/html.py | def parse_tables(self):
"""
Parse and return all tables from the DOM.
Returns
-------
list of parsed (header, body, footer) tuples from tables.
"""
tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
return (self._parse_thead_tbody_tfoot(table) for table in tables) | def parse_tables(self):
"""
Parse and return all tables from the DOM.
Returns
-------
list of parsed (header, body, footer) tuples from tables.
"""
tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
return (self._parse_thead_tbody_tfoot(table) for table in tables) | [
"Parse",
"and",
"return",
"all",
"tables",
"from",
"the",
"DOM",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L208-L217 | [
"def",
"parse_tables",
"(",
"self",
")",
":",
"tables",
"=",
"self",
".",
"_parse_tables",
"(",
"self",
".",
"_build_doc",
"(",
")",
",",
"self",
".",
"match",
",",
"self",
".",
"attrs",
")",
"return",
"(",
"self",
".",
"_parse_thead_tbody_tfoot",
"(",
"table",
")",
"for",
"table",
"in",
"tables",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _HtmlFrameParser._parse_thead_tbody_tfoot | Given a table, return parsed header, body, and foot.
Parameters
----------
table_html : node-like
Returns
-------
tuple of (header, body, footer), each a list of list-of-text rows.
Notes
-----
Header and body are lists-of-lists. Top level list is a list of
rows. Each row is a list of str text.
Logic: Use <thead>, <tbody>, <tfoot> elements to identify
header, body, and footer, otherwise:
- Put all rows into body
- Move rows from top of body to header only if
all elements inside row are <th>
- Move rows from bottom of body to footer only if
all elements inside row are <th> | pandas/io/html.py | def _parse_thead_tbody_tfoot(self, table_html):
"""
Given a table, return parsed header, body, and foot.
Parameters
----------
table_html : node-like
Returns
-------
tuple of (header, body, footer), each a list of list-of-text rows.
Notes
-----
Header and body are lists-of-lists. Top level list is a list of
rows. Each row is a list of str text.
Logic: Use <thead>, <tbody>, <tfoot> elements to identify
header, body, and footer, otherwise:
- Put all rows into body
- Move rows from top of body to header only if
all elements inside row are <th>
- Move rows from bottom of body to footer only if
all elements inside row are <th>
"""
header_rows = self._parse_thead_tr(table_html)
body_rows = self._parse_tbody_tr(table_html)
footer_rows = self._parse_tfoot_tr(table_html)
def row_is_all_th(row):
return all(self._equals_tag(t, 'th') for t in
self._parse_td(row))
if not header_rows:
# The table has no <thead>. Move the top all-<th> rows from
# body_rows to header_rows. (This is a common case because many
# tables in the wild have no <thead> or <tfoot>
while body_rows and row_is_all_th(body_rows[0]):
header_rows.append(body_rows.pop(0))
header = self._expand_colspan_rowspan(header_rows)
body = self._expand_colspan_rowspan(body_rows)
footer = self._expand_colspan_rowspan(footer_rows)
return header, body, footer | def _parse_thead_tbody_tfoot(self, table_html):
"""
Given a table, return parsed header, body, and foot.
Parameters
----------
table_html : node-like
Returns
-------
tuple of (header, body, footer), each a list of list-of-text rows.
Notes
-----
Header and body are lists-of-lists. Top level list is a list of
rows. Each row is a list of str text.
Logic: Use <thead>, <tbody>, <tfoot> elements to identify
header, body, and footer, otherwise:
- Put all rows into body
- Move rows from top of body to header only if
all elements inside row are <th>
- Move rows from bottom of body to footer only if
all elements inside row are <th>
"""
header_rows = self._parse_thead_tr(table_html)
body_rows = self._parse_tbody_tr(table_html)
footer_rows = self._parse_tfoot_tr(table_html)
def row_is_all_th(row):
return all(self._equals_tag(t, 'th') for t in
self._parse_td(row))
if not header_rows:
# The table has no <thead>. Move the top all-<th> rows from
# body_rows to header_rows. (This is a common case because many
# tables in the wild have no <thead> or <tfoot>
while body_rows and row_is_all_th(body_rows[0]):
header_rows.append(body_rows.pop(0))
header = self._expand_colspan_rowspan(header_rows)
body = self._expand_colspan_rowspan(body_rows)
footer = self._expand_colspan_rowspan(footer_rows)
return header, body, footer | [
"Given",
"a",
"table",
"return",
"parsed",
"header",
"body",
"and",
"foot",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L375-L420 | [
"def",
"_parse_thead_tbody_tfoot",
"(",
"self",
",",
"table_html",
")",
":",
"header_rows",
"=",
"self",
".",
"_parse_thead_tr",
"(",
"table_html",
")",
"body_rows",
"=",
"self",
".",
"_parse_tbody_tr",
"(",
"table_html",
")",
"footer_rows",
"=",
"self",
".",
"_parse_tfoot_tr",
"(",
"table_html",
")",
"def",
"row_is_all_th",
"(",
"row",
")",
":",
"return",
"all",
"(",
"self",
".",
"_equals_tag",
"(",
"t",
",",
"'th'",
")",
"for",
"t",
"in",
"self",
".",
"_parse_td",
"(",
"row",
")",
")",
"if",
"not",
"header_rows",
":",
"# The table has no <thead>. Move the top all-<th> rows from",
"# body_rows to header_rows. (This is a common case because many",
"# tables in the wild have no <thead> or <tfoot>",
"while",
"body_rows",
"and",
"row_is_all_th",
"(",
"body_rows",
"[",
"0",
"]",
")",
":",
"header_rows",
".",
"append",
"(",
"body_rows",
".",
"pop",
"(",
"0",
")",
")",
"header",
"=",
"self",
".",
"_expand_colspan_rowspan",
"(",
"header_rows",
")",
"body",
"=",
"self",
".",
"_expand_colspan_rowspan",
"(",
"body_rows",
")",
"footer",
"=",
"self",
".",
"_expand_colspan_rowspan",
"(",
"footer_rows",
")",
"return",
"header",
",",
"body",
",",
"footer"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _HtmlFrameParser._expand_colspan_rowspan | Given a list of <tr>s, return a list of text rows.
Parameters
----------
rows : list of node-like
List of <tr>s
Returns
-------
list of list
Each returned row is a list of str text.
Notes
-----
Any cell with ``rowspan`` or ``colspan`` will have its contents copied
to subsequent cells. | pandas/io/html.py | def _expand_colspan_rowspan(self, rows):
"""
Given a list of <tr>s, return a list of text rows.
Parameters
----------
rows : list of node-like
List of <tr>s
Returns
-------
list of list
Each returned row is a list of str text.
Notes
-----
Any cell with ``rowspan`` or ``colspan`` will have its contents copied
to subsequent cells.
"""
all_texts = [] # list of rows, each a list of str
remainder = [] # list of (index, text, nrows)
for tr in rows:
texts = [] # the output for this row
next_remainder = []
index = 0
tds = self._parse_td(tr)
for td in tds:
# Append texts from previous rows with rowspan>1 that come
# before this <td>
while remainder and remainder[0][0] <= index:
prev_i, prev_text, prev_rowspan = remainder.pop(0)
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
index += 1
# Append the text from this <td>, colspan times
text = _remove_whitespace(self._text_getter(td))
rowspan = int(self._attr_getter(td, 'rowspan') or 1)
colspan = int(self._attr_getter(td, 'colspan') or 1)
for _ in range(colspan):
texts.append(text)
if rowspan > 1:
next_remainder.append((index, text, rowspan - 1))
index += 1
# Append texts from previous rows at the final position
for prev_i, prev_text, prev_rowspan in remainder:
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
all_texts.append(texts)
remainder = next_remainder
# Append rows that only appear because the previous row had non-1
# rowspan
while remainder:
next_remainder = []
texts = []
for prev_i, prev_text, prev_rowspan in remainder:
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
all_texts.append(texts)
remainder = next_remainder
return all_texts | def _expand_colspan_rowspan(self, rows):
"""
Given a list of <tr>s, return a list of text rows.
Parameters
----------
rows : list of node-like
List of <tr>s
Returns
-------
list of list
Each returned row is a list of str text.
Notes
-----
Any cell with ``rowspan`` or ``colspan`` will have its contents copied
to subsequent cells.
"""
all_texts = [] # list of rows, each a list of str
remainder = [] # list of (index, text, nrows)
for tr in rows:
texts = [] # the output for this row
next_remainder = []
index = 0
tds = self._parse_td(tr)
for td in tds:
# Append texts from previous rows with rowspan>1 that come
# before this <td>
while remainder and remainder[0][0] <= index:
prev_i, prev_text, prev_rowspan = remainder.pop(0)
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
index += 1
# Append the text from this <td>, colspan times
text = _remove_whitespace(self._text_getter(td))
rowspan = int(self._attr_getter(td, 'rowspan') or 1)
colspan = int(self._attr_getter(td, 'colspan') or 1)
for _ in range(colspan):
texts.append(text)
if rowspan > 1:
next_remainder.append((index, text, rowspan - 1))
index += 1
# Append texts from previous rows at the final position
for prev_i, prev_text, prev_rowspan in remainder:
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
all_texts.append(texts)
remainder = next_remainder
# Append rows that only appear because the previous row had non-1
# rowspan
while remainder:
next_remainder = []
texts = []
for prev_i, prev_text, prev_rowspan in remainder:
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text,
prev_rowspan - 1))
all_texts.append(texts)
remainder = next_remainder
return all_texts | [
"Given",
"a",
"list",
"of",
"<tr",
">",
"s",
"return",
"a",
"list",
"of",
"text",
"rows",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L422-L496 | [
"def",
"_expand_colspan_rowspan",
"(",
"self",
",",
"rows",
")",
":",
"all_texts",
"=",
"[",
"]",
"# list of rows, each a list of str",
"remainder",
"=",
"[",
"]",
"# list of (index, text, nrows)",
"for",
"tr",
"in",
"rows",
":",
"texts",
"=",
"[",
"]",
"# the output for this row",
"next_remainder",
"=",
"[",
"]",
"index",
"=",
"0",
"tds",
"=",
"self",
".",
"_parse_td",
"(",
"tr",
")",
"for",
"td",
"in",
"tds",
":",
"# Append texts from previous rows with rowspan>1 that come",
"# before this <td>",
"while",
"remainder",
"and",
"remainder",
"[",
"0",
"]",
"[",
"0",
"]",
"<=",
"index",
":",
"prev_i",
",",
"prev_text",
",",
"prev_rowspan",
"=",
"remainder",
".",
"pop",
"(",
"0",
")",
"texts",
".",
"append",
"(",
"prev_text",
")",
"if",
"prev_rowspan",
">",
"1",
":",
"next_remainder",
".",
"append",
"(",
"(",
"prev_i",
",",
"prev_text",
",",
"prev_rowspan",
"-",
"1",
")",
")",
"index",
"+=",
"1",
"# Append the text from this <td>, colspan times",
"text",
"=",
"_remove_whitespace",
"(",
"self",
".",
"_text_getter",
"(",
"td",
")",
")",
"rowspan",
"=",
"int",
"(",
"self",
".",
"_attr_getter",
"(",
"td",
",",
"'rowspan'",
")",
"or",
"1",
")",
"colspan",
"=",
"int",
"(",
"self",
".",
"_attr_getter",
"(",
"td",
",",
"'colspan'",
")",
"or",
"1",
")",
"for",
"_",
"in",
"range",
"(",
"colspan",
")",
":",
"texts",
".",
"append",
"(",
"text",
")",
"if",
"rowspan",
">",
"1",
":",
"next_remainder",
".",
"append",
"(",
"(",
"index",
",",
"text",
",",
"rowspan",
"-",
"1",
")",
")",
"index",
"+=",
"1",
"# Append texts from previous rows at the final position",
"for",
"prev_i",
",",
"prev_text",
",",
"prev_rowspan",
"in",
"remainder",
":",
"texts",
".",
"append",
"(",
"prev_text",
")",
"if",
"prev_rowspan",
">",
"1",
":",
"next_remainder",
".",
"append",
"(",
"(",
"prev_i",
",",
"prev_text",
",",
"prev_rowspan",
"-",
"1",
")",
")",
"all_texts",
".",
"append",
"(",
"texts",
")",
"remainder",
"=",
"next_remainder",
"# Append rows that only appear because the previous row had non-1",
"# rowspan",
"while",
"remainder",
":",
"next_remainder",
"=",
"[",
"]",
"texts",
"=",
"[",
"]",
"for",
"prev_i",
",",
"prev_text",
",",
"prev_rowspan",
"in",
"remainder",
":",
"texts",
".",
"append",
"(",
"prev_text",
")",
"if",
"prev_rowspan",
">",
"1",
":",
"next_remainder",
".",
"append",
"(",
"(",
"prev_i",
",",
"prev_text",
",",
"prev_rowspan",
"-",
"1",
")",
")",
"all_texts",
".",
"append",
"(",
"texts",
")",
"remainder",
"=",
"next_remainder",
"return",
"all_texts"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _HtmlFrameParser._handle_hidden_tables | Return list of tables, potentially removing hidden elements
Parameters
----------
tbl_list : list of node-like
Type of list elements will vary depending upon parser used
attr_name : str
Name of the accessor for retrieving HTML attributes
Returns
-------
list of node-like
Return type matches `tbl_list` | pandas/io/html.py | def _handle_hidden_tables(self, tbl_list, attr_name):
"""
Return list of tables, potentially removing hidden elements
Parameters
----------
tbl_list : list of node-like
Type of list elements will vary depending upon parser used
attr_name : str
Name of the accessor for retrieving HTML attributes
Returns
-------
list of node-like
Return type matches `tbl_list`
"""
if not self.displayed_only:
return tbl_list
return [x for x in tbl_list if "display:none" not in
getattr(x, attr_name).get('style', '').replace(" ", "")] | def _handle_hidden_tables(self, tbl_list, attr_name):
"""
Return list of tables, potentially removing hidden elements
Parameters
----------
tbl_list : list of node-like
Type of list elements will vary depending upon parser used
attr_name : str
Name of the accessor for retrieving HTML attributes
Returns
-------
list of node-like
Return type matches `tbl_list`
"""
if not self.displayed_only:
return tbl_list
return [x for x in tbl_list if "display:none" not in
getattr(x, attr_name).get('style', '').replace(" ", "")] | [
"Return",
"list",
"of",
"tables",
"potentially",
"removing",
"hidden",
"elements"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L498-L518 | [
"def",
"_handle_hidden_tables",
"(",
"self",
",",
"tbl_list",
",",
"attr_name",
")",
":",
"if",
"not",
"self",
".",
"displayed_only",
":",
"return",
"tbl_list",
"return",
"[",
"x",
"for",
"x",
"in",
"tbl_list",
"if",
"\"display:none\"",
"not",
"in",
"getattr",
"(",
"x",
",",
"attr_name",
")",
".",
"get",
"(",
"'style'",
",",
"''",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _LxmlFrameParser._build_doc | Raises
------
ValueError
* If a URL that lxml cannot parse is passed.
Exception
* Any other ``Exception`` thrown. For example, trying to parse a
URL that is syntactically correct on a machine with no internet
connection will fail.
See Also
--------
pandas.io.html._HtmlFrameParser._build_doc | pandas/io/html.py | def _build_doc(self):
"""
Raises
------
ValueError
* If a URL that lxml cannot parse is passed.
Exception
* Any other ``Exception`` thrown. For example, trying to parse a
URL that is syntactically correct on a machine with no internet
connection will fail.
See Also
--------
pandas.io.html._HtmlFrameParser._build_doc
"""
from lxml.html import parse, fromstring, HTMLParser
from lxml.etree import XMLSyntaxError
parser = HTMLParser(recover=True, encoding=self.encoding)
try:
if _is_url(self.io):
with urlopen(self.io) as f:
r = parse(f, parser=parser)
else:
# try to parse the input in the simplest way
r = parse(self.io, parser=parser)
try:
r = r.getroot()
except AttributeError:
pass
except (UnicodeDecodeError, IOError) as e:
# if the input is a blob of html goop
if not _is_url(self.io):
r = fromstring(self.io, parser=parser)
try:
r = r.getroot()
except AttributeError:
pass
else:
raise e
else:
if not hasattr(r, 'text_content'):
raise XMLSyntaxError("no text parsed from document", 0, 0, 0)
return r | def _build_doc(self):
"""
Raises
------
ValueError
* If a URL that lxml cannot parse is passed.
Exception
* Any other ``Exception`` thrown. For example, trying to parse a
URL that is syntactically correct on a machine with no internet
connection will fail.
See Also
--------
pandas.io.html._HtmlFrameParser._build_doc
"""
from lxml.html import parse, fromstring, HTMLParser
from lxml.etree import XMLSyntaxError
parser = HTMLParser(recover=True, encoding=self.encoding)
try:
if _is_url(self.io):
with urlopen(self.io) as f:
r = parse(f, parser=parser)
else:
# try to parse the input in the simplest way
r = parse(self.io, parser=parser)
try:
r = r.getroot()
except AttributeError:
pass
except (UnicodeDecodeError, IOError) as e:
# if the input is a blob of html goop
if not _is_url(self.io):
r = fromstring(self.io, parser=parser)
try:
r = r.getroot()
except AttributeError:
pass
else:
raise e
else:
if not hasattr(r, 'text_content'):
raise XMLSyntaxError("no text parsed from document", 0, 0, 0)
return r | [
"Raises",
"------",
"ValueError",
"*",
"If",
"a",
"URL",
"that",
"lxml",
"cannot",
"parse",
"is",
"passed",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L690-L735 | [
"def",
"_build_doc",
"(",
"self",
")",
":",
"from",
"lxml",
".",
"html",
"import",
"parse",
",",
"fromstring",
",",
"HTMLParser",
"from",
"lxml",
".",
"etree",
"import",
"XMLSyntaxError",
"parser",
"=",
"HTMLParser",
"(",
"recover",
"=",
"True",
",",
"encoding",
"=",
"self",
".",
"encoding",
")",
"try",
":",
"if",
"_is_url",
"(",
"self",
".",
"io",
")",
":",
"with",
"urlopen",
"(",
"self",
".",
"io",
")",
"as",
"f",
":",
"r",
"=",
"parse",
"(",
"f",
",",
"parser",
"=",
"parser",
")",
"else",
":",
"# try to parse the input in the simplest way",
"r",
"=",
"parse",
"(",
"self",
".",
"io",
",",
"parser",
"=",
"parser",
")",
"try",
":",
"r",
"=",
"r",
".",
"getroot",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"except",
"(",
"UnicodeDecodeError",
",",
"IOError",
")",
"as",
"e",
":",
"# if the input is a blob of html goop",
"if",
"not",
"_is_url",
"(",
"self",
".",
"io",
")",
":",
"r",
"=",
"fromstring",
"(",
"self",
".",
"io",
",",
"parser",
"=",
"parser",
")",
"try",
":",
"r",
"=",
"r",
".",
"getroot",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"raise",
"e",
"else",
":",
"if",
"not",
"hasattr",
"(",
"r",
",",
"'text_content'",
")",
":",
"raise",
"XMLSyntaxError",
"(",
"\"no text parsed from document\"",
",",
"0",
",",
"0",
",",
"0",
")",
"return",
"r"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | get_dtype_kinds | Parameters
----------
l : list of arrays
Returns
-------
a set of kinds that exist in this list of arrays | pandas/core/dtypes/concat.py | def get_dtype_kinds(l):
"""
Parameters
----------
l : list of arrays
Returns
-------
a set of kinds that exist in this list of arrays
"""
typs = set()
for arr in l:
dtype = arr.dtype
if is_categorical_dtype(dtype):
typ = 'category'
elif is_sparse(arr):
typ = 'sparse'
elif isinstance(arr, ABCRangeIndex):
typ = 'range'
elif is_datetime64tz_dtype(arr):
# if to_concat contains different tz,
# the result must be object dtype
typ = str(arr.dtype)
elif is_datetime64_dtype(dtype):
typ = 'datetime'
elif is_timedelta64_dtype(dtype):
typ = 'timedelta'
elif is_object_dtype(dtype):
typ = 'object'
elif is_bool_dtype(dtype):
typ = 'bool'
elif is_extension_array_dtype(dtype):
typ = str(arr.dtype)
else:
typ = dtype.kind
typs.add(typ)
return typs | def get_dtype_kinds(l):
"""
Parameters
----------
l : list of arrays
Returns
-------
a set of kinds that exist in this list of arrays
"""
typs = set()
for arr in l:
dtype = arr.dtype
if is_categorical_dtype(dtype):
typ = 'category'
elif is_sparse(arr):
typ = 'sparse'
elif isinstance(arr, ABCRangeIndex):
typ = 'range'
elif is_datetime64tz_dtype(arr):
# if to_concat contains different tz,
# the result must be object dtype
typ = str(arr.dtype)
elif is_datetime64_dtype(dtype):
typ = 'datetime'
elif is_timedelta64_dtype(dtype):
typ = 'timedelta'
elif is_object_dtype(dtype):
typ = 'object'
elif is_bool_dtype(dtype):
typ = 'bool'
elif is_extension_array_dtype(dtype):
typ = str(arr.dtype)
else:
typ = dtype.kind
typs.add(typ)
return typs | [
"Parameters",
"----------",
"l",
":",
"list",
"of",
"arrays"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/concat.py#L18-L56 | [
"def",
"get_dtype_kinds",
"(",
"l",
")",
":",
"typs",
"=",
"set",
"(",
")",
"for",
"arr",
"in",
"l",
":",
"dtype",
"=",
"arr",
".",
"dtype",
"if",
"is_categorical_dtype",
"(",
"dtype",
")",
":",
"typ",
"=",
"'category'",
"elif",
"is_sparse",
"(",
"arr",
")",
":",
"typ",
"=",
"'sparse'",
"elif",
"isinstance",
"(",
"arr",
",",
"ABCRangeIndex",
")",
":",
"typ",
"=",
"'range'",
"elif",
"is_datetime64tz_dtype",
"(",
"arr",
")",
":",
"# if to_concat contains different tz,",
"# the result must be object dtype",
"typ",
"=",
"str",
"(",
"arr",
".",
"dtype",
")",
"elif",
"is_datetime64_dtype",
"(",
"dtype",
")",
":",
"typ",
"=",
"'datetime'",
"elif",
"is_timedelta64_dtype",
"(",
"dtype",
")",
":",
"typ",
"=",
"'timedelta'",
"elif",
"is_object_dtype",
"(",
"dtype",
")",
":",
"typ",
"=",
"'object'",
"elif",
"is_bool_dtype",
"(",
"dtype",
")",
":",
"typ",
"=",
"'bool'",
"elif",
"is_extension_array_dtype",
"(",
"dtype",
")",
":",
"typ",
"=",
"str",
"(",
"arr",
".",
"dtype",
")",
"else",
":",
"typ",
"=",
"dtype",
".",
"kind",
"typs",
".",
"add",
"(",
"typ",
")",
"return",
"typs"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.