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 | MPLPlot._has_plotted_object | check whether ax has data | pandas/plotting/_core.py | def _has_plotted_object(self, ax):
"""check whether ax has data"""
return (len(ax.lines) != 0 or
len(ax.artists) != 0 or
len(ax.containers) != 0) | def _has_plotted_object(self, ax):
"""check whether ax has data"""
return (len(ax.lines) != 0 or
len(ax.artists) != 0 or
len(ax.containers) != 0) | [
"check",
"whether",
"ax",
"has",
"data"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L260-L264 | [
"def",
"_has_plotted_object",
"(",
"self",
",",
"ax",
")",
":",
"return",
"(",
"len",
"(",
"ax",
".",
"lines",
")",
"!=",
"0",
"or",
"len",
"(",
"ax",
".",
"artists",
")",
"!=",
"0",
"or",
"len",
"(",
"ax",
".",
"containers",
")",
"!=",
"0",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | MPLPlot.result | Return result axes | pandas/plotting/_core.py | def result(self):
"""
Return result axes
"""
if self.subplots:
if self.layout is not None and not is_list_like(self.ax):
return self.axes.reshape(*self.layout)
else:
return self.axes
else:
sec_true = isinstance(self.secondary_y, bool) and self.secondary_y
all_sec = (is_list_like(self.secondary_y) and
len(self.secondary_y) == self.nseries)
if (sec_true or all_sec):
# if all data is plotted on secondary, return right axes
return self._get_ax_layer(self.axes[0], primary=False)
else:
return self.axes[0] | def result(self):
"""
Return result axes
"""
if self.subplots:
if self.layout is not None and not is_list_like(self.ax):
return self.axes.reshape(*self.layout)
else:
return self.axes
else:
sec_true = isinstance(self.secondary_y, bool) and self.secondary_y
all_sec = (is_list_like(self.secondary_y) and
len(self.secondary_y) == self.nseries)
if (sec_true or all_sec):
# if all data is plotted on secondary, return right axes
return self._get_ax_layer(self.axes[0], primary=False)
else:
return self.axes[0] | [
"Return",
"result",
"axes"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L336-L353 | [
"def",
"result",
"(",
"self",
")",
":",
"if",
"self",
".",
"subplots",
":",
"if",
"self",
".",
"layout",
"is",
"not",
"None",
"and",
"not",
"is_list_like",
"(",
"self",
".",
"ax",
")",
":",
"return",
"self",
".",
"axes",
".",
"reshape",
"(",
"*",
"self",
".",
"layout",
")",
"else",
":",
"return",
"self",
".",
"axes",
"else",
":",
"sec_true",
"=",
"isinstance",
"(",
"self",
".",
"secondary_y",
",",
"bool",
")",
"and",
"self",
".",
"secondary_y",
"all_sec",
"=",
"(",
"is_list_like",
"(",
"self",
".",
"secondary_y",
")",
"and",
"len",
"(",
"self",
".",
"secondary_y",
")",
"==",
"self",
".",
"nseries",
")",
"if",
"(",
"sec_true",
"or",
"all_sec",
")",
":",
"# if all data is plotted on secondary, return right axes",
"return",
"self",
".",
"_get_ax_layer",
"(",
"self",
".",
"axes",
"[",
"0",
"]",
",",
"primary",
"=",
"False",
")",
"else",
":",
"return",
"self",
".",
"axes",
"[",
"0",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | MPLPlot._post_plot_logic_common | Common post process for each axes | pandas/plotting/_core.py | def _post_plot_logic_common(self, ax, data):
"""Common post process for each axes"""
def get_label(i):
try:
return pprint_thing(data.index[i])
except Exception:
return ''
if self.orientation == 'vertical' or self.orientation is None:
if self._need_to_set_index:
xticklabels = [get_label(x) for x in ax.get_xticks()]
ax.set_xticklabels(xticklabels)
self._apply_axis_properties(ax.xaxis, rot=self.rot,
fontsize=self.fontsize)
self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)
if hasattr(ax, 'right_ax'):
self._apply_axis_properties(ax.right_ax.yaxis,
fontsize=self.fontsize)
elif self.orientation == 'horizontal':
if self._need_to_set_index:
yticklabels = [get_label(y) for y in ax.get_yticks()]
ax.set_yticklabels(yticklabels)
self._apply_axis_properties(ax.yaxis, rot=self.rot,
fontsize=self.fontsize)
self._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)
if hasattr(ax, 'right_ax'):
self._apply_axis_properties(ax.right_ax.yaxis,
fontsize=self.fontsize)
else: # pragma no cover
raise ValueError | def _post_plot_logic_common(self, ax, data):
"""Common post process for each axes"""
def get_label(i):
try:
return pprint_thing(data.index[i])
except Exception:
return ''
if self.orientation == 'vertical' or self.orientation is None:
if self._need_to_set_index:
xticklabels = [get_label(x) for x in ax.get_xticks()]
ax.set_xticklabels(xticklabels)
self._apply_axis_properties(ax.xaxis, rot=self.rot,
fontsize=self.fontsize)
self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)
if hasattr(ax, 'right_ax'):
self._apply_axis_properties(ax.right_ax.yaxis,
fontsize=self.fontsize)
elif self.orientation == 'horizontal':
if self._need_to_set_index:
yticklabels = [get_label(y) for y in ax.get_yticks()]
ax.set_yticklabels(yticklabels)
self._apply_axis_properties(ax.yaxis, rot=self.rot,
fontsize=self.fontsize)
self._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)
if hasattr(ax, 'right_ax'):
self._apply_axis_properties(ax.right_ax.yaxis,
fontsize=self.fontsize)
else: # pragma no cover
raise ValueError | [
"Common",
"post",
"process",
"for",
"each",
"axes"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L402-L435 | [
"def",
"_post_plot_logic_common",
"(",
"self",
",",
"ax",
",",
"data",
")",
":",
"def",
"get_label",
"(",
"i",
")",
":",
"try",
":",
"return",
"pprint_thing",
"(",
"data",
".",
"index",
"[",
"i",
"]",
")",
"except",
"Exception",
":",
"return",
"''",
"if",
"self",
".",
"orientation",
"==",
"'vertical'",
"or",
"self",
".",
"orientation",
"is",
"None",
":",
"if",
"self",
".",
"_need_to_set_index",
":",
"xticklabels",
"=",
"[",
"get_label",
"(",
"x",
")",
"for",
"x",
"in",
"ax",
".",
"get_xticks",
"(",
")",
"]",
"ax",
".",
"set_xticklabels",
"(",
"xticklabels",
")",
"self",
".",
"_apply_axis_properties",
"(",
"ax",
".",
"xaxis",
",",
"rot",
"=",
"self",
".",
"rot",
",",
"fontsize",
"=",
"self",
".",
"fontsize",
")",
"self",
".",
"_apply_axis_properties",
"(",
"ax",
".",
"yaxis",
",",
"fontsize",
"=",
"self",
".",
"fontsize",
")",
"if",
"hasattr",
"(",
"ax",
",",
"'right_ax'",
")",
":",
"self",
".",
"_apply_axis_properties",
"(",
"ax",
".",
"right_ax",
".",
"yaxis",
",",
"fontsize",
"=",
"self",
".",
"fontsize",
")",
"elif",
"self",
".",
"orientation",
"==",
"'horizontal'",
":",
"if",
"self",
".",
"_need_to_set_index",
":",
"yticklabels",
"=",
"[",
"get_label",
"(",
"y",
")",
"for",
"y",
"in",
"ax",
".",
"get_yticks",
"(",
")",
"]",
"ax",
".",
"set_yticklabels",
"(",
"yticklabels",
")",
"self",
".",
"_apply_axis_properties",
"(",
"ax",
".",
"yaxis",
",",
"rot",
"=",
"self",
".",
"rot",
",",
"fontsize",
"=",
"self",
".",
"fontsize",
")",
"self",
".",
"_apply_axis_properties",
"(",
"ax",
".",
"xaxis",
",",
"fontsize",
"=",
"self",
".",
"fontsize",
")",
"if",
"hasattr",
"(",
"ax",
",",
"'right_ax'",
")",
":",
"self",
".",
"_apply_axis_properties",
"(",
"ax",
".",
"right_ax",
".",
"yaxis",
",",
"fontsize",
"=",
"self",
".",
"fontsize",
")",
"else",
":",
"# pragma no cover",
"raise",
"ValueError"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | MPLPlot._adorn_subplots | Common post process unrelated to data | pandas/plotting/_core.py | def _adorn_subplots(self):
"""Common post process unrelated to data"""
if len(self.axes) > 0:
all_axes = self._get_subplots()
nrows, ncols = self._get_axes_layout()
_handle_shared_axes(axarr=all_axes, nplots=len(all_axes),
naxes=nrows * ncols, nrows=nrows,
ncols=ncols, sharex=self.sharex,
sharey=self.sharey)
for ax in self.axes:
if self.yticks is not None:
ax.set_yticks(self.yticks)
if self.xticks is not None:
ax.set_xticks(self.xticks)
if self.ylim is not None:
ax.set_ylim(self.ylim)
if self.xlim is not None:
ax.set_xlim(self.xlim)
ax.grid(self.grid)
if self.title:
if self.subplots:
if is_list_like(self.title):
if len(self.title) != self.nseries:
msg = ('The length of `title` must equal the number '
'of columns if using `title` of type `list` '
'and `subplots=True`.\n'
'length of title = {}\n'
'number of columns = {}').format(
len(self.title), self.nseries)
raise ValueError(msg)
for (ax, title) in zip(self.axes, self.title):
ax.set_title(title)
else:
self.fig.suptitle(self.title)
else:
if is_list_like(self.title):
msg = ('Using `title` of type `list` is not supported '
'unless `subplots=True` is passed')
raise ValueError(msg)
self.axes[0].set_title(self.title) | def _adorn_subplots(self):
"""Common post process unrelated to data"""
if len(self.axes) > 0:
all_axes = self._get_subplots()
nrows, ncols = self._get_axes_layout()
_handle_shared_axes(axarr=all_axes, nplots=len(all_axes),
naxes=nrows * ncols, nrows=nrows,
ncols=ncols, sharex=self.sharex,
sharey=self.sharey)
for ax in self.axes:
if self.yticks is not None:
ax.set_yticks(self.yticks)
if self.xticks is not None:
ax.set_xticks(self.xticks)
if self.ylim is not None:
ax.set_ylim(self.ylim)
if self.xlim is not None:
ax.set_xlim(self.xlim)
ax.grid(self.grid)
if self.title:
if self.subplots:
if is_list_like(self.title):
if len(self.title) != self.nseries:
msg = ('The length of `title` must equal the number '
'of columns if using `title` of type `list` '
'and `subplots=True`.\n'
'length of title = {}\n'
'number of columns = {}').format(
len(self.title), self.nseries)
raise ValueError(msg)
for (ax, title) in zip(self.axes, self.title):
ax.set_title(title)
else:
self.fig.suptitle(self.title)
else:
if is_list_like(self.title):
msg = ('Using `title` of type `list` is not supported '
'unless `subplots=True` is passed')
raise ValueError(msg)
self.axes[0].set_title(self.title) | [
"Common",
"post",
"process",
"unrelated",
"to",
"data"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L441-L487 | [
"def",
"_adorn_subplots",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"axes",
")",
">",
"0",
":",
"all_axes",
"=",
"self",
".",
"_get_subplots",
"(",
")",
"nrows",
",",
"ncols",
"=",
"self",
".",
"_get_axes_layout",
"(",
")",
"_handle_shared_axes",
"(",
"axarr",
"=",
"all_axes",
",",
"nplots",
"=",
"len",
"(",
"all_axes",
")",
",",
"naxes",
"=",
"nrows",
"*",
"ncols",
",",
"nrows",
"=",
"nrows",
",",
"ncols",
"=",
"ncols",
",",
"sharex",
"=",
"self",
".",
"sharex",
",",
"sharey",
"=",
"self",
".",
"sharey",
")",
"for",
"ax",
"in",
"self",
".",
"axes",
":",
"if",
"self",
".",
"yticks",
"is",
"not",
"None",
":",
"ax",
".",
"set_yticks",
"(",
"self",
".",
"yticks",
")",
"if",
"self",
".",
"xticks",
"is",
"not",
"None",
":",
"ax",
".",
"set_xticks",
"(",
"self",
".",
"xticks",
")",
"if",
"self",
".",
"ylim",
"is",
"not",
"None",
":",
"ax",
".",
"set_ylim",
"(",
"self",
".",
"ylim",
")",
"if",
"self",
".",
"xlim",
"is",
"not",
"None",
":",
"ax",
".",
"set_xlim",
"(",
"self",
".",
"xlim",
")",
"ax",
".",
"grid",
"(",
"self",
".",
"grid",
")",
"if",
"self",
".",
"title",
":",
"if",
"self",
".",
"subplots",
":",
"if",
"is_list_like",
"(",
"self",
".",
"title",
")",
":",
"if",
"len",
"(",
"self",
".",
"title",
")",
"!=",
"self",
".",
"nseries",
":",
"msg",
"=",
"(",
"'The length of `title` must equal the number '",
"'of columns if using `title` of type `list` '",
"'and `subplots=True`.\\n'",
"'length of title = {}\\n'",
"'number of columns = {}'",
")",
".",
"format",
"(",
"len",
"(",
"self",
".",
"title",
")",
",",
"self",
".",
"nseries",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"for",
"(",
"ax",
",",
"title",
")",
"in",
"zip",
"(",
"self",
".",
"axes",
",",
"self",
".",
"title",
")",
":",
"ax",
".",
"set_title",
"(",
"title",
")",
"else",
":",
"self",
".",
"fig",
".",
"suptitle",
"(",
"self",
".",
"title",
")",
"else",
":",
"if",
"is_list_like",
"(",
"self",
".",
"title",
")",
":",
"msg",
"=",
"(",
"'Using `title` of type `list` is not supported '",
"'unless `subplots=True` is passed'",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"self",
".",
"axes",
"[",
"0",
"]",
".",
"set_title",
"(",
"self",
".",
"title",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | MPLPlot._apply_axis_properties | Tick creation within matplotlib is reasonably expensive and is
internally deferred until accessed as Ticks are created/destroyed
multiple times per draw. It's therefore beneficial for us to avoid
accessing unless we will act on the Tick. | pandas/plotting/_core.py | def _apply_axis_properties(self, axis, rot=None, fontsize=None):
""" Tick creation within matplotlib is reasonably expensive and is
internally deferred until accessed as Ticks are created/destroyed
multiple times per draw. It's therefore beneficial for us to avoid
accessing unless we will act on the Tick.
"""
if rot is not None or fontsize is not None:
# rot=0 is a valid setting, hence the explicit None check
labels = axis.get_majorticklabels() + axis.get_minorticklabels()
for label in labels:
if rot is not None:
label.set_rotation(rot)
if fontsize is not None:
label.set_fontsize(fontsize) | def _apply_axis_properties(self, axis, rot=None, fontsize=None):
""" Tick creation within matplotlib is reasonably expensive and is
internally deferred until accessed as Ticks are created/destroyed
multiple times per draw. It's therefore beneficial for us to avoid
accessing unless we will act on the Tick.
"""
if rot is not None or fontsize is not None:
# rot=0 is a valid setting, hence the explicit None check
labels = axis.get_majorticklabels() + axis.get_minorticklabels()
for label in labels:
if rot is not None:
label.set_rotation(rot)
if fontsize is not None:
label.set_fontsize(fontsize) | [
"Tick",
"creation",
"within",
"matplotlib",
"is",
"reasonably",
"expensive",
"and",
"is",
"internally",
"deferred",
"until",
"accessed",
"as",
"Ticks",
"are",
"created",
"/",
"destroyed",
"multiple",
"times",
"per",
"draw",
".",
"It",
"s",
"therefore",
"beneficial",
"for",
"us",
"to",
"avoid",
"accessing",
"unless",
"we",
"will",
"act",
"on",
"the",
"Tick",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L489-L503 | [
"def",
"_apply_axis_properties",
"(",
"self",
",",
"axis",
",",
"rot",
"=",
"None",
",",
"fontsize",
"=",
"None",
")",
":",
"if",
"rot",
"is",
"not",
"None",
"or",
"fontsize",
"is",
"not",
"None",
":",
"# rot=0 is a valid setting, hence the explicit None check",
"labels",
"=",
"axis",
".",
"get_majorticklabels",
"(",
")",
"+",
"axis",
".",
"get_minorticklabels",
"(",
")",
"for",
"label",
"in",
"labels",
":",
"if",
"rot",
"is",
"not",
"None",
":",
"label",
".",
"set_rotation",
"(",
"rot",
")",
"if",
"fontsize",
"is",
"not",
"None",
":",
"label",
".",
"set_fontsize",
"(",
"fontsize",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | MPLPlot._get_ax_layer | get left (primary) or right (secondary) axes | pandas/plotting/_core.py | def _get_ax_layer(cls, ax, primary=True):
"""get left (primary) or right (secondary) axes"""
if primary:
return getattr(ax, 'left_ax', ax)
else:
return getattr(ax, 'right_ax', ax) | def _get_ax_layer(cls, ax, primary=True):
"""get left (primary) or right (secondary) axes"""
if primary:
return getattr(ax, 'left_ax', ax)
else:
return getattr(ax, 'right_ax', ax) | [
"get",
"left",
"(",
"primary",
")",
"or",
"right",
"(",
"secondary",
")",
"axes"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L644-L649 | [
"def",
"_get_ax_layer",
"(",
"cls",
",",
"ax",
",",
"primary",
"=",
"True",
")",
":",
"if",
"primary",
":",
"return",
"getattr",
"(",
"ax",
",",
"'left_ax'",
",",
"ax",
")",
"else",
":",
"return",
"getattr",
"(",
"ax",
",",
"'right_ax'",
",",
"ax",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | MPLPlot._apply_style_colors | Manage style and color based on column number and its label.
Returns tuple of appropriate style and kwds which "color" may be added. | pandas/plotting/_core.py | def _apply_style_colors(self, colors, kwds, col_num, label):
"""
Manage style and color based on column number and its label.
Returns tuple of appropriate style and kwds which "color" may be added.
"""
style = None
if self.style is not None:
if isinstance(self.style, list):
try:
style = self.style[col_num]
except IndexError:
pass
elif isinstance(self.style, dict):
style = self.style.get(label, style)
else:
style = self.style
has_color = 'color' in kwds or self.colormap is not None
nocolor_style = style is None or re.match('[a-z]+', style) is None
if (has_color or self.subplots) and nocolor_style:
kwds['color'] = colors[col_num % len(colors)]
return style, kwds | def _apply_style_colors(self, colors, kwds, col_num, label):
"""
Manage style and color based on column number and its label.
Returns tuple of appropriate style and kwds which "color" may be added.
"""
style = None
if self.style is not None:
if isinstance(self.style, list):
try:
style = self.style[col_num]
except IndexError:
pass
elif isinstance(self.style, dict):
style = self.style.get(label, style)
else:
style = self.style
has_color = 'color' in kwds or self.colormap is not None
nocolor_style = style is None or re.match('[a-z]+', style) is None
if (has_color or self.subplots) and nocolor_style:
kwds['color'] = colors[col_num % len(colors)]
return style, kwds | [
"Manage",
"style",
"and",
"color",
"based",
"on",
"column",
"number",
"and",
"its",
"label",
".",
"Returns",
"tuple",
"of",
"appropriate",
"style",
"and",
"kwds",
"which",
"color",
"may",
"be",
"added",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L672-L693 | [
"def",
"_apply_style_colors",
"(",
"self",
",",
"colors",
",",
"kwds",
",",
"col_num",
",",
"label",
")",
":",
"style",
"=",
"None",
"if",
"self",
".",
"style",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"style",
",",
"list",
")",
":",
"try",
":",
"style",
"=",
"self",
".",
"style",
"[",
"col_num",
"]",
"except",
"IndexError",
":",
"pass",
"elif",
"isinstance",
"(",
"self",
".",
"style",
",",
"dict",
")",
":",
"style",
"=",
"self",
".",
"style",
".",
"get",
"(",
"label",
",",
"style",
")",
"else",
":",
"style",
"=",
"self",
".",
"style",
"has_color",
"=",
"'color'",
"in",
"kwds",
"or",
"self",
".",
"colormap",
"is",
"not",
"None",
"nocolor_style",
"=",
"style",
"is",
"None",
"or",
"re",
".",
"match",
"(",
"'[a-z]+'",
",",
"style",
")",
"is",
"None",
"if",
"(",
"has_color",
"or",
"self",
".",
"subplots",
")",
"and",
"nocolor_style",
":",
"kwds",
"[",
"'color'",
"]",
"=",
"colors",
"[",
"col_num",
"%",
"len",
"(",
"colors",
")",
"]",
"return",
"style",
",",
"kwds"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | MPLPlot._parse_errorbars | Look for error keyword arguments and return the actual errorbar data
or return the error DataFrame/dict
Error bars can be specified in several ways:
Series: the user provides a pandas.Series object of the same
length as the data
ndarray: provides a np.ndarray of the same length as the data
DataFrame/dict: error values are paired with keys matching the
key in the plotted DataFrame
str: the name of the column within the plotted DataFrame | pandas/plotting/_core.py | def _parse_errorbars(self, label, err):
"""
Look for error keyword arguments and return the actual errorbar data
or return the error DataFrame/dict
Error bars can be specified in several ways:
Series: the user provides a pandas.Series object of the same
length as the data
ndarray: provides a np.ndarray of the same length as the data
DataFrame/dict: error values are paired with keys matching the
key in the plotted DataFrame
str: the name of the column within the plotted DataFrame
"""
if err is None:
return None
def match_labels(data, e):
e = e.reindex(data.index)
return e
# key-matched DataFrame
if isinstance(err, ABCDataFrame):
err = match_labels(self.data, err)
# key-matched dict
elif isinstance(err, dict):
pass
# Series of error values
elif isinstance(err, ABCSeries):
# broadcast error series across data
err = match_labels(self.data, err)
err = np.atleast_2d(err)
err = np.tile(err, (self.nseries, 1))
# errors are a column in the dataframe
elif isinstance(err, str):
evalues = self.data[err].values
self.data = self.data[self.data.columns.drop(err)]
err = np.atleast_2d(evalues)
err = np.tile(err, (self.nseries, 1))
elif is_list_like(err):
if is_iterator(err):
err = np.atleast_2d(list(err))
else:
# raw error values
err = np.atleast_2d(err)
err_shape = err.shape
# asymmetrical error bars
if err.ndim == 3:
if (err_shape[0] != self.nseries) or \
(err_shape[1] != 2) or \
(err_shape[2] != len(self.data)):
msg = "Asymmetrical error bars should be provided " + \
"with the shape (%u, 2, %u)" % \
(self.nseries, len(self.data))
raise ValueError(msg)
# broadcast errors to each data series
if len(err) == 1:
err = np.tile(err, (self.nseries, 1))
elif is_number(err):
err = np.tile([err], (self.nseries, len(self.data)))
else:
msg = "No valid {label} detected".format(label=label)
raise ValueError(msg)
return err | def _parse_errorbars(self, label, err):
"""
Look for error keyword arguments and return the actual errorbar data
or return the error DataFrame/dict
Error bars can be specified in several ways:
Series: the user provides a pandas.Series object of the same
length as the data
ndarray: provides a np.ndarray of the same length as the data
DataFrame/dict: error values are paired with keys matching the
key in the plotted DataFrame
str: the name of the column within the plotted DataFrame
"""
if err is None:
return None
def match_labels(data, e):
e = e.reindex(data.index)
return e
# key-matched DataFrame
if isinstance(err, ABCDataFrame):
err = match_labels(self.data, err)
# key-matched dict
elif isinstance(err, dict):
pass
# Series of error values
elif isinstance(err, ABCSeries):
# broadcast error series across data
err = match_labels(self.data, err)
err = np.atleast_2d(err)
err = np.tile(err, (self.nseries, 1))
# errors are a column in the dataframe
elif isinstance(err, str):
evalues = self.data[err].values
self.data = self.data[self.data.columns.drop(err)]
err = np.atleast_2d(evalues)
err = np.tile(err, (self.nseries, 1))
elif is_list_like(err):
if is_iterator(err):
err = np.atleast_2d(list(err))
else:
# raw error values
err = np.atleast_2d(err)
err_shape = err.shape
# asymmetrical error bars
if err.ndim == 3:
if (err_shape[0] != self.nseries) or \
(err_shape[1] != 2) or \
(err_shape[2] != len(self.data)):
msg = "Asymmetrical error bars should be provided " + \
"with the shape (%u, 2, %u)" % \
(self.nseries, len(self.data))
raise ValueError(msg)
# broadcast errors to each data series
if len(err) == 1:
err = np.tile(err, (self.nseries, 1))
elif is_number(err):
err = np.tile([err], (self.nseries, len(self.data)))
else:
msg = "No valid {label} detected".format(label=label)
raise ValueError(msg)
return err | [
"Look",
"for",
"error",
"keyword",
"arguments",
"and",
"return",
"the",
"actual",
"errorbar",
"data",
"or",
"return",
"the",
"error",
"DataFrame",
"/",
"dict"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L703-L776 | [
"def",
"_parse_errorbars",
"(",
"self",
",",
"label",
",",
"err",
")",
":",
"if",
"err",
"is",
"None",
":",
"return",
"None",
"def",
"match_labels",
"(",
"data",
",",
"e",
")",
":",
"e",
"=",
"e",
".",
"reindex",
"(",
"data",
".",
"index",
")",
"return",
"e",
"# key-matched DataFrame",
"if",
"isinstance",
"(",
"err",
",",
"ABCDataFrame",
")",
":",
"err",
"=",
"match_labels",
"(",
"self",
".",
"data",
",",
"err",
")",
"# key-matched dict",
"elif",
"isinstance",
"(",
"err",
",",
"dict",
")",
":",
"pass",
"# Series of error values",
"elif",
"isinstance",
"(",
"err",
",",
"ABCSeries",
")",
":",
"# broadcast error series across data",
"err",
"=",
"match_labels",
"(",
"self",
".",
"data",
",",
"err",
")",
"err",
"=",
"np",
".",
"atleast_2d",
"(",
"err",
")",
"err",
"=",
"np",
".",
"tile",
"(",
"err",
",",
"(",
"self",
".",
"nseries",
",",
"1",
")",
")",
"# errors are a column in the dataframe",
"elif",
"isinstance",
"(",
"err",
",",
"str",
")",
":",
"evalues",
"=",
"self",
".",
"data",
"[",
"err",
"]",
".",
"values",
"self",
".",
"data",
"=",
"self",
".",
"data",
"[",
"self",
".",
"data",
".",
"columns",
".",
"drop",
"(",
"err",
")",
"]",
"err",
"=",
"np",
".",
"atleast_2d",
"(",
"evalues",
")",
"err",
"=",
"np",
".",
"tile",
"(",
"err",
",",
"(",
"self",
".",
"nseries",
",",
"1",
")",
")",
"elif",
"is_list_like",
"(",
"err",
")",
":",
"if",
"is_iterator",
"(",
"err",
")",
":",
"err",
"=",
"np",
".",
"atleast_2d",
"(",
"list",
"(",
"err",
")",
")",
"else",
":",
"# raw error values",
"err",
"=",
"np",
".",
"atleast_2d",
"(",
"err",
")",
"err_shape",
"=",
"err",
".",
"shape",
"# asymmetrical error bars",
"if",
"err",
".",
"ndim",
"==",
"3",
":",
"if",
"(",
"err_shape",
"[",
"0",
"]",
"!=",
"self",
".",
"nseries",
")",
"or",
"(",
"err_shape",
"[",
"1",
"]",
"!=",
"2",
")",
"or",
"(",
"err_shape",
"[",
"2",
"]",
"!=",
"len",
"(",
"self",
".",
"data",
")",
")",
":",
"msg",
"=",
"\"Asymmetrical error bars should be provided \"",
"+",
"\"with the shape (%u, 2, %u)\"",
"%",
"(",
"self",
".",
"nseries",
",",
"len",
"(",
"self",
".",
"data",
")",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"# broadcast errors to each data series",
"if",
"len",
"(",
"err",
")",
"==",
"1",
":",
"err",
"=",
"np",
".",
"tile",
"(",
"err",
",",
"(",
"self",
".",
"nseries",
",",
"1",
")",
")",
"elif",
"is_number",
"(",
"err",
")",
":",
"err",
"=",
"np",
".",
"tile",
"(",
"[",
"err",
"]",
",",
"(",
"self",
".",
"nseries",
",",
"len",
"(",
"self",
".",
"data",
")",
")",
")",
"else",
":",
"msg",
"=",
"\"No valid {label} detected\"",
".",
"format",
"(",
"label",
"=",
"label",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"err"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | HistPlot._make_plot_keywords | merge BoxPlot/KdePlot properties to passed kwds | pandas/plotting/_core.py | def _make_plot_keywords(self, kwds, y):
"""merge BoxPlot/KdePlot properties to passed kwds"""
# y is required for KdePlot
kwds['bottom'] = self.bottom
kwds['bins'] = self.bins
return kwds | def _make_plot_keywords(self, kwds, y):
"""merge BoxPlot/KdePlot properties to passed kwds"""
# y is required for KdePlot
kwds['bottom'] = self.bottom
kwds['bins'] = self.bins
return kwds | [
"merge",
"BoxPlot",
"/",
"KdePlot",
"properties",
"to",
"passed",
"kwds"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L1395-L1400 | [
"def",
"_make_plot_keywords",
"(",
"self",
",",
"kwds",
",",
"y",
")",
":",
"# y is required for KdePlot",
"kwds",
"[",
"'bottom'",
"]",
"=",
"self",
".",
"bottom",
"kwds",
"[",
"'bins'",
"]",
"=",
"self",
".",
"bins",
"return",
"kwds"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | FramePlotMethods.line | Plot DataFrame columns as lines.
This function is useful to plot lines using DataFrame's values
as coordinates.
Parameters
----------
x : int or str, optional
Columns to use for the horizontal axis.
Either the location or the label of the columns to be used.
By default, it will use the DataFrame indices.
y : int, str, or list of them, optional
The values to be plotted.
Either the location or the label of the columns to be used.
By default, it will use the remaining DataFrame numeric columns.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or :class:`numpy.ndarray`
Return an ndarray when ``subplots=True``.
See Also
--------
matplotlib.pyplot.plot : Plot y versus x as lines and/or markers.
Examples
--------
.. plot::
:context: close-figs
The following example shows the populations for some animals
over the years.
>>> df = pd.DataFrame({
... 'pig': [20, 18, 489, 675, 1776],
... 'horse': [4, 25, 281, 600, 1900]
... }, index=[1990, 1997, 2003, 2009, 2014])
>>> lines = df.plot.line()
.. plot::
:context: close-figs
An example with subplots, so an array of axes is returned.
>>> axes = df.plot.line(subplots=True)
>>> type(axes)
<class 'numpy.ndarray'>
.. plot::
:context: close-figs
The following example shows the relationship between both
populations.
>>> lines = df.plot.line(x='pig', y='horse') | pandas/plotting/_core.py | def line(self, x=None, y=None, **kwds):
"""
Plot DataFrame columns as lines.
This function is useful to plot lines using DataFrame's values
as coordinates.
Parameters
----------
x : int or str, optional
Columns to use for the horizontal axis.
Either the location or the label of the columns to be used.
By default, it will use the DataFrame indices.
y : int, str, or list of them, optional
The values to be plotted.
Either the location or the label of the columns to be used.
By default, it will use the remaining DataFrame numeric columns.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or :class:`numpy.ndarray`
Return an ndarray when ``subplots=True``.
See Also
--------
matplotlib.pyplot.plot : Plot y versus x as lines and/or markers.
Examples
--------
.. plot::
:context: close-figs
The following example shows the populations for some animals
over the years.
>>> df = pd.DataFrame({
... 'pig': [20, 18, 489, 675, 1776],
... 'horse': [4, 25, 281, 600, 1900]
... }, index=[1990, 1997, 2003, 2009, 2014])
>>> lines = df.plot.line()
.. plot::
:context: close-figs
An example with subplots, so an array of axes is returned.
>>> axes = df.plot.line(subplots=True)
>>> type(axes)
<class 'numpy.ndarray'>
.. plot::
:context: close-figs
The following example shows the relationship between both
populations.
>>> lines = df.plot.line(x='pig', y='horse')
"""
return self(kind='line', x=x, y=y, **kwds) | def line(self, x=None, y=None, **kwds):
"""
Plot DataFrame columns as lines.
This function is useful to plot lines using DataFrame's values
as coordinates.
Parameters
----------
x : int or str, optional
Columns to use for the horizontal axis.
Either the location or the label of the columns to be used.
By default, it will use the DataFrame indices.
y : int, str, or list of them, optional
The values to be plotted.
Either the location or the label of the columns to be used.
By default, it will use the remaining DataFrame numeric columns.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or :class:`numpy.ndarray`
Return an ndarray when ``subplots=True``.
See Also
--------
matplotlib.pyplot.plot : Plot y versus x as lines and/or markers.
Examples
--------
.. plot::
:context: close-figs
The following example shows the populations for some animals
over the years.
>>> df = pd.DataFrame({
... 'pig': [20, 18, 489, 675, 1776],
... 'horse': [4, 25, 281, 600, 1900]
... }, index=[1990, 1997, 2003, 2009, 2014])
>>> lines = df.plot.line()
.. plot::
:context: close-figs
An example with subplots, so an array of axes is returned.
>>> axes = df.plot.line(subplots=True)
>>> type(axes)
<class 'numpy.ndarray'>
.. plot::
:context: close-figs
The following example shows the relationship between both
populations.
>>> lines = df.plot.line(x='pig', y='horse')
"""
return self(kind='line', x=x, y=y, **kwds) | [
"Plot",
"DataFrame",
"columns",
"as",
"lines",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L2970-L3031 | [
"def",
"line",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'line'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"*",
"*",
"kwds",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | FramePlotMethods.bar | Vertical bar plot.
A bar plot is a plot that presents categorical data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the plot shows the specific categories being compared, and the
other axis represents a measured value.
Parameters
----------
x : label or position, optional
Allows plotting of one column versus another. If not specified,
the index of the DataFrame is used.
y : label or position, optional
Allows plotting of one column versus another. If not specified,
all numerical columns are used.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.axes.Axes or np.ndarray of them
An ndarray is returned with one :class:`matplotlib.axes.Axes`
per column when ``subplots=True``.
See Also
--------
DataFrame.plot.barh : Horizontal bar plot.
DataFrame.plot : Make plots of a DataFrame.
matplotlib.pyplot.bar : Make a bar plot with matplotlib.
Examples
--------
Basic plot.
.. plot::
:context: close-figs
>>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
>>> ax = df.plot.bar(x='lab', y='val', rot=0)
Plot a whole dataframe to a bar plot. Each column is assigned a
distinct color, and each row is nested in a group along the
horizontal axis.
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.bar(rot=0)
Instead of nesting, the figure can be split by column with
``subplots=True``. In this case, a :class:`numpy.ndarray` of
:class:`matplotlib.axes.Axes` are returned.
.. plot::
:context: close-figs
>>> axes = df.plot.bar(rot=0, subplots=True)
>>> axes[1].legend(loc=2) # doctest: +SKIP
Plot a single column.
.. plot::
:context: close-figs
>>> ax = df.plot.bar(y='speed', rot=0)
Plot only selected categories for the DataFrame.
.. plot::
:context: close-figs
>>> ax = df.plot.bar(x='lifespan', rot=0) | pandas/plotting/_core.py | def bar(self, x=None, y=None, **kwds):
"""
Vertical bar plot.
A bar plot is a plot that presents categorical data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the plot shows the specific categories being compared, and the
other axis represents a measured value.
Parameters
----------
x : label or position, optional
Allows plotting of one column versus another. If not specified,
the index of the DataFrame is used.
y : label or position, optional
Allows plotting of one column versus another. If not specified,
all numerical columns are used.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.axes.Axes or np.ndarray of them
An ndarray is returned with one :class:`matplotlib.axes.Axes`
per column when ``subplots=True``.
See Also
--------
DataFrame.plot.barh : Horizontal bar plot.
DataFrame.plot : Make plots of a DataFrame.
matplotlib.pyplot.bar : Make a bar plot with matplotlib.
Examples
--------
Basic plot.
.. plot::
:context: close-figs
>>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
>>> ax = df.plot.bar(x='lab', y='val', rot=0)
Plot a whole dataframe to a bar plot. Each column is assigned a
distinct color, and each row is nested in a group along the
horizontal axis.
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.bar(rot=0)
Instead of nesting, the figure can be split by column with
``subplots=True``. In this case, a :class:`numpy.ndarray` of
:class:`matplotlib.axes.Axes` are returned.
.. plot::
:context: close-figs
>>> axes = df.plot.bar(rot=0, subplots=True)
>>> axes[1].legend(loc=2) # doctest: +SKIP
Plot a single column.
.. plot::
:context: close-figs
>>> ax = df.plot.bar(y='speed', rot=0)
Plot only selected categories for the DataFrame.
.. plot::
:context: close-figs
>>> ax = df.plot.bar(x='lifespan', rot=0)
"""
return self(kind='bar', x=x, y=y, **kwds) | def bar(self, x=None, y=None, **kwds):
"""
Vertical bar plot.
A bar plot is a plot that presents categorical data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the plot shows the specific categories being compared, and the
other axis represents a measured value.
Parameters
----------
x : label or position, optional
Allows plotting of one column versus another. If not specified,
the index of the DataFrame is used.
y : label or position, optional
Allows plotting of one column versus another. If not specified,
all numerical columns are used.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.axes.Axes or np.ndarray of them
An ndarray is returned with one :class:`matplotlib.axes.Axes`
per column when ``subplots=True``.
See Also
--------
DataFrame.plot.barh : Horizontal bar plot.
DataFrame.plot : Make plots of a DataFrame.
matplotlib.pyplot.bar : Make a bar plot with matplotlib.
Examples
--------
Basic plot.
.. plot::
:context: close-figs
>>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
>>> ax = df.plot.bar(x='lab', y='val', rot=0)
Plot a whole dataframe to a bar plot. Each column is assigned a
distinct color, and each row is nested in a group along the
horizontal axis.
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.bar(rot=0)
Instead of nesting, the figure can be split by column with
``subplots=True``. In this case, a :class:`numpy.ndarray` of
:class:`matplotlib.axes.Axes` are returned.
.. plot::
:context: close-figs
>>> axes = df.plot.bar(rot=0, subplots=True)
>>> axes[1].legend(loc=2) # doctest: +SKIP
Plot a single column.
.. plot::
:context: close-figs
>>> ax = df.plot.bar(y='speed', rot=0)
Plot only selected categories for the DataFrame.
.. plot::
:context: close-figs
>>> ax = df.plot.bar(x='lifespan', rot=0)
"""
return self(kind='bar', x=x, y=y, **kwds) | [
"Vertical",
"bar",
"plot",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L3033-L3116 | [
"def",
"bar",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'bar'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"*",
"*",
"kwds",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | FramePlotMethods.barh | Make a horizontal bar plot.
A horizontal bar plot is a plot that presents quantitative data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the plot shows the specific categories being compared, and the
other axis represents a measured value.
Parameters
----------
x : label or position, default DataFrame.index
Column to be used for categories.
y : label or position, default All numeric columns in dataframe
Columns to be plotted from the DataFrame.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or numpy.ndarray of them
See Also
--------
DataFrame.plot.bar: Vertical bar plot.
DataFrame.plot : Make plots of DataFrame using matplotlib.
matplotlib.axes.Axes.bar : Plot a vertical bar plot using matplotlib.
Examples
--------
Basic example
.. plot::
:context: close-figs
>>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
>>> ax = df.plot.barh(x='lab', y='val')
Plot a whole DataFrame to a horizontal bar plot
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh()
Plot a column of the DataFrame to a horizontal bar plot
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh(y='speed')
Plot DataFrame versus the desired column
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh(x='lifespan') | pandas/plotting/_core.py | def barh(self, x=None, y=None, **kwds):
"""
Make a horizontal bar plot.
A horizontal bar plot is a plot that presents quantitative data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the plot shows the specific categories being compared, and the
other axis represents a measured value.
Parameters
----------
x : label or position, default DataFrame.index
Column to be used for categories.
y : label or position, default All numeric columns in dataframe
Columns to be plotted from the DataFrame.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or numpy.ndarray of them
See Also
--------
DataFrame.plot.bar: Vertical bar plot.
DataFrame.plot : Make plots of DataFrame using matplotlib.
matplotlib.axes.Axes.bar : Plot a vertical bar plot using matplotlib.
Examples
--------
Basic example
.. plot::
:context: close-figs
>>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
>>> ax = df.plot.barh(x='lab', y='val')
Plot a whole DataFrame to a horizontal bar plot
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh()
Plot a column of the DataFrame to a horizontal bar plot
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh(y='speed')
Plot DataFrame versus the desired column
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh(x='lifespan')
"""
return self(kind='barh', x=x, y=y, **kwds) | def barh(self, x=None, y=None, **kwds):
"""
Make a horizontal bar plot.
A horizontal bar plot is a plot that presents quantitative data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the plot shows the specific categories being compared, and the
other axis represents a measured value.
Parameters
----------
x : label or position, default DataFrame.index
Column to be used for categories.
y : label or position, default All numeric columns in dataframe
Columns to be plotted from the DataFrame.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or numpy.ndarray of them
See Also
--------
DataFrame.plot.bar: Vertical bar plot.
DataFrame.plot : Make plots of DataFrame using matplotlib.
matplotlib.axes.Axes.bar : Plot a vertical bar plot using matplotlib.
Examples
--------
Basic example
.. plot::
:context: close-figs
>>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
>>> ax = df.plot.barh(x='lab', y='val')
Plot a whole DataFrame to a horizontal bar plot
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh()
Plot a column of the DataFrame to a horizontal bar plot
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh(y='speed')
Plot DataFrame versus the desired column
.. plot::
:context: close-figs
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh(x='lifespan')
"""
return self(kind='barh', x=x, y=y, **kwds) | [
"Make",
"a",
"horizontal",
"bar",
"plot",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L3118-L3196 | [
"def",
"barh",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'barh'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"*",
"*",
"kwds",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | FramePlotMethods.hist | Draw one histogram of the DataFrame's columns.
A histogram is a representation of the distribution of data.
This function groups the values of all given Series in the DataFrame
into bins and draws all bins in one :class:`matplotlib.axes.Axes`.
This is useful when the DataFrame's Series are in a similar scale.
Parameters
----------
by : str or sequence, optional
Column in the DataFrame to group by.
bins : int, default 10
Number of histogram bins to be used.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
class:`matplotlib.AxesSubplot`
Return a histogram plot.
See Also
--------
DataFrame.hist : Draw histograms per DataFrame's Series.
Series.hist : Draw a histogram with Series' data.
Examples
--------
When we draw a dice 6000 times, we expect to get each value around 1000
times. But when we draw two dices and sum the result, the distribution
is going to be quite different. A histogram illustrates those
distributions.
.. plot::
:context: close-figs
>>> df = pd.DataFrame(
... np.random.randint(1, 7, 6000),
... columns = ['one'])
>>> df['two'] = df['one'] + np.random.randint(1, 7, 6000)
>>> ax = df.plot.hist(bins=12, alpha=0.5) | pandas/plotting/_core.py | def hist(self, by=None, bins=10, **kwds):
"""
Draw one histogram of the DataFrame's columns.
A histogram is a representation of the distribution of data.
This function groups the values of all given Series in the DataFrame
into bins and draws all bins in one :class:`matplotlib.axes.Axes`.
This is useful when the DataFrame's Series are in a similar scale.
Parameters
----------
by : str or sequence, optional
Column in the DataFrame to group by.
bins : int, default 10
Number of histogram bins to be used.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
class:`matplotlib.AxesSubplot`
Return a histogram plot.
See Also
--------
DataFrame.hist : Draw histograms per DataFrame's Series.
Series.hist : Draw a histogram with Series' data.
Examples
--------
When we draw a dice 6000 times, we expect to get each value around 1000
times. But when we draw two dices and sum the result, the distribution
is going to be quite different. A histogram illustrates those
distributions.
.. plot::
:context: close-figs
>>> df = pd.DataFrame(
... np.random.randint(1, 7, 6000),
... columns = ['one'])
>>> df['two'] = df['one'] + np.random.randint(1, 7, 6000)
>>> ax = df.plot.hist(bins=12, alpha=0.5)
"""
return self(kind='hist', by=by, bins=bins, **kwds) | def hist(self, by=None, bins=10, **kwds):
"""
Draw one histogram of the DataFrame's columns.
A histogram is a representation of the distribution of data.
This function groups the values of all given Series in the DataFrame
into bins and draws all bins in one :class:`matplotlib.axes.Axes`.
This is useful when the DataFrame's Series are in a similar scale.
Parameters
----------
by : str or sequence, optional
Column in the DataFrame to group by.
bins : int, default 10
Number of histogram bins to be used.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
class:`matplotlib.AxesSubplot`
Return a histogram plot.
See Also
--------
DataFrame.hist : Draw histograms per DataFrame's Series.
Series.hist : Draw a histogram with Series' data.
Examples
--------
When we draw a dice 6000 times, we expect to get each value around 1000
times. But when we draw two dices and sum the result, the distribution
is going to be quite different. A histogram illustrates those
distributions.
.. plot::
:context: close-figs
>>> df = pd.DataFrame(
... np.random.randint(1, 7, 6000),
... columns = ['one'])
>>> df['two'] = df['one'] + np.random.randint(1, 7, 6000)
>>> ax = df.plot.hist(bins=12, alpha=0.5)
"""
return self(kind='hist', by=by, bins=bins, **kwds) | [
"Draw",
"one",
"histogram",
"of",
"the",
"DataFrame",
"s",
"columns",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L3248-L3293 | [
"def",
"hist",
"(",
"self",
",",
"by",
"=",
"None",
",",
"bins",
"=",
"10",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'hist'",
",",
"by",
"=",
"by",
",",
"bins",
"=",
"bins",
",",
"*",
"*",
"kwds",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | FramePlotMethods.area | Draw a stacked area plot.
An area plot displays quantitative data visually.
This function wraps the matplotlib area function.
Parameters
----------
x : label or position, optional
Coordinates for the X axis. By default uses the index.
y : label or position, optional
Column to plot. By default uses all columns.
stacked : bool, default True
Area plots are stacked by default. Set to False to create a
unstacked plot.
**kwds : optional
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.axes.Axes or numpy.ndarray
Area plot, or array of area plots if subplots is True.
See Also
--------
DataFrame.plot : Make plots of DataFrame using matplotlib / pylab.
Examples
--------
Draw an area plot based on basic business metrics:
.. plot::
:context: close-figs
>>> df = pd.DataFrame({
... 'sales': [3, 2, 3, 9, 10, 6],
... 'signups': [5, 5, 6, 12, 14, 13],
... 'visits': [20, 42, 28, 62, 81, 50],
... }, index=pd.date_range(start='2018/01/01', end='2018/07/01',
... freq='M'))
>>> ax = df.plot.area()
Area plots are stacked by default. To produce an unstacked plot,
pass ``stacked=False``:
.. plot::
:context: close-figs
>>> ax = df.plot.area(stacked=False)
Draw an area plot for a single column:
.. plot::
:context: close-figs
>>> ax = df.plot.area(y='sales')
Draw with a different `x`:
.. plot::
:context: close-figs
>>> df = pd.DataFrame({
... 'sales': [3, 2, 3],
... 'visits': [20, 42, 28],
... 'day': [1, 2, 3],
... })
>>> ax = df.plot.area(x='day') | pandas/plotting/_core.py | def area(self, x=None, y=None, **kwds):
"""
Draw a stacked area plot.
An area plot displays quantitative data visually.
This function wraps the matplotlib area function.
Parameters
----------
x : label or position, optional
Coordinates for the X axis. By default uses the index.
y : label or position, optional
Column to plot. By default uses all columns.
stacked : bool, default True
Area plots are stacked by default. Set to False to create a
unstacked plot.
**kwds : optional
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.axes.Axes or numpy.ndarray
Area plot, or array of area plots if subplots is True.
See Also
--------
DataFrame.plot : Make plots of DataFrame using matplotlib / pylab.
Examples
--------
Draw an area plot based on basic business metrics:
.. plot::
:context: close-figs
>>> df = pd.DataFrame({
... 'sales': [3, 2, 3, 9, 10, 6],
... 'signups': [5, 5, 6, 12, 14, 13],
... 'visits': [20, 42, 28, 62, 81, 50],
... }, index=pd.date_range(start='2018/01/01', end='2018/07/01',
... freq='M'))
>>> ax = df.plot.area()
Area plots are stacked by default. To produce an unstacked plot,
pass ``stacked=False``:
.. plot::
:context: close-figs
>>> ax = df.plot.area(stacked=False)
Draw an area plot for a single column:
.. plot::
:context: close-figs
>>> ax = df.plot.area(y='sales')
Draw with a different `x`:
.. plot::
:context: close-figs
>>> df = pd.DataFrame({
... 'sales': [3, 2, 3],
... 'visits': [20, 42, 28],
... 'day': [1, 2, 3],
... })
>>> ax = df.plot.area(x='day')
"""
return self(kind='area', x=x, y=y, **kwds) | def area(self, x=None, y=None, **kwds):
"""
Draw a stacked area plot.
An area plot displays quantitative data visually.
This function wraps the matplotlib area function.
Parameters
----------
x : label or position, optional
Coordinates for the X axis. By default uses the index.
y : label or position, optional
Column to plot. By default uses all columns.
stacked : bool, default True
Area plots are stacked by default. Set to False to create a
unstacked plot.
**kwds : optional
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.axes.Axes or numpy.ndarray
Area plot, or array of area plots if subplots is True.
See Also
--------
DataFrame.plot : Make plots of DataFrame using matplotlib / pylab.
Examples
--------
Draw an area plot based on basic business metrics:
.. plot::
:context: close-figs
>>> df = pd.DataFrame({
... 'sales': [3, 2, 3, 9, 10, 6],
... 'signups': [5, 5, 6, 12, 14, 13],
... 'visits': [20, 42, 28, 62, 81, 50],
... }, index=pd.date_range(start='2018/01/01', end='2018/07/01',
... freq='M'))
>>> ax = df.plot.area()
Area plots are stacked by default. To produce an unstacked plot,
pass ``stacked=False``:
.. plot::
:context: close-figs
>>> ax = df.plot.area(stacked=False)
Draw an area plot for a single column:
.. plot::
:context: close-figs
>>> ax = df.plot.area(y='sales')
Draw with a different `x`:
.. plot::
:context: close-figs
>>> df = pd.DataFrame({
... 'sales': [3, 2, 3],
... 'visits': [20, 42, 28],
... 'day': [1, 2, 3],
... })
>>> ax = df.plot.area(x='day')
"""
return self(kind='area', x=x, y=y, **kwds) | [
"Draw",
"a",
"stacked",
"area",
"plot",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L3341-L3412 | [
"def",
"area",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'area'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"*",
"*",
"kwds",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | FramePlotMethods.scatter | Create a scatter plot with varying marker point size and color.
The coordinates of each point are defined by two dataframe columns and
filled circles are used to represent each point. This kind of plot is
useful to see complex correlations between two variables. Points could
be for instance natural 2D coordinates like longitude and latitude in
a map or, in general, any pair of metrics that can be plotted against
each other.
Parameters
----------
x : int or str
The column name or column position to be used as horizontal
coordinates for each point.
y : int or str
The column name or column position to be used as vertical
coordinates for each point.
s : scalar or array_like, optional
The size of each point. Possible values are:
- A single scalar so all points have the same size.
- A sequence of scalars, which will be used for each point's size
recursively. For instance, when passing [2,14] all points size
will be either 2 or 14, alternatively.
c : str, int or array_like, optional
The color of each point. Possible values are:
- A single color string referred to by name, RGB or RGBA code,
for instance 'red' or '#a98d19'.
- A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each point's color recursively. For
instance ['green','yellow'] all points will be filled in green or
yellow, alternatively.
- A column name or position whose values will be used to color the
marker points according to a colormap.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or numpy.ndarray of them
See Also
--------
matplotlib.pyplot.scatter : Scatter plot using multiple input data
formats.
Examples
--------
Let's see how to draw a scatter plot using coordinates from the values
in a DataFrame's columns.
.. plot::
:context: close-figs
>>> df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
... [6.4, 3.2, 1], [5.9, 3.0, 2]],
... columns=['length', 'width', 'species'])
>>> ax1 = df.plot.scatter(x='length',
... y='width',
... c='DarkBlue')
And now with the color determined by a column as well.
.. plot::
:context: close-figs
>>> ax2 = df.plot.scatter(x='length',
... y='width',
... c='species',
... colormap='viridis') | pandas/plotting/_core.py | def scatter(self, x, y, s=None, c=None, **kwds):
"""
Create a scatter plot with varying marker point size and color.
The coordinates of each point are defined by two dataframe columns and
filled circles are used to represent each point. This kind of plot is
useful to see complex correlations between two variables. Points could
be for instance natural 2D coordinates like longitude and latitude in
a map or, in general, any pair of metrics that can be plotted against
each other.
Parameters
----------
x : int or str
The column name or column position to be used as horizontal
coordinates for each point.
y : int or str
The column name or column position to be used as vertical
coordinates for each point.
s : scalar or array_like, optional
The size of each point. Possible values are:
- A single scalar so all points have the same size.
- A sequence of scalars, which will be used for each point's size
recursively. For instance, when passing [2,14] all points size
will be either 2 or 14, alternatively.
c : str, int or array_like, optional
The color of each point. Possible values are:
- A single color string referred to by name, RGB or RGBA code,
for instance 'red' or '#a98d19'.
- A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each point's color recursively. For
instance ['green','yellow'] all points will be filled in green or
yellow, alternatively.
- A column name or position whose values will be used to color the
marker points according to a colormap.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or numpy.ndarray of them
See Also
--------
matplotlib.pyplot.scatter : Scatter plot using multiple input data
formats.
Examples
--------
Let's see how to draw a scatter plot using coordinates from the values
in a DataFrame's columns.
.. plot::
:context: close-figs
>>> df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
... [6.4, 3.2, 1], [5.9, 3.0, 2]],
... columns=['length', 'width', 'species'])
>>> ax1 = df.plot.scatter(x='length',
... y='width',
... c='DarkBlue')
And now with the color determined by a column as well.
.. plot::
:context: close-figs
>>> ax2 = df.plot.scatter(x='length',
... y='width',
... c='species',
... colormap='viridis')
"""
return self(kind='scatter', x=x, y=y, c=c, s=s, **kwds) | def scatter(self, x, y, s=None, c=None, **kwds):
"""
Create a scatter plot with varying marker point size and color.
The coordinates of each point are defined by two dataframe columns and
filled circles are used to represent each point. This kind of plot is
useful to see complex correlations between two variables. Points could
be for instance natural 2D coordinates like longitude and latitude in
a map or, in general, any pair of metrics that can be plotted against
each other.
Parameters
----------
x : int or str
The column name or column position to be used as horizontal
coordinates for each point.
y : int or str
The column name or column position to be used as vertical
coordinates for each point.
s : scalar or array_like, optional
The size of each point. Possible values are:
- A single scalar so all points have the same size.
- A sequence of scalars, which will be used for each point's size
recursively. For instance, when passing [2,14] all points size
will be either 2 or 14, alternatively.
c : str, int or array_like, optional
The color of each point. Possible values are:
- A single color string referred to by name, RGB or RGBA code,
for instance 'red' or '#a98d19'.
- A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each point's color recursively. For
instance ['green','yellow'] all points will be filled in green or
yellow, alternatively.
- A column name or position whose values will be used to color the
marker points according to a colormap.
**kwds
Keyword arguments to pass on to :meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or numpy.ndarray of them
See Also
--------
matplotlib.pyplot.scatter : Scatter plot using multiple input data
formats.
Examples
--------
Let's see how to draw a scatter plot using coordinates from the values
in a DataFrame's columns.
.. plot::
:context: close-figs
>>> df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
... [6.4, 3.2, 1], [5.9, 3.0, 2]],
... columns=['length', 'width', 'species'])
>>> ax1 = df.plot.scatter(x='length',
... y='width',
... c='DarkBlue')
And now with the color determined by a column as well.
.. plot::
:context: close-figs
>>> ax2 = df.plot.scatter(x='length',
... y='width',
... c='species',
... colormap='viridis')
"""
return self(kind='scatter', x=x, y=y, c=c, s=s, **kwds) | [
"Create",
"a",
"scatter",
"plot",
"with",
"varying",
"marker",
"point",
"size",
"and",
"color",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L3463-L3542 | [
"def",
"scatter",
"(",
"self",
",",
"x",
",",
"y",
",",
"s",
"=",
"None",
",",
"c",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'scatter'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"c",
"=",
"c",
",",
"s",
"=",
"s",
",",
"*",
"*",
"kwds",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | FramePlotMethods.hexbin | Generate a hexagonal binning plot.
Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None`
(the default), this is a histogram of the number of occurrences
of the observations at ``(x[i], y[i])``.
If `C` is specified, specifies values at given coordinates
``(x[i], y[i])``. These values are accumulated for each hexagonal
bin and then reduced according to `reduce_C_function`,
having as default the NumPy's mean function (:meth:`numpy.mean`).
(If `C` is specified, it must also be a 1-D sequence
of the same length as `x` and `y`, or a column label.)
Parameters
----------
x : int or str
The column label or position for x points.
y : int or str
The column label or position for y points.
C : int or str, optional
The column label or position for the value of `(x, y)` point.
reduce_C_function : callable, default `np.mean`
Function of one argument that reduces all the values in a bin to
a single number (e.g. `np.mean`, `np.max`, `np.sum`, `np.std`).
gridsize : int or tuple of (int, int), default 100
The number of hexagons in the x-direction.
The corresponding number of hexagons in the y-direction is
chosen in a way that the hexagons are approximately regular.
Alternatively, gridsize can be a tuple with two elements
specifying the number of hexagons in the x-direction and the
y-direction.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.AxesSubplot
The matplotlib ``Axes`` on which the hexbin is plotted.
See Also
--------
DataFrame.plot : Make plots of a DataFrame.
matplotlib.pyplot.hexbin : Hexagonal binning plot using matplotlib,
the matplotlib function that is used under the hood.
Examples
--------
The following examples are generated with random data from
a normal distribution.
.. plot::
:context: close-figs
>>> n = 10000
>>> df = pd.DataFrame({'x': np.random.randn(n),
... 'y': np.random.randn(n)})
>>> ax = df.plot.hexbin(x='x', y='y', gridsize=20)
The next example uses `C` and `np.sum` as `reduce_C_function`.
Note that `'observations'` values ranges from 1 to 5 but the result
plot shows values up to more than 25. This is because of the
`reduce_C_function`.
.. plot::
:context: close-figs
>>> n = 500
>>> df = pd.DataFrame({
... 'coord_x': np.random.uniform(-3, 3, size=n),
... 'coord_y': np.random.uniform(30, 50, size=n),
... 'observations': np.random.randint(1,5, size=n)
... })
>>> ax = df.plot.hexbin(x='coord_x',
... y='coord_y',
... C='observations',
... reduce_C_function=np.sum,
... gridsize=10,
... cmap="viridis") | pandas/plotting/_core.py | def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None,
**kwds):
"""
Generate a hexagonal binning plot.
Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None`
(the default), this is a histogram of the number of occurrences
of the observations at ``(x[i], y[i])``.
If `C` is specified, specifies values at given coordinates
``(x[i], y[i])``. These values are accumulated for each hexagonal
bin and then reduced according to `reduce_C_function`,
having as default the NumPy's mean function (:meth:`numpy.mean`).
(If `C` is specified, it must also be a 1-D sequence
of the same length as `x` and `y`, or a column label.)
Parameters
----------
x : int or str
The column label or position for x points.
y : int or str
The column label or position for y points.
C : int or str, optional
The column label or position for the value of `(x, y)` point.
reduce_C_function : callable, default `np.mean`
Function of one argument that reduces all the values in a bin to
a single number (e.g. `np.mean`, `np.max`, `np.sum`, `np.std`).
gridsize : int or tuple of (int, int), default 100
The number of hexagons in the x-direction.
The corresponding number of hexagons in the y-direction is
chosen in a way that the hexagons are approximately regular.
Alternatively, gridsize can be a tuple with two elements
specifying the number of hexagons in the x-direction and the
y-direction.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.AxesSubplot
The matplotlib ``Axes`` on which the hexbin is plotted.
See Also
--------
DataFrame.plot : Make plots of a DataFrame.
matplotlib.pyplot.hexbin : Hexagonal binning plot using matplotlib,
the matplotlib function that is used under the hood.
Examples
--------
The following examples are generated with random data from
a normal distribution.
.. plot::
:context: close-figs
>>> n = 10000
>>> df = pd.DataFrame({'x': np.random.randn(n),
... 'y': np.random.randn(n)})
>>> ax = df.plot.hexbin(x='x', y='y', gridsize=20)
The next example uses `C` and `np.sum` as `reduce_C_function`.
Note that `'observations'` values ranges from 1 to 5 but the result
plot shows values up to more than 25. This is because of the
`reduce_C_function`.
.. plot::
:context: close-figs
>>> n = 500
>>> df = pd.DataFrame({
... 'coord_x': np.random.uniform(-3, 3, size=n),
... 'coord_y': np.random.uniform(30, 50, size=n),
... 'observations': np.random.randint(1,5, size=n)
... })
>>> ax = df.plot.hexbin(x='coord_x',
... y='coord_y',
... C='observations',
... reduce_C_function=np.sum,
... gridsize=10,
... cmap="viridis")
"""
if reduce_C_function is not None:
kwds['reduce_C_function'] = reduce_C_function
if gridsize is not None:
kwds['gridsize'] = gridsize
return self(kind='hexbin', x=x, y=y, C=C, **kwds) | def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None,
**kwds):
"""
Generate a hexagonal binning plot.
Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None`
(the default), this is a histogram of the number of occurrences
of the observations at ``(x[i], y[i])``.
If `C` is specified, specifies values at given coordinates
``(x[i], y[i])``. These values are accumulated for each hexagonal
bin and then reduced according to `reduce_C_function`,
having as default the NumPy's mean function (:meth:`numpy.mean`).
(If `C` is specified, it must also be a 1-D sequence
of the same length as `x` and `y`, or a column label.)
Parameters
----------
x : int or str
The column label or position for x points.
y : int or str
The column label or position for y points.
C : int or str, optional
The column label or position for the value of `(x, y)` point.
reduce_C_function : callable, default `np.mean`
Function of one argument that reduces all the values in a bin to
a single number (e.g. `np.mean`, `np.max`, `np.sum`, `np.std`).
gridsize : int or tuple of (int, int), default 100
The number of hexagons in the x-direction.
The corresponding number of hexagons in the y-direction is
chosen in a way that the hexagons are approximately regular.
Alternatively, gridsize can be a tuple with two elements
specifying the number of hexagons in the x-direction and the
y-direction.
**kwds
Additional keyword arguments are documented in
:meth:`DataFrame.plot`.
Returns
-------
matplotlib.AxesSubplot
The matplotlib ``Axes`` on which the hexbin is plotted.
See Also
--------
DataFrame.plot : Make plots of a DataFrame.
matplotlib.pyplot.hexbin : Hexagonal binning plot using matplotlib,
the matplotlib function that is used under the hood.
Examples
--------
The following examples are generated with random data from
a normal distribution.
.. plot::
:context: close-figs
>>> n = 10000
>>> df = pd.DataFrame({'x': np.random.randn(n),
... 'y': np.random.randn(n)})
>>> ax = df.plot.hexbin(x='x', y='y', gridsize=20)
The next example uses `C` and `np.sum` as `reduce_C_function`.
Note that `'observations'` values ranges from 1 to 5 but the result
plot shows values up to more than 25. This is because of the
`reduce_C_function`.
.. plot::
:context: close-figs
>>> n = 500
>>> df = pd.DataFrame({
... 'coord_x': np.random.uniform(-3, 3, size=n),
... 'coord_y': np.random.uniform(30, 50, size=n),
... 'observations': np.random.randint(1,5, size=n)
... })
>>> ax = df.plot.hexbin(x='coord_x',
... y='coord_y',
... C='observations',
... reduce_C_function=np.sum,
... gridsize=10,
... cmap="viridis")
"""
if reduce_C_function is not None:
kwds['reduce_C_function'] = reduce_C_function
if gridsize is not None:
kwds['gridsize'] = gridsize
return self(kind='hexbin', x=x, y=y, C=C, **kwds) | [
"Generate",
"a",
"hexagonal",
"binning",
"plot",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L3544-L3631 | [
"def",
"hexbin",
"(",
"self",
",",
"x",
",",
"y",
",",
"C",
"=",
"None",
",",
"reduce_C_function",
"=",
"None",
",",
"gridsize",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"reduce_C_function",
"is",
"not",
"None",
":",
"kwds",
"[",
"'reduce_C_function'",
"]",
"=",
"reduce_C_function",
"if",
"gridsize",
"is",
"not",
"None",
":",
"kwds",
"[",
"'gridsize'",
"]",
"=",
"gridsize",
"return",
"self",
"(",
"kind",
"=",
"'hexbin'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"C",
"=",
"C",
",",
"*",
"*",
"kwds",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_objs_combined_axis | Extract combined index: return intersection or union (depending on the
value of "intersect") of indexes on given axis, or None if all objects
lack indexes (e.g. they are numpy arrays).
Parameters
----------
objs : list of objects
Each object will only be considered if it has a _get_axis
attribute.
intersect : bool, default False
If True, calculate the intersection between indexes. Otherwise,
calculate the union.
axis : {0 or 'index', 1 or 'outer'}, default 0
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index | pandas/core/indexes/api.py | def _get_objs_combined_axis(objs, intersect=False, axis=0, sort=True):
"""
Extract combined index: return intersection or union (depending on the
value of "intersect") of indexes on given axis, or None if all objects
lack indexes (e.g. they are numpy arrays).
Parameters
----------
objs : list of objects
Each object will only be considered if it has a _get_axis
attribute.
intersect : bool, default False
If True, calculate the intersection between indexes. Otherwise,
calculate the union.
axis : {0 or 'index', 1 or 'outer'}, default 0
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
obs_idxes = [obj._get_axis(axis) for obj in objs
if hasattr(obj, '_get_axis')]
if obs_idxes:
return _get_combined_index(obs_idxes, intersect=intersect, sort=sort) | def _get_objs_combined_axis(objs, intersect=False, axis=0, sort=True):
"""
Extract combined index: return intersection or union (depending on the
value of "intersect") of indexes on given axis, or None if all objects
lack indexes (e.g. they are numpy arrays).
Parameters
----------
objs : list of objects
Each object will only be considered if it has a _get_axis
attribute.
intersect : bool, default False
If True, calculate the intersection between indexes. Otherwise,
calculate the union.
axis : {0 or 'index', 1 or 'outer'}, default 0
The axis to extract indexes from.
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
obs_idxes = [obj._get_axis(axis) for obj in objs
if hasattr(obj, '_get_axis')]
if obs_idxes:
return _get_combined_index(obs_idxes, intersect=intersect, sort=sort) | [
"Extract",
"combined",
"index",
":",
"return",
"intersection",
"or",
"union",
"(",
"depending",
"on",
"the",
"value",
"of",
"intersect",
")",
"of",
"indexes",
"on",
"given",
"axis",
"or",
"None",
"if",
"all",
"objects",
"lack",
"indexes",
"(",
"e",
".",
"g",
".",
"they",
"are",
"numpy",
"arrays",
")",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/api.py#L44-L70 | [
"def",
"_get_objs_combined_axis",
"(",
"objs",
",",
"intersect",
"=",
"False",
",",
"axis",
"=",
"0",
",",
"sort",
"=",
"True",
")",
":",
"obs_idxes",
"=",
"[",
"obj",
".",
"_get_axis",
"(",
"axis",
")",
"for",
"obj",
"in",
"objs",
"if",
"hasattr",
"(",
"obj",
",",
"'_get_axis'",
")",
"]",
"if",
"obs_idxes",
":",
"return",
"_get_combined_index",
"(",
"obs_idxes",
",",
"intersect",
"=",
"intersect",
",",
"sort",
"=",
"sort",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_distinct_objs | Return a list with distinct elements of "objs" (different ids).
Preserves order. | pandas/core/indexes/api.py | def _get_distinct_objs(objs):
"""
Return a list with distinct elements of "objs" (different ids).
Preserves order.
"""
ids = set()
res = []
for obj in objs:
if not id(obj) in ids:
ids.add(id(obj))
res.append(obj)
return res | def _get_distinct_objs(objs):
"""
Return a list with distinct elements of "objs" (different ids).
Preserves order.
"""
ids = set()
res = []
for obj in objs:
if not id(obj) in ids:
ids.add(id(obj))
res.append(obj)
return res | [
"Return",
"a",
"list",
"with",
"distinct",
"elements",
"of",
"objs",
"(",
"different",
"ids",
")",
".",
"Preserves",
"order",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/api.py#L73-L84 | [
"def",
"_get_distinct_objs",
"(",
"objs",
")",
":",
"ids",
"=",
"set",
"(",
")",
"res",
"=",
"[",
"]",
"for",
"obj",
"in",
"objs",
":",
"if",
"not",
"id",
"(",
"obj",
")",
"in",
"ids",
":",
"ids",
".",
"add",
"(",
"id",
"(",
"obj",
")",
")",
"res",
".",
"append",
"(",
"obj",
")",
"return",
"res"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_combined_index | Return the union or intersection of indexes.
Parameters
----------
indexes : list of Index or list objects
When intersect=True, do not accept list of lists.
intersect : bool, default False
If True, calculate the intersection between indexes. Otherwise,
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
Returns
-------
Index | pandas/core/indexes/api.py | def _get_combined_index(indexes, intersect=False, sort=False):
"""
Return the union or intersection of indexes.
Parameters
----------
indexes : list of Index or list objects
When intersect=True, do not accept list of lists.
intersect : bool, default False
If True, calculate the intersection between indexes. Otherwise,
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
# TODO: handle index names!
indexes = _get_distinct_objs(indexes)
if len(indexes) == 0:
index = Index([])
elif len(indexes) == 1:
index = indexes[0]
elif intersect:
index = indexes[0]
for other in indexes[1:]:
index = index.intersection(other)
else:
index = _union_indexes(indexes, sort=sort)
index = ensure_index(index)
if sort:
try:
index = index.sort_values()
except TypeError:
pass
return index | def _get_combined_index(indexes, intersect=False, sort=False):
"""
Return the union or intersection of indexes.
Parameters
----------
indexes : list of Index or list objects
When intersect=True, do not accept list of lists.
intersect : bool, default False
If True, calculate the intersection between indexes. Otherwise,
calculate the union.
sort : bool, default False
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
# TODO: handle index names!
indexes = _get_distinct_objs(indexes)
if len(indexes) == 0:
index = Index([])
elif len(indexes) == 1:
index = indexes[0]
elif intersect:
index = indexes[0]
for other in indexes[1:]:
index = index.intersection(other)
else:
index = _union_indexes(indexes, sort=sort)
index = ensure_index(index)
if sort:
try:
index = index.sort_values()
except TypeError:
pass
return index | [
"Return",
"the",
"union",
"or",
"intersection",
"of",
"indexes",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/api.py#L87-L125 | [
"def",
"_get_combined_index",
"(",
"indexes",
",",
"intersect",
"=",
"False",
",",
"sort",
"=",
"False",
")",
":",
"# TODO: handle index names!",
"indexes",
"=",
"_get_distinct_objs",
"(",
"indexes",
")",
"if",
"len",
"(",
"indexes",
")",
"==",
"0",
":",
"index",
"=",
"Index",
"(",
"[",
"]",
")",
"elif",
"len",
"(",
"indexes",
")",
"==",
"1",
":",
"index",
"=",
"indexes",
"[",
"0",
"]",
"elif",
"intersect",
":",
"index",
"=",
"indexes",
"[",
"0",
"]",
"for",
"other",
"in",
"indexes",
"[",
"1",
":",
"]",
":",
"index",
"=",
"index",
".",
"intersection",
"(",
"other",
")",
"else",
":",
"index",
"=",
"_union_indexes",
"(",
"indexes",
",",
"sort",
"=",
"sort",
")",
"index",
"=",
"ensure_index",
"(",
"index",
")",
"if",
"sort",
":",
"try",
":",
"index",
"=",
"index",
".",
"sort_values",
"(",
")",
"except",
"TypeError",
":",
"pass",
"return",
"index"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _union_indexes | Return the union of indexes.
The behavior of sort and names is not consistent.
Parameters
----------
indexes : list of Index or list objects
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index | pandas/core/indexes/api.py | def _union_indexes(indexes, sort=True):
"""
Return the union of indexes.
The behavior of sort and names is not consistent.
Parameters
----------
indexes : list of Index or list objects
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
if len(indexes) == 0:
raise AssertionError('Must have at least 1 Index to union')
if len(indexes) == 1:
result = indexes[0]
if isinstance(result, list):
result = Index(sorted(result))
return result
indexes, kind = _sanitize_and_check(indexes)
def _unique_indices(inds):
"""
Convert indexes to lists and concatenate them, removing duplicates.
The final dtype is inferred.
Parameters
----------
inds : list of Index or list objects
Returns
-------
Index
"""
def conv(i):
if isinstance(i, Index):
i = i.tolist()
return i
return Index(
lib.fast_unique_multiple_list([conv(i) for i in inds], sort=sort))
if kind == 'special':
result = indexes[0]
if hasattr(result, 'union_many'):
return result.union_many(indexes[1:])
else:
for other in indexes[1:]:
result = result.union(other)
return result
elif kind == 'array':
index = indexes[0]
for other in indexes[1:]:
if not index.equals(other):
if sort is None:
# TODO: remove once pd.concat sort default changes
warnings.warn(_sort_msg, FutureWarning, stacklevel=8)
sort = True
return _unique_indices(indexes)
name = _get_consensus_names(indexes)[0]
if name != index.name:
index = index._shallow_copy(name=name)
return index
else: # kind='list'
return _unique_indices(indexes) | def _union_indexes(indexes, sort=True):
"""
Return the union of indexes.
The behavior of sort and names is not consistent.
Parameters
----------
indexes : list of Index or list objects
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
-------
Index
"""
if len(indexes) == 0:
raise AssertionError('Must have at least 1 Index to union')
if len(indexes) == 1:
result = indexes[0]
if isinstance(result, list):
result = Index(sorted(result))
return result
indexes, kind = _sanitize_and_check(indexes)
def _unique_indices(inds):
"""
Convert indexes to lists and concatenate them, removing duplicates.
The final dtype is inferred.
Parameters
----------
inds : list of Index or list objects
Returns
-------
Index
"""
def conv(i):
if isinstance(i, Index):
i = i.tolist()
return i
return Index(
lib.fast_unique_multiple_list([conv(i) for i in inds], sort=sort))
if kind == 'special':
result = indexes[0]
if hasattr(result, 'union_many'):
return result.union_many(indexes[1:])
else:
for other in indexes[1:]:
result = result.union(other)
return result
elif kind == 'array':
index = indexes[0]
for other in indexes[1:]:
if not index.equals(other):
if sort is None:
# TODO: remove once pd.concat sort default changes
warnings.warn(_sort_msg, FutureWarning, stacklevel=8)
sort = True
return _unique_indices(indexes)
name = _get_consensus_names(indexes)[0]
if name != index.name:
index = index._shallow_copy(name=name)
return index
else: # kind='list'
return _unique_indices(indexes) | [
"Return",
"the",
"union",
"of",
"indexes",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/api.py#L128-L202 | [
"def",
"_union_indexes",
"(",
"indexes",
",",
"sort",
"=",
"True",
")",
":",
"if",
"len",
"(",
"indexes",
")",
"==",
"0",
":",
"raise",
"AssertionError",
"(",
"'Must have at least 1 Index to union'",
")",
"if",
"len",
"(",
"indexes",
")",
"==",
"1",
":",
"result",
"=",
"indexes",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"result",
",",
"list",
")",
":",
"result",
"=",
"Index",
"(",
"sorted",
"(",
"result",
")",
")",
"return",
"result",
"indexes",
",",
"kind",
"=",
"_sanitize_and_check",
"(",
"indexes",
")",
"def",
"_unique_indices",
"(",
"inds",
")",
":",
"\"\"\"\n Convert indexes to lists and concatenate them, removing duplicates.\n\n The final dtype is inferred.\n\n Parameters\n ----------\n inds : list of Index or list objects\n\n Returns\n -------\n Index\n \"\"\"",
"def",
"conv",
"(",
"i",
")",
":",
"if",
"isinstance",
"(",
"i",
",",
"Index",
")",
":",
"i",
"=",
"i",
".",
"tolist",
"(",
")",
"return",
"i",
"return",
"Index",
"(",
"lib",
".",
"fast_unique_multiple_list",
"(",
"[",
"conv",
"(",
"i",
")",
"for",
"i",
"in",
"inds",
"]",
",",
"sort",
"=",
"sort",
")",
")",
"if",
"kind",
"==",
"'special'",
":",
"result",
"=",
"indexes",
"[",
"0",
"]",
"if",
"hasattr",
"(",
"result",
",",
"'union_many'",
")",
":",
"return",
"result",
".",
"union_many",
"(",
"indexes",
"[",
"1",
":",
"]",
")",
"else",
":",
"for",
"other",
"in",
"indexes",
"[",
"1",
":",
"]",
":",
"result",
"=",
"result",
".",
"union",
"(",
"other",
")",
"return",
"result",
"elif",
"kind",
"==",
"'array'",
":",
"index",
"=",
"indexes",
"[",
"0",
"]",
"for",
"other",
"in",
"indexes",
"[",
"1",
":",
"]",
":",
"if",
"not",
"index",
".",
"equals",
"(",
"other",
")",
":",
"if",
"sort",
"is",
"None",
":",
"# TODO: remove once pd.concat sort default changes",
"warnings",
".",
"warn",
"(",
"_sort_msg",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"8",
")",
"sort",
"=",
"True",
"return",
"_unique_indices",
"(",
"indexes",
")",
"name",
"=",
"_get_consensus_names",
"(",
"indexes",
")",
"[",
"0",
"]",
"if",
"name",
"!=",
"index",
".",
"name",
":",
"index",
"=",
"index",
".",
"_shallow_copy",
"(",
"name",
"=",
"name",
")",
"return",
"index",
"else",
":",
"# kind='list'",
"return",
"_unique_indices",
"(",
"indexes",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _sanitize_and_check | Verify the type of indexes and convert lists to Index.
Cases:
- [list, list, ...]: Return ([list, list, ...], 'list')
- [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...])
Lists are sorted and converted to Index.
- [Index, Index, ...]: Return ([Index, Index, ...], TYPE)
TYPE = 'special' if at least one special type, 'array' otherwise.
Parameters
----------
indexes : list of Index or list objects
Returns
-------
sanitized_indexes : list of Index or list objects
type : {'list', 'array', 'special'} | pandas/core/indexes/api.py | def _sanitize_and_check(indexes):
"""
Verify the type of indexes and convert lists to Index.
Cases:
- [list, list, ...]: Return ([list, list, ...], 'list')
- [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...])
Lists are sorted and converted to Index.
- [Index, Index, ...]: Return ([Index, Index, ...], TYPE)
TYPE = 'special' if at least one special type, 'array' otherwise.
Parameters
----------
indexes : list of Index or list objects
Returns
-------
sanitized_indexes : list of Index or list objects
type : {'list', 'array', 'special'}
"""
kinds = list({type(index) for index in indexes})
if list in kinds:
if len(kinds) > 1:
indexes = [Index(com.try_sort(x))
if not isinstance(x, Index) else
x for x in indexes]
kinds.remove(list)
else:
return indexes, 'list'
if len(kinds) > 1 or Index not in kinds:
return indexes, 'special'
else:
return indexes, 'array' | def _sanitize_and_check(indexes):
"""
Verify the type of indexes and convert lists to Index.
Cases:
- [list, list, ...]: Return ([list, list, ...], 'list')
- [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...])
Lists are sorted and converted to Index.
- [Index, Index, ...]: Return ([Index, Index, ...], TYPE)
TYPE = 'special' if at least one special type, 'array' otherwise.
Parameters
----------
indexes : list of Index or list objects
Returns
-------
sanitized_indexes : list of Index or list objects
type : {'list', 'array', 'special'}
"""
kinds = list({type(index) for index in indexes})
if list in kinds:
if len(kinds) > 1:
indexes = [Index(com.try_sort(x))
if not isinstance(x, Index) else
x for x in indexes]
kinds.remove(list)
else:
return indexes, 'list'
if len(kinds) > 1 or Index not in kinds:
return indexes, 'special'
else:
return indexes, 'array' | [
"Verify",
"the",
"type",
"of",
"indexes",
"and",
"convert",
"lists",
"to",
"Index",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/api.py#L205-L240 | [
"def",
"_sanitize_and_check",
"(",
"indexes",
")",
":",
"kinds",
"=",
"list",
"(",
"{",
"type",
"(",
"index",
")",
"for",
"index",
"in",
"indexes",
"}",
")",
"if",
"list",
"in",
"kinds",
":",
"if",
"len",
"(",
"kinds",
")",
">",
"1",
":",
"indexes",
"=",
"[",
"Index",
"(",
"com",
".",
"try_sort",
"(",
"x",
")",
")",
"if",
"not",
"isinstance",
"(",
"x",
",",
"Index",
")",
"else",
"x",
"for",
"x",
"in",
"indexes",
"]",
"kinds",
".",
"remove",
"(",
"list",
")",
"else",
":",
"return",
"indexes",
",",
"'list'",
"if",
"len",
"(",
"kinds",
")",
">",
"1",
"or",
"Index",
"not",
"in",
"kinds",
":",
"return",
"indexes",
",",
"'special'",
"else",
":",
"return",
"indexes",
",",
"'array'"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_consensus_names | Give a consensus 'names' to indexes.
If there's exactly one non-empty 'names', return this,
otherwise, return empty.
Parameters
----------
indexes : list of Index objects
Returns
-------
list
A list representing the consensus 'names' found. | pandas/core/indexes/api.py | def _get_consensus_names(indexes):
"""
Give a consensus 'names' to indexes.
If there's exactly one non-empty 'names', return this,
otherwise, return empty.
Parameters
----------
indexes : list of Index objects
Returns
-------
list
A list representing the consensus 'names' found.
"""
# find the non-none names, need to tupleify to make
# the set hashable, then reverse on return
consensus_names = {tuple(i.names) for i in indexes
if com._any_not_none(*i.names)}
if len(consensus_names) == 1:
return list(list(consensus_names)[0])
return [None] * indexes[0].nlevels | def _get_consensus_names(indexes):
"""
Give a consensus 'names' to indexes.
If there's exactly one non-empty 'names', return this,
otherwise, return empty.
Parameters
----------
indexes : list of Index objects
Returns
-------
list
A list representing the consensus 'names' found.
"""
# find the non-none names, need to tupleify to make
# the set hashable, then reverse on return
consensus_names = {tuple(i.names) for i in indexes
if com._any_not_none(*i.names)}
if len(consensus_names) == 1:
return list(list(consensus_names)[0])
return [None] * indexes[0].nlevels | [
"Give",
"a",
"consensus",
"names",
"to",
"indexes",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/api.py#L243-L266 | [
"def",
"_get_consensus_names",
"(",
"indexes",
")",
":",
"# find the non-none names, need to tupleify to make",
"# the set hashable, then reverse on return",
"consensus_names",
"=",
"{",
"tuple",
"(",
"i",
".",
"names",
")",
"for",
"i",
"in",
"indexes",
"if",
"com",
".",
"_any_not_none",
"(",
"*",
"i",
".",
"names",
")",
"}",
"if",
"len",
"(",
"consensus_names",
")",
"==",
"1",
":",
"return",
"list",
"(",
"list",
"(",
"consensus_names",
")",
"[",
"0",
"]",
")",
"return",
"[",
"None",
"]",
"*",
"indexes",
"[",
"0",
"]",
".",
"nlevels"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _all_indexes_same | Determine if all indexes contain the same elements.
Parameters
----------
indexes : list of Index objects
Returns
-------
bool
True if all indexes contain the same elements, False otherwise. | pandas/core/indexes/api.py | def _all_indexes_same(indexes):
"""
Determine if all indexes contain the same elements.
Parameters
----------
indexes : list of Index objects
Returns
-------
bool
True if all indexes contain the same elements, False otherwise.
"""
first = indexes[0]
for index in indexes[1:]:
if not first.equals(index):
return False
return True | def _all_indexes_same(indexes):
"""
Determine if all indexes contain the same elements.
Parameters
----------
indexes : list of Index objects
Returns
-------
bool
True if all indexes contain the same elements, False otherwise.
"""
first = indexes[0]
for index in indexes[1:]:
if not first.equals(index):
return False
return True | [
"Determine",
"if",
"all",
"indexes",
"contain",
"the",
"same",
"elements",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/api.py#L269-L286 | [
"def",
"_all_indexes_same",
"(",
"indexes",
")",
":",
"first",
"=",
"indexes",
"[",
"0",
"]",
"for",
"index",
"in",
"indexes",
"[",
"1",
":",
"]",
":",
"if",
"not",
"first",
".",
"equals",
"(",
"index",
")",
":",
"return",
"False",
"return",
"True"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _convert_params | Convert SQL and params args to DBAPI2.0 compliant format. | pandas/io/sql.py | def _convert_params(sql, params):
"""Convert SQL and params args to DBAPI2.0 compliant format."""
args = [sql]
if params is not None:
if hasattr(params, 'keys'): # test if params is a mapping
args += [params]
else:
args += [list(params)]
return args | def _convert_params(sql, params):
"""Convert SQL and params args to DBAPI2.0 compliant format."""
args = [sql]
if params is not None:
if hasattr(params, 'keys'): # test if params is a mapping
args += [params]
else:
args += [list(params)]
return args | [
"Convert",
"SQL",
"and",
"params",
"args",
"to",
"DBAPI2",
".",
"0",
"compliant",
"format",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L57-L65 | [
"def",
"_convert_params",
"(",
"sql",
",",
"params",
")",
":",
"args",
"=",
"[",
"sql",
"]",
"if",
"params",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"params",
",",
"'keys'",
")",
":",
"# test if params is a mapping",
"args",
"+=",
"[",
"params",
"]",
"else",
":",
"args",
"+=",
"[",
"list",
"(",
"params",
")",
"]",
"return",
"args"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _process_parse_dates_argument | Process parse_dates argument for read_sql functions | pandas/io/sql.py | def _process_parse_dates_argument(parse_dates):
"""Process parse_dates argument for read_sql functions"""
# handle non-list entries for parse_dates gracefully
if parse_dates is True or parse_dates is None or parse_dates is False:
parse_dates = []
elif not hasattr(parse_dates, '__iter__'):
parse_dates = [parse_dates]
return parse_dates | def _process_parse_dates_argument(parse_dates):
"""Process parse_dates argument for read_sql functions"""
# handle non-list entries for parse_dates gracefully
if parse_dates is True or parse_dates is None or parse_dates is False:
parse_dates = []
elif not hasattr(parse_dates, '__iter__'):
parse_dates = [parse_dates]
return parse_dates | [
"Process",
"parse_dates",
"argument",
"for",
"read_sql",
"functions"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L68-L76 | [
"def",
"_process_parse_dates_argument",
"(",
"parse_dates",
")",
":",
"# handle non-list entries for parse_dates gracefully",
"if",
"parse_dates",
"is",
"True",
"or",
"parse_dates",
"is",
"None",
"or",
"parse_dates",
"is",
"False",
":",
"parse_dates",
"=",
"[",
"]",
"elif",
"not",
"hasattr",
"(",
"parse_dates",
",",
"'__iter__'",
")",
":",
"parse_dates",
"=",
"[",
"parse_dates",
"]",
"return",
"parse_dates"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _parse_date_columns | Force non-datetime columns to be read as such.
Supports both string formatted and integer timestamp columns. | pandas/io/sql.py | def _parse_date_columns(data_frame, parse_dates):
"""
Force non-datetime columns to be read as such.
Supports both string formatted and integer timestamp columns.
"""
parse_dates = _process_parse_dates_argument(parse_dates)
# we want to coerce datetime64_tz dtypes for now to UTC
# we could in theory do a 'nice' conversion from a FixedOffset tz
# GH11216
for col_name, df_col in data_frame.iteritems():
if is_datetime64tz_dtype(df_col) or col_name in parse_dates:
try:
fmt = parse_dates[col_name]
except TypeError:
fmt = None
data_frame[col_name] = _handle_date_column(df_col, format=fmt)
return data_frame | def _parse_date_columns(data_frame, parse_dates):
"""
Force non-datetime columns to be read as such.
Supports both string formatted and integer timestamp columns.
"""
parse_dates = _process_parse_dates_argument(parse_dates)
# we want to coerce datetime64_tz dtypes for now to UTC
# we could in theory do a 'nice' conversion from a FixedOffset tz
# GH11216
for col_name, df_col in data_frame.iteritems():
if is_datetime64tz_dtype(df_col) or col_name in parse_dates:
try:
fmt = parse_dates[col_name]
except TypeError:
fmt = None
data_frame[col_name] = _handle_date_column(df_col, format=fmt)
return data_frame | [
"Force",
"non",
"-",
"datetime",
"columns",
"to",
"be",
"read",
"as",
"such",
".",
"Supports",
"both",
"string",
"formatted",
"and",
"integer",
"timestamp",
"columns",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L98-L116 | [
"def",
"_parse_date_columns",
"(",
"data_frame",
",",
"parse_dates",
")",
":",
"parse_dates",
"=",
"_process_parse_dates_argument",
"(",
"parse_dates",
")",
"# we want to coerce datetime64_tz dtypes for now to UTC",
"# we could in theory do a 'nice' conversion from a FixedOffset tz",
"# GH11216",
"for",
"col_name",
",",
"df_col",
"in",
"data_frame",
".",
"iteritems",
"(",
")",
":",
"if",
"is_datetime64tz_dtype",
"(",
"df_col",
")",
"or",
"col_name",
"in",
"parse_dates",
":",
"try",
":",
"fmt",
"=",
"parse_dates",
"[",
"col_name",
"]",
"except",
"TypeError",
":",
"fmt",
"=",
"None",
"data_frame",
"[",
"col_name",
"]",
"=",
"_handle_date_column",
"(",
"df_col",
",",
"format",
"=",
"fmt",
")",
"return",
"data_frame"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _wrap_result | Wrap result set of query in a DataFrame. | pandas/io/sql.py | def _wrap_result(data, columns, index_col=None, coerce_float=True,
parse_dates=None):
"""Wrap result set of query in a DataFrame."""
frame = DataFrame.from_records(data, columns=columns,
coerce_float=coerce_float)
frame = _parse_date_columns(frame, parse_dates)
if index_col is not None:
frame.set_index(index_col, inplace=True)
return frame | def _wrap_result(data, columns, index_col=None, coerce_float=True,
parse_dates=None):
"""Wrap result set of query in a DataFrame."""
frame = DataFrame.from_records(data, columns=columns,
coerce_float=coerce_float)
frame = _parse_date_columns(frame, parse_dates)
if index_col is not None:
frame.set_index(index_col, inplace=True)
return frame | [
"Wrap",
"result",
"set",
"of",
"query",
"in",
"a",
"DataFrame",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L119-L131 | [
"def",
"_wrap_result",
"(",
"data",
",",
"columns",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
")",
":",
"frame",
"=",
"DataFrame",
".",
"from_records",
"(",
"data",
",",
"columns",
"=",
"columns",
",",
"coerce_float",
"=",
"coerce_float",
")",
"frame",
"=",
"_parse_date_columns",
"(",
"frame",
",",
"parse_dates",
")",
"if",
"index_col",
"is",
"not",
"None",
":",
"frame",
".",
"set_index",
"(",
"index_col",
",",
"inplace",
"=",
"True",
")",
"return",
"frame"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | execute | Execute the given SQL query using the provided connection object.
Parameters
----------
sql : string
SQL query to be executed.
con : SQLAlchemy connectable(engine/connection) or sqlite3 connection
Using SQLAlchemy makes it possible to use any DB supported by the
library.
If a DBAPI2 object, only sqlite3 is supported.
cur : deprecated, cursor is obtained from connection, default: None
params : list or tuple, optional, default: None
List of parameters to pass to execute method.
Returns
-------
Results Iterable | pandas/io/sql.py | def execute(sql, con, cur=None, params=None):
"""
Execute the given SQL query using the provided connection object.
Parameters
----------
sql : string
SQL query to be executed.
con : SQLAlchemy connectable(engine/connection) or sqlite3 connection
Using SQLAlchemy makes it possible to use any DB supported by the
library.
If a DBAPI2 object, only sqlite3 is supported.
cur : deprecated, cursor is obtained from connection, default: None
params : list or tuple, optional, default: None
List of parameters to pass to execute method.
Returns
-------
Results Iterable
"""
if cur is None:
pandas_sql = pandasSQL_builder(con)
else:
pandas_sql = pandasSQL_builder(cur, is_cursor=True)
args = _convert_params(sql, params)
return pandas_sql.execute(*args) | def execute(sql, con, cur=None, params=None):
"""
Execute the given SQL query using the provided connection object.
Parameters
----------
sql : string
SQL query to be executed.
con : SQLAlchemy connectable(engine/connection) or sqlite3 connection
Using SQLAlchemy makes it possible to use any DB supported by the
library.
If a DBAPI2 object, only sqlite3 is supported.
cur : deprecated, cursor is obtained from connection, default: None
params : list or tuple, optional, default: None
List of parameters to pass to execute method.
Returns
-------
Results Iterable
"""
if cur is None:
pandas_sql = pandasSQL_builder(con)
else:
pandas_sql = pandasSQL_builder(cur, is_cursor=True)
args = _convert_params(sql, params)
return pandas_sql.execute(*args) | [
"Execute",
"the",
"given",
"SQL",
"query",
"using",
"the",
"provided",
"connection",
"object",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L134-L159 | [
"def",
"execute",
"(",
"sql",
",",
"con",
",",
"cur",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"cur",
"is",
"None",
":",
"pandas_sql",
"=",
"pandasSQL_builder",
"(",
"con",
")",
"else",
":",
"pandas_sql",
"=",
"pandasSQL_builder",
"(",
"cur",
",",
"is_cursor",
"=",
"True",
")",
"args",
"=",
"_convert_params",
"(",
"sql",
",",
"params",
")",
"return",
"pandas_sql",
".",
"execute",
"(",
"*",
"args",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | read_sql_table | Read SQL database table into a DataFrame.
Given a table name and a SQLAlchemy connectable, returns a DataFrame.
This function does not support DBAPI connections.
Parameters
----------
table_name : str
Name of SQL table in database.
con : SQLAlchemy connectable or str
A database URI could be provided as as str.
SQLite DBAPI connection mode not supported.
schema : str, default None
Name of SQL schema in database to query (if database flavor
supports this). Uses default schema if None (default).
index_col : str or list of str, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : bool, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Can result in loss of Precision.
parse_dates : list or dict, default None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default None
List of column names to select from SQL table.
chunksize : int, default None
If specified, returns an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame
A SQL table is returned as two-dimensional data structure with labeled
axes.
See Also
--------
read_sql_query : Read SQL query into a DataFrame.
read_sql : Read SQL query or database table into a DataFrame.
Notes
-----
Any datetime values with time zone information will be converted to UTC.
Examples
--------
>>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP | pandas/io/sql.py | def read_sql_table(table_name, con, schema=None, index_col=None,
coerce_float=True, parse_dates=None, columns=None,
chunksize=None):
"""
Read SQL database table into a DataFrame.
Given a table name and a SQLAlchemy connectable, returns a DataFrame.
This function does not support DBAPI connections.
Parameters
----------
table_name : str
Name of SQL table in database.
con : SQLAlchemy connectable or str
A database URI could be provided as as str.
SQLite DBAPI connection mode not supported.
schema : str, default None
Name of SQL schema in database to query (if database flavor
supports this). Uses default schema if None (default).
index_col : str or list of str, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : bool, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Can result in loss of Precision.
parse_dates : list or dict, default None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default None
List of column names to select from SQL table.
chunksize : int, default None
If specified, returns an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame
A SQL table is returned as two-dimensional data structure with labeled
axes.
See Also
--------
read_sql_query : Read SQL query into a DataFrame.
read_sql : Read SQL query or database table into a DataFrame.
Notes
-----
Any datetime values with time zone information will be converted to UTC.
Examples
--------
>>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
"""
con = _engine_builder(con)
if not _is_sqlalchemy_connectable(con):
raise NotImplementedError("read_sql_table only supported for "
"SQLAlchemy connectable.")
import sqlalchemy
from sqlalchemy.schema import MetaData
meta = MetaData(con, schema=schema)
try:
meta.reflect(only=[table_name], views=True)
except sqlalchemy.exc.InvalidRequestError:
raise ValueError("Table {name} not found".format(name=table_name))
pandas_sql = SQLDatabase(con, meta=meta)
table = pandas_sql.read_table(
table_name, index_col=index_col, coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns, chunksize=chunksize)
if table is not None:
return table
else:
raise ValueError("Table {name} not found".format(name=table_name), con) | def read_sql_table(table_name, con, schema=None, index_col=None,
coerce_float=True, parse_dates=None, columns=None,
chunksize=None):
"""
Read SQL database table into a DataFrame.
Given a table name and a SQLAlchemy connectable, returns a DataFrame.
This function does not support DBAPI connections.
Parameters
----------
table_name : str
Name of SQL table in database.
con : SQLAlchemy connectable or str
A database URI could be provided as as str.
SQLite DBAPI connection mode not supported.
schema : str, default None
Name of SQL schema in database to query (if database flavor
supports this). Uses default schema if None (default).
index_col : str or list of str, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : bool, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Can result in loss of Precision.
parse_dates : list or dict, default None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default None
List of column names to select from SQL table.
chunksize : int, default None
If specified, returns an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame
A SQL table is returned as two-dimensional data structure with labeled
axes.
See Also
--------
read_sql_query : Read SQL query into a DataFrame.
read_sql : Read SQL query or database table into a DataFrame.
Notes
-----
Any datetime values with time zone information will be converted to UTC.
Examples
--------
>>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
"""
con = _engine_builder(con)
if not _is_sqlalchemy_connectable(con):
raise NotImplementedError("read_sql_table only supported for "
"SQLAlchemy connectable.")
import sqlalchemy
from sqlalchemy.schema import MetaData
meta = MetaData(con, schema=schema)
try:
meta.reflect(only=[table_name], views=True)
except sqlalchemy.exc.InvalidRequestError:
raise ValueError("Table {name} not found".format(name=table_name))
pandas_sql = SQLDatabase(con, meta=meta)
table = pandas_sql.read_table(
table_name, index_col=index_col, coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns, chunksize=chunksize)
if table is not None:
return table
else:
raise ValueError("Table {name} not found".format(name=table_name), con) | [
"Read",
"SQL",
"database",
"table",
"into",
"a",
"DataFrame",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L165-L244 | [
"def",
"read_sql_table",
"(",
"table_name",
",",
"con",
",",
"schema",
"=",
"None",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"con",
"=",
"_engine_builder",
"(",
"con",
")",
"if",
"not",
"_is_sqlalchemy_connectable",
"(",
"con",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"read_sql_table only supported for \"",
"\"SQLAlchemy connectable.\"",
")",
"import",
"sqlalchemy",
"from",
"sqlalchemy",
".",
"schema",
"import",
"MetaData",
"meta",
"=",
"MetaData",
"(",
"con",
",",
"schema",
"=",
"schema",
")",
"try",
":",
"meta",
".",
"reflect",
"(",
"only",
"=",
"[",
"table_name",
"]",
",",
"views",
"=",
"True",
")",
"except",
"sqlalchemy",
".",
"exc",
".",
"InvalidRequestError",
":",
"raise",
"ValueError",
"(",
"\"Table {name} not found\"",
".",
"format",
"(",
"name",
"=",
"table_name",
")",
")",
"pandas_sql",
"=",
"SQLDatabase",
"(",
"con",
",",
"meta",
"=",
"meta",
")",
"table",
"=",
"pandas_sql",
".",
"read_table",
"(",
"table_name",
",",
"index_col",
"=",
"index_col",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"columns",
"=",
"columns",
",",
"chunksize",
"=",
"chunksize",
")",
"if",
"table",
"is",
"not",
"None",
":",
"return",
"table",
"else",
":",
"raise",
"ValueError",
"(",
"\"Table {name} not found\"",
".",
"format",
"(",
"name",
"=",
"table_name",
")",
",",
"con",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | read_sql_query | Read SQL query into a DataFrame.
Returns a DataFrame corresponding to the result set of the query
string. Optionally provide an `index_col` parameter to use one of the
columns as the index, otherwise default integer index will be used.
Parameters
----------
sql : string SQL query or SQLAlchemy Selectable (select or text object)
SQL query to be executed.
con : SQLAlchemy connectable(engine/connection), database string URI,
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
index_col : string or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql
Notes
-----
Any datetime values with time zone information parsed via the `parse_dates`
parameter will be converted to UTC. | pandas/io/sql.py | def read_sql_query(sql, con, index_col=None, coerce_float=True, params=None,
parse_dates=None, chunksize=None):
"""Read SQL query into a DataFrame.
Returns a DataFrame corresponding to the result set of the query
string. Optionally provide an `index_col` parameter to use one of the
columns as the index, otherwise default integer index will be used.
Parameters
----------
sql : string SQL query or SQLAlchemy Selectable (select or text object)
SQL query to be executed.
con : SQLAlchemy connectable(engine/connection), database string URI,
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
index_col : string or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql
Notes
-----
Any datetime values with time zone information parsed via the `parse_dates`
parameter will be converted to UTC.
"""
pandas_sql = pandasSQL_builder(con)
return pandas_sql.read_query(
sql, index_col=index_col, params=params, coerce_float=coerce_float,
parse_dates=parse_dates, chunksize=chunksize) | def read_sql_query(sql, con, index_col=None, coerce_float=True, params=None,
parse_dates=None, chunksize=None):
"""Read SQL query into a DataFrame.
Returns a DataFrame corresponding to the result set of the query
string. Optionally provide an `index_col` parameter to use one of the
columns as the index, otherwise default integer index will be used.
Parameters
----------
sql : string SQL query or SQLAlchemy Selectable (select or text object)
SQL query to be executed.
con : SQLAlchemy connectable(engine/connection), database string URI,
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
index_col : string or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql
Notes
-----
Any datetime values with time zone information parsed via the `parse_dates`
parameter will be converted to UTC.
"""
pandas_sql = pandasSQL_builder(con)
return pandas_sql.read_query(
sql, index_col=index_col, params=params, coerce_float=coerce_float,
parse_dates=parse_dates, chunksize=chunksize) | [
"Read",
"SQL",
"query",
"into",
"a",
"DataFrame",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L247-L305 | [
"def",
"read_sql_query",
"(",
"sql",
",",
"con",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"pandas_sql",
"=",
"pandasSQL_builder",
"(",
"con",
")",
"return",
"pandas_sql",
".",
"read_query",
"(",
"sql",
",",
"index_col",
"=",
"index_col",
",",
"params",
"=",
"params",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"chunksize",
"=",
"chunksize",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | read_sql | Read SQL query or database table into a DataFrame.
This function is a convenience wrapper around ``read_sql_table`` and
``read_sql_query`` (for backward compatibility). It will delegate
to the specific function depending on the provided input. A SQL query
will be routed to ``read_sql_query``, while a database table name will
be routed to ``read_sql_table``. Note that the delegated function might
have more specific notes about their functionality not listed here.
Parameters
----------
sql : string or SQLAlchemy Selectable (select or text object)
SQL query to be executed or a table name.
con : SQLAlchemy connectable (engine/connection) or database string URI
or DBAPI2 connection (fallback mode)
Using SQLAlchemy makes it possible to use any DB supported by that
library. If a DBAPI2 object, only sqlite3 is supported.
index_col : string or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default: None
List of column names to select from SQL table (only used when reading
a table).
chunksize : int, default None
If specified, return an iterator where `chunksize` is the
number of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql_query : Read SQL query into a DataFrame. | pandas/io/sql.py | def read_sql(sql, con, index_col=None, coerce_float=True, params=None,
parse_dates=None, columns=None, chunksize=None):
"""
Read SQL query or database table into a DataFrame.
This function is a convenience wrapper around ``read_sql_table`` and
``read_sql_query`` (for backward compatibility). It will delegate
to the specific function depending on the provided input. A SQL query
will be routed to ``read_sql_query``, while a database table name will
be routed to ``read_sql_table``. Note that the delegated function might
have more specific notes about their functionality not listed here.
Parameters
----------
sql : string or SQLAlchemy Selectable (select or text object)
SQL query to be executed or a table name.
con : SQLAlchemy connectable (engine/connection) or database string URI
or DBAPI2 connection (fallback mode)
Using SQLAlchemy makes it possible to use any DB supported by that
library. If a DBAPI2 object, only sqlite3 is supported.
index_col : string or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default: None
List of column names to select from SQL table (only used when reading
a table).
chunksize : int, default None
If specified, return an iterator where `chunksize` is the
number of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql_query : Read SQL query into a DataFrame.
"""
pandas_sql = pandasSQL_builder(con)
if isinstance(pandas_sql, SQLiteDatabase):
return pandas_sql.read_query(
sql, index_col=index_col, params=params,
coerce_float=coerce_float, parse_dates=parse_dates,
chunksize=chunksize)
try:
_is_table_name = pandas_sql.has_table(sql)
except Exception:
# using generic exception to catch errors from sql drivers (GH24988)
_is_table_name = False
if _is_table_name:
pandas_sql.meta.reflect(only=[sql])
return pandas_sql.read_table(
sql, index_col=index_col, coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns, chunksize=chunksize)
else:
return pandas_sql.read_query(
sql, index_col=index_col, params=params,
coerce_float=coerce_float, parse_dates=parse_dates,
chunksize=chunksize) | def read_sql(sql, con, index_col=None, coerce_float=True, params=None,
parse_dates=None, columns=None, chunksize=None):
"""
Read SQL query or database table into a DataFrame.
This function is a convenience wrapper around ``read_sql_table`` and
``read_sql_query`` (for backward compatibility). It will delegate
to the specific function depending on the provided input. A SQL query
will be routed to ``read_sql_query``, while a database table name will
be routed to ``read_sql_table``. Note that the delegated function might
have more specific notes about their functionality not listed here.
Parameters
----------
sql : string or SQLAlchemy Selectable (select or text object)
SQL query to be executed or a table name.
con : SQLAlchemy connectable (engine/connection) or database string URI
or DBAPI2 connection (fallback mode)
Using SQLAlchemy makes it possible to use any DB supported by that
library. If a DBAPI2 object, only sqlite3 is supported.
index_col : string or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default: None
List of column names to select from SQL table (only used when reading
a table).
chunksize : int, default None
If specified, return an iterator where `chunksize` is the
number of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql_query : Read SQL query into a DataFrame.
"""
pandas_sql = pandasSQL_builder(con)
if isinstance(pandas_sql, SQLiteDatabase):
return pandas_sql.read_query(
sql, index_col=index_col, params=params,
coerce_float=coerce_float, parse_dates=parse_dates,
chunksize=chunksize)
try:
_is_table_name = pandas_sql.has_table(sql)
except Exception:
# using generic exception to catch errors from sql drivers (GH24988)
_is_table_name = False
if _is_table_name:
pandas_sql.meta.reflect(only=[sql])
return pandas_sql.read_table(
sql, index_col=index_col, coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns, chunksize=chunksize)
else:
return pandas_sql.read_query(
sql, index_col=index_col, params=params,
coerce_float=coerce_float, parse_dates=parse_dates,
chunksize=chunksize) | [
"Read",
"SQL",
"query",
"or",
"database",
"table",
"into",
"a",
"DataFrame",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L308-L388 | [
"def",
"read_sql",
"(",
"sql",
",",
"con",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"pandas_sql",
"=",
"pandasSQL_builder",
"(",
"con",
")",
"if",
"isinstance",
"(",
"pandas_sql",
",",
"SQLiteDatabase",
")",
":",
"return",
"pandas_sql",
".",
"read_query",
"(",
"sql",
",",
"index_col",
"=",
"index_col",
",",
"params",
"=",
"params",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"chunksize",
"=",
"chunksize",
")",
"try",
":",
"_is_table_name",
"=",
"pandas_sql",
".",
"has_table",
"(",
"sql",
")",
"except",
"Exception",
":",
"# using generic exception to catch errors from sql drivers (GH24988)",
"_is_table_name",
"=",
"False",
"if",
"_is_table_name",
":",
"pandas_sql",
".",
"meta",
".",
"reflect",
"(",
"only",
"=",
"[",
"sql",
"]",
")",
"return",
"pandas_sql",
".",
"read_table",
"(",
"sql",
",",
"index_col",
"=",
"index_col",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"columns",
"=",
"columns",
",",
"chunksize",
"=",
"chunksize",
")",
"else",
":",
"return",
"pandas_sql",
".",
"read_query",
"(",
"sql",
",",
"index_col",
"=",
"index_col",
",",
"params",
"=",
"params",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"chunksize",
"=",
"chunksize",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | to_sql | Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame, Series
name : string
Name of SQL table.
con : SQLAlchemy connectable(engine/connection) or database string URI
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
schema : string, default None
Name of SQL schema in database to write to (if database flavor
supports this). If None, use default schema (default).
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
chunksize : int, default None
If not None, then rows will be written in batches of this size at a
time. If None, all rows will be written at once.
dtype : single SQLtype or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type, or a string for sqlite3 fallback connection.
If all columns are of the same type, one single value can be used.
method : {None, 'multi', callable}, default None
Controls the SQL insertion clause used:
- None : Uses standard SQL ``INSERT`` clause (one per row).
- 'multi': Pass multiple values in a single ``INSERT`` clause.
- callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0 | pandas/io/sql.py | def to_sql(frame, name, con, schema=None, if_exists='fail', index=True,
index_label=None, chunksize=None, dtype=None, method=None):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame, Series
name : string
Name of SQL table.
con : SQLAlchemy connectable(engine/connection) or database string URI
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
schema : string, default None
Name of SQL schema in database to write to (if database flavor
supports this). If None, use default schema (default).
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
chunksize : int, default None
If not None, then rows will be written in batches of this size at a
time. If None, all rows will be written at once.
dtype : single SQLtype or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type, or a string for sqlite3 fallback connection.
If all columns are of the same type, one single value can be used.
method : {None, 'multi', callable}, default None
Controls the SQL insertion clause used:
- None : Uses standard SQL ``INSERT`` clause (one per row).
- 'multi': Pass multiple values in a single ``INSERT`` clause.
- callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if if_exists not in ('fail', 'replace', 'append'):
raise ValueError("'{0}' is not valid for if_exists".format(if_exists))
pandas_sql = pandasSQL_builder(con, schema=schema)
if isinstance(frame, Series):
frame = frame.to_frame()
elif not isinstance(frame, DataFrame):
raise NotImplementedError("'frame' argument should be either a "
"Series or a DataFrame")
pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index,
index_label=index_label, schema=schema,
chunksize=chunksize, dtype=dtype, method=method) | def to_sql(frame, name, con, schema=None, if_exists='fail', index=True,
index_label=None, chunksize=None, dtype=None, method=None):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame, Series
name : string
Name of SQL table.
con : SQLAlchemy connectable(engine/connection) or database string URI
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
schema : string, default None
Name of SQL schema in database to write to (if database flavor
supports this). If None, use default schema (default).
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
chunksize : int, default None
If not None, then rows will be written in batches of this size at a
time. If None, all rows will be written at once.
dtype : single SQLtype or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type, or a string for sqlite3 fallback connection.
If all columns are of the same type, one single value can be used.
method : {None, 'multi', callable}, default None
Controls the SQL insertion clause used:
- None : Uses standard SQL ``INSERT`` clause (one per row).
- 'multi': Pass multiple values in a single ``INSERT`` clause.
- callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if if_exists not in ('fail', 'replace', 'append'):
raise ValueError("'{0}' is not valid for if_exists".format(if_exists))
pandas_sql = pandasSQL_builder(con, schema=schema)
if isinstance(frame, Series):
frame = frame.to_frame()
elif not isinstance(frame, DataFrame):
raise NotImplementedError("'frame' argument should be either a "
"Series or a DataFrame")
pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index,
index_label=index_label, schema=schema,
chunksize=chunksize, dtype=dtype, method=method) | [
"Write",
"records",
"stored",
"in",
"a",
"DataFrame",
"to",
"a",
"SQL",
"database",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L391-L451 | [
"def",
"to_sql",
"(",
"frame",
",",
"name",
",",
"con",
",",
"schema",
"=",
"None",
",",
"if_exists",
"=",
"'fail'",
",",
"index",
"=",
"True",
",",
"index_label",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"if",
"if_exists",
"not",
"in",
"(",
"'fail'",
",",
"'replace'",
",",
"'append'",
")",
":",
"raise",
"ValueError",
"(",
"\"'{0}' is not valid for if_exists\"",
".",
"format",
"(",
"if_exists",
")",
")",
"pandas_sql",
"=",
"pandasSQL_builder",
"(",
"con",
",",
"schema",
"=",
"schema",
")",
"if",
"isinstance",
"(",
"frame",
",",
"Series",
")",
":",
"frame",
"=",
"frame",
".",
"to_frame",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"frame",
",",
"DataFrame",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"'frame' argument should be either a \"",
"\"Series or a DataFrame\"",
")",
"pandas_sql",
".",
"to_sql",
"(",
"frame",
",",
"name",
",",
"if_exists",
"=",
"if_exists",
",",
"index",
"=",
"index",
",",
"index_label",
"=",
"index_label",
",",
"schema",
"=",
"schema",
",",
"chunksize",
"=",
"chunksize",
",",
"dtype",
"=",
"dtype",
",",
"method",
"=",
"method",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | has_table | Check if DataBase has named table.
Parameters
----------
table_name: string
Name of SQL table.
con: SQLAlchemy connectable(engine/connection) or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
schema : string, default None
Name of SQL schema in database to write to (if database flavor supports
this). If None, use default schema (default).
Returns
-------
boolean | pandas/io/sql.py | def has_table(table_name, con, schema=None):
"""
Check if DataBase has named table.
Parameters
----------
table_name: string
Name of SQL table.
con: SQLAlchemy connectable(engine/connection) or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
schema : string, default None
Name of SQL schema in database to write to (if database flavor supports
this). If None, use default schema (default).
Returns
-------
boolean
"""
pandas_sql = pandasSQL_builder(con, schema=schema)
return pandas_sql.has_table(table_name) | def has_table(table_name, con, schema=None):
"""
Check if DataBase has named table.
Parameters
----------
table_name: string
Name of SQL table.
con: SQLAlchemy connectable(engine/connection) or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
schema : string, default None
Name of SQL schema in database to write to (if database flavor supports
this). If None, use default schema (default).
Returns
-------
boolean
"""
pandas_sql = pandasSQL_builder(con, schema=schema)
return pandas_sql.has_table(table_name) | [
"Check",
"if",
"DataBase",
"has",
"named",
"table",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L454-L475 | [
"def",
"has_table",
"(",
"table_name",
",",
"con",
",",
"schema",
"=",
"None",
")",
":",
"pandas_sql",
"=",
"pandasSQL_builder",
"(",
"con",
",",
"schema",
"=",
"schema",
")",
"return",
"pandas_sql",
".",
"has_table",
"(",
"table_name",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _engine_builder | Returns a SQLAlchemy engine from a URI (if con is a string)
else it just return con without modifying it. | pandas/io/sql.py | def _engine_builder(con):
"""
Returns a SQLAlchemy engine from a URI (if con is a string)
else it just return con without modifying it.
"""
global _SQLALCHEMY_INSTALLED
if isinstance(con, str):
try:
import sqlalchemy
except ImportError:
_SQLALCHEMY_INSTALLED = False
else:
con = sqlalchemy.create_engine(con)
return con
return con | def _engine_builder(con):
"""
Returns a SQLAlchemy engine from a URI (if con is a string)
else it just return con without modifying it.
"""
global _SQLALCHEMY_INSTALLED
if isinstance(con, str):
try:
import sqlalchemy
except ImportError:
_SQLALCHEMY_INSTALLED = False
else:
con = sqlalchemy.create_engine(con)
return con
return con | [
"Returns",
"a",
"SQLAlchemy",
"engine",
"from",
"a",
"URI",
"(",
"if",
"con",
"is",
"a",
"string",
")",
"else",
"it",
"just",
"return",
"con",
"without",
"modifying",
"it",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L481-L496 | [
"def",
"_engine_builder",
"(",
"con",
")",
":",
"global",
"_SQLALCHEMY_INSTALLED",
"if",
"isinstance",
"(",
"con",
",",
"str",
")",
":",
"try",
":",
"import",
"sqlalchemy",
"except",
"ImportError",
":",
"_SQLALCHEMY_INSTALLED",
"=",
"False",
"else",
":",
"con",
"=",
"sqlalchemy",
".",
"create_engine",
"(",
"con",
")",
"return",
"con",
"return",
"con"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | pandasSQL_builder | Convenience function to return the correct PandasSQL subclass based on the
provided parameters. | pandas/io/sql.py | def pandasSQL_builder(con, schema=None, meta=None,
is_cursor=False):
"""
Convenience function to return the correct PandasSQL subclass based on the
provided parameters.
"""
# When support for DBAPI connections is removed,
# is_cursor should not be necessary.
con = _engine_builder(con)
if _is_sqlalchemy_connectable(con):
return SQLDatabase(con, schema=schema, meta=meta)
elif isinstance(con, str):
raise ImportError("Using URI string without sqlalchemy installed.")
else:
return SQLiteDatabase(con, is_cursor=is_cursor) | def pandasSQL_builder(con, schema=None, meta=None,
is_cursor=False):
"""
Convenience function to return the correct PandasSQL subclass based on the
provided parameters.
"""
# When support for DBAPI connections is removed,
# is_cursor should not be necessary.
con = _engine_builder(con)
if _is_sqlalchemy_connectable(con):
return SQLDatabase(con, schema=schema, meta=meta)
elif isinstance(con, str):
raise ImportError("Using URI string without sqlalchemy installed.")
else:
return SQLiteDatabase(con, is_cursor=is_cursor) | [
"Convenience",
"function",
"to",
"return",
"the",
"correct",
"PandasSQL",
"subclass",
"based",
"on",
"the",
"provided",
"parameters",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L499-L513 | [
"def",
"pandasSQL_builder",
"(",
"con",
",",
"schema",
"=",
"None",
",",
"meta",
"=",
"None",
",",
"is_cursor",
"=",
"False",
")",
":",
"# When support for DBAPI connections is removed,",
"# is_cursor should not be necessary.",
"con",
"=",
"_engine_builder",
"(",
"con",
")",
"if",
"_is_sqlalchemy_connectable",
"(",
"con",
")",
":",
"return",
"SQLDatabase",
"(",
"con",
",",
"schema",
"=",
"schema",
",",
"meta",
"=",
"meta",
")",
"elif",
"isinstance",
"(",
"con",
",",
"str",
")",
":",
"raise",
"ImportError",
"(",
"\"Using URI string without sqlalchemy installed.\"",
")",
"else",
":",
"return",
"SQLiteDatabase",
"(",
"con",
",",
"is_cursor",
"=",
"is_cursor",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | get_schema | Get the SQL db table schema for the given frame.
Parameters
----------
frame : DataFrame
name : string
name of SQL table
keys : string or sequence, default: None
columns to use a primary key
con: an open SQL database connection object or a SQLAlchemy connectable
Using SQLAlchemy makes it possible to use any DB supported by that
library, default: None
If a DBAPI2 object, only sqlite3 is supported.
dtype : dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type, or a string for sqlite3 fallback connection. | pandas/io/sql.py | def get_schema(frame, name, keys=None, con=None, dtype=None):
"""
Get the SQL db table schema for the given frame.
Parameters
----------
frame : DataFrame
name : string
name of SQL table
keys : string or sequence, default: None
columns to use a primary key
con: an open SQL database connection object or a SQLAlchemy connectable
Using SQLAlchemy makes it possible to use any DB supported by that
library, default: None
If a DBAPI2 object, only sqlite3 is supported.
dtype : dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type, or a string for sqlite3 fallback connection.
"""
pandas_sql = pandasSQL_builder(con=con)
return pandas_sql._create_sql_schema(frame, name, keys=keys, dtype=dtype) | def get_schema(frame, name, keys=None, con=None, dtype=None):
"""
Get the SQL db table schema for the given frame.
Parameters
----------
frame : DataFrame
name : string
name of SQL table
keys : string or sequence, default: None
columns to use a primary key
con: an open SQL database connection object or a SQLAlchemy connectable
Using SQLAlchemy makes it possible to use any DB supported by that
library, default: None
If a DBAPI2 object, only sqlite3 is supported.
dtype : dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type, or a string for sqlite3 fallback connection.
"""
pandas_sql = pandasSQL_builder(con=con)
return pandas_sql._create_sql_schema(frame, name, keys=keys, dtype=dtype) | [
"Get",
"the",
"SQL",
"db",
"table",
"schema",
"for",
"the",
"given",
"frame",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L1564-L1586 | [
"def",
"get_schema",
"(",
"frame",
",",
"name",
",",
"keys",
"=",
"None",
",",
"con",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"pandas_sql",
"=",
"pandasSQL_builder",
"(",
"con",
"=",
"con",
")",
"return",
"pandas_sql",
".",
"_create_sql_schema",
"(",
"frame",
",",
"name",
",",
"keys",
"=",
"keys",
",",
"dtype",
"=",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLTable._execute_insert | Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted | pandas/io/sql.py | def _execute_insert(self, conn, keys, data_iter):
"""Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted
"""
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(self.table.insert(), data) | def _execute_insert(self, conn, keys, data_iter):
"""Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted
"""
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(self.table.insert(), data) | [
"Execute",
"SQL",
"statement",
"inserting",
"data"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L578-L590 | [
"def",
"_execute_insert",
"(",
"self",
",",
"conn",
",",
"keys",
",",
"data_iter",
")",
":",
"data",
"=",
"[",
"dict",
"(",
"zip",
"(",
"keys",
",",
"row",
")",
")",
"for",
"row",
"in",
"data_iter",
"]",
"conn",
".",
"execute",
"(",
"self",
".",
"table",
".",
"insert",
"(",
")",
",",
"data",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLTable._query_iterator | Return generator through chunked result set. | pandas/io/sql.py | def _query_iterator(self, result, chunksize, columns, coerce_float=True,
parse_dates=None):
"""Return generator through chunked result set."""
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
self.frame = DataFrame.from_records(
data, columns=columns, coerce_float=coerce_float)
self._harmonize_columns(parse_dates=parse_dates)
if self.index is not None:
self.frame.set_index(self.index, inplace=True)
yield self.frame | def _query_iterator(self, result, chunksize, columns, coerce_float=True,
parse_dates=None):
"""Return generator through chunked result set."""
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
self.frame = DataFrame.from_records(
data, columns=columns, coerce_float=coerce_float)
self._harmonize_columns(parse_dates=parse_dates)
if self.index is not None:
self.frame.set_index(self.index, inplace=True)
yield self.frame | [
"Return",
"generator",
"through",
"chunked",
"result",
"set",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L679-L696 | [
"def",
"_query_iterator",
"(",
"self",
",",
"result",
",",
"chunksize",
",",
"columns",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
")",
":",
"while",
"True",
":",
"data",
"=",
"result",
".",
"fetchmany",
"(",
"chunksize",
")",
"if",
"not",
"data",
":",
"break",
"else",
":",
"self",
".",
"frame",
"=",
"DataFrame",
".",
"from_records",
"(",
"data",
",",
"columns",
"=",
"columns",
",",
"coerce_float",
"=",
"coerce_float",
")",
"self",
".",
"_harmonize_columns",
"(",
"parse_dates",
"=",
"parse_dates",
")",
"if",
"self",
".",
"index",
"is",
"not",
"None",
":",
"self",
".",
"frame",
".",
"set_index",
"(",
"self",
".",
"index",
",",
"inplace",
"=",
"True",
")",
"yield",
"self",
".",
"frame"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLTable._harmonize_columns | Make the DataFrame's column types align with the SQL table
column types.
Need to work around limited NA value support. Floats are always
fine, ints must always be floats if there are Null values.
Booleans are hard because converting bool column with None replaces
all Nones with false. Therefore only convert bool if there are no
NA values.
Datetimes should already be converted to np.datetime64 if supported,
but here we also force conversion if required. | pandas/io/sql.py | def _harmonize_columns(self, parse_dates=None):
"""
Make the DataFrame's column types align with the SQL table
column types.
Need to work around limited NA value support. Floats are always
fine, ints must always be floats if there are Null values.
Booleans are hard because converting bool column with None replaces
all Nones with false. Therefore only convert bool if there are no
NA values.
Datetimes should already be converted to np.datetime64 if supported,
but here we also force conversion if required.
"""
parse_dates = _process_parse_dates_argument(parse_dates)
for sql_col in self.table.columns:
col_name = sql_col.name
try:
df_col = self.frame[col_name]
# Handle date parsing upfront; don't try to convert columns
# twice
if col_name in parse_dates:
try:
fmt = parse_dates[col_name]
except TypeError:
fmt = None
self.frame[col_name] = _handle_date_column(
df_col, format=fmt)
continue
# the type the dataframe column should have
col_type = self._get_dtype(sql_col.type)
if (col_type is datetime or col_type is date or
col_type is DatetimeTZDtype):
# Convert tz-aware Datetime SQL columns to UTC
utc = col_type is DatetimeTZDtype
self.frame[col_name] = _handle_date_column(df_col, utc=utc)
elif col_type is float:
# floats support NA, can always convert!
self.frame[col_name] = df_col.astype(col_type, copy=False)
elif len(df_col) == df_col.count():
# No NA values, can convert ints and bools
if col_type is np.dtype('int64') or col_type is bool:
self.frame[col_name] = df_col.astype(
col_type, copy=False)
except KeyError:
pass | def _harmonize_columns(self, parse_dates=None):
"""
Make the DataFrame's column types align with the SQL table
column types.
Need to work around limited NA value support. Floats are always
fine, ints must always be floats if there are Null values.
Booleans are hard because converting bool column with None replaces
all Nones with false. Therefore only convert bool if there are no
NA values.
Datetimes should already be converted to np.datetime64 if supported,
but here we also force conversion if required.
"""
parse_dates = _process_parse_dates_argument(parse_dates)
for sql_col in self.table.columns:
col_name = sql_col.name
try:
df_col = self.frame[col_name]
# Handle date parsing upfront; don't try to convert columns
# twice
if col_name in parse_dates:
try:
fmt = parse_dates[col_name]
except TypeError:
fmt = None
self.frame[col_name] = _handle_date_column(
df_col, format=fmt)
continue
# the type the dataframe column should have
col_type = self._get_dtype(sql_col.type)
if (col_type is datetime or col_type is date or
col_type is DatetimeTZDtype):
# Convert tz-aware Datetime SQL columns to UTC
utc = col_type is DatetimeTZDtype
self.frame[col_name] = _handle_date_column(df_col, utc=utc)
elif col_type is float:
# floats support NA, can always convert!
self.frame[col_name] = df_col.astype(col_type, copy=False)
elif len(df_col) == df_col.count():
# No NA values, can convert ints and bools
if col_type is np.dtype('int64') or col_type is bool:
self.frame[col_name] = df_col.astype(
col_type, copy=False)
except KeyError:
pass | [
"Make",
"the",
"DataFrame",
"s",
"column",
"types",
"align",
"with",
"the",
"SQL",
"table",
"column",
"types",
".",
"Need",
"to",
"work",
"around",
"limited",
"NA",
"value",
"support",
".",
"Floats",
"are",
"always",
"fine",
"ints",
"must",
"always",
"be",
"floats",
"if",
"there",
"are",
"Null",
"values",
".",
"Booleans",
"are",
"hard",
"because",
"converting",
"bool",
"column",
"with",
"None",
"replaces",
"all",
"Nones",
"with",
"false",
".",
"Therefore",
"only",
"convert",
"bool",
"if",
"there",
"are",
"no",
"NA",
"values",
".",
"Datetimes",
"should",
"already",
"be",
"converted",
"to",
"np",
".",
"datetime64",
"if",
"supported",
"but",
"here",
"we",
"also",
"force",
"conversion",
"if",
"required",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L803-L851 | [
"def",
"_harmonize_columns",
"(",
"self",
",",
"parse_dates",
"=",
"None",
")",
":",
"parse_dates",
"=",
"_process_parse_dates_argument",
"(",
"parse_dates",
")",
"for",
"sql_col",
"in",
"self",
".",
"table",
".",
"columns",
":",
"col_name",
"=",
"sql_col",
".",
"name",
"try",
":",
"df_col",
"=",
"self",
".",
"frame",
"[",
"col_name",
"]",
"# Handle date parsing upfront; don't try to convert columns",
"# twice",
"if",
"col_name",
"in",
"parse_dates",
":",
"try",
":",
"fmt",
"=",
"parse_dates",
"[",
"col_name",
"]",
"except",
"TypeError",
":",
"fmt",
"=",
"None",
"self",
".",
"frame",
"[",
"col_name",
"]",
"=",
"_handle_date_column",
"(",
"df_col",
",",
"format",
"=",
"fmt",
")",
"continue",
"# the type the dataframe column should have",
"col_type",
"=",
"self",
".",
"_get_dtype",
"(",
"sql_col",
".",
"type",
")",
"if",
"(",
"col_type",
"is",
"datetime",
"or",
"col_type",
"is",
"date",
"or",
"col_type",
"is",
"DatetimeTZDtype",
")",
":",
"# Convert tz-aware Datetime SQL columns to UTC",
"utc",
"=",
"col_type",
"is",
"DatetimeTZDtype",
"self",
".",
"frame",
"[",
"col_name",
"]",
"=",
"_handle_date_column",
"(",
"df_col",
",",
"utc",
"=",
"utc",
")",
"elif",
"col_type",
"is",
"float",
":",
"# floats support NA, can always convert!",
"self",
".",
"frame",
"[",
"col_name",
"]",
"=",
"df_col",
".",
"astype",
"(",
"col_type",
",",
"copy",
"=",
"False",
")",
"elif",
"len",
"(",
"df_col",
")",
"==",
"df_col",
".",
"count",
"(",
")",
":",
"# No NA values, can convert ints and bools",
"if",
"col_type",
"is",
"np",
".",
"dtype",
"(",
"'int64'",
")",
"or",
"col_type",
"is",
"bool",
":",
"self",
".",
"frame",
"[",
"col_name",
"]",
"=",
"df_col",
".",
"astype",
"(",
"col_type",
",",
"copy",
"=",
"False",
")",
"except",
"KeyError",
":",
"pass"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLDatabase.read_table | Read SQL database table into a DataFrame.
Parameters
----------
table_name : string
Name of SQL table in database.
index_col : string, optional, default: None
Column to set as index.
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects
(like decimal.Decimal) to floating point. This can result in
loss of precision.
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg}``, where the arg corresponds
to the keyword arguments of :func:`pandas.to_datetime`.
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default: None
List of column names to select from SQL table.
schema : string, default None
Name of SQL schema in database to query (if database flavor
supports this). If specified, this overwrites the default
schema of the SQL database object.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number
of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
pandas.read_sql_table
SQLDatabase.read_query | pandas/io/sql.py | def read_table(self, table_name, index_col=None, coerce_float=True,
parse_dates=None, columns=None, schema=None,
chunksize=None):
"""Read SQL database table into a DataFrame.
Parameters
----------
table_name : string
Name of SQL table in database.
index_col : string, optional, default: None
Column to set as index.
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects
(like decimal.Decimal) to floating point. This can result in
loss of precision.
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg}``, where the arg corresponds
to the keyword arguments of :func:`pandas.to_datetime`.
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default: None
List of column names to select from SQL table.
schema : string, default None
Name of SQL schema in database to query (if database flavor
supports this). If specified, this overwrites the default
schema of the SQL database object.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number
of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
pandas.read_sql_table
SQLDatabase.read_query
"""
table = SQLTable(table_name, self, index=index_col, schema=schema)
return table.read(coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns,
chunksize=chunksize) | def read_table(self, table_name, index_col=None, coerce_float=True,
parse_dates=None, columns=None, schema=None,
chunksize=None):
"""Read SQL database table into a DataFrame.
Parameters
----------
table_name : string
Name of SQL table in database.
index_col : string, optional, default: None
Column to set as index.
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects
(like decimal.Decimal) to floating point. This can result in
loss of precision.
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg}``, where the arg corresponds
to the keyword arguments of :func:`pandas.to_datetime`.
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default: None
List of column names to select from SQL table.
schema : string, default None
Name of SQL schema in database to query (if database flavor
supports this). If specified, this overwrites the default
schema of the SQL database object.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number
of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
pandas.read_sql_table
SQLDatabase.read_query
"""
table = SQLTable(table_name, self, index=index_col, schema=schema)
return table.read(coerce_float=coerce_float,
parse_dates=parse_dates, columns=columns,
chunksize=chunksize) | [
"Read",
"SQL",
"database",
"table",
"into",
"a",
"DataFrame",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L982-L1029 | [
"def",
"read_table",
"(",
"self",
",",
"table_name",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"table",
"=",
"SQLTable",
"(",
"table_name",
",",
"self",
",",
"index",
"=",
"index_col",
",",
"schema",
"=",
"schema",
")",
"return",
"table",
".",
"read",
"(",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"columns",
"=",
"columns",
",",
"chunksize",
"=",
"chunksize",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLDatabase._query_iterator | Return generator through chunked result set | pandas/io/sql.py | def _query_iterator(result, chunksize, columns, index_col=None,
coerce_float=True, parse_dates=None):
"""Return generator through chunked result set"""
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
yield _wrap_result(data, columns, index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates) | def _query_iterator(result, chunksize, columns, index_col=None,
coerce_float=True, parse_dates=None):
"""Return generator through chunked result set"""
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
yield _wrap_result(data, columns, index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates) | [
"Return",
"generator",
"through",
"chunked",
"result",
"set"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L1032-L1043 | [
"def",
"_query_iterator",
"(",
"result",
",",
"chunksize",
",",
"columns",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
")",
":",
"while",
"True",
":",
"data",
"=",
"result",
".",
"fetchmany",
"(",
"chunksize",
")",
"if",
"not",
"data",
":",
"break",
"else",
":",
"yield",
"_wrap_result",
"(",
"data",
",",
"columns",
",",
"index_col",
"=",
"index_col",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLDatabase.read_query | Read SQL query into a DataFrame.
Parameters
----------
sql : string
SQL query to be executed.
index_col : string, optional, default: None
Column name to use as index for the returned DataFrame object.
coerce_float : boolean, default True
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict
corresponds to the keyword arguments of
:func:`pandas.to_datetime` Especially useful with databases
without native Datetime support, such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number
of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql | pandas/io/sql.py | def read_query(self, sql, index_col=None, coerce_float=True,
parse_dates=None, params=None, chunksize=None):
"""Read SQL query into a DataFrame.
Parameters
----------
sql : string
SQL query to be executed.
index_col : string, optional, default: None
Column name to use as index for the returned DataFrame object.
coerce_float : boolean, default True
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict
corresponds to the keyword arguments of
:func:`pandas.to_datetime` Especially useful with databases
without native Datetime support, such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number
of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql
"""
args = _convert_params(sql, params)
result = self.execute(*args)
columns = result.keys()
if chunksize is not None:
return self._query_iterator(result, chunksize, columns,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates)
else:
data = result.fetchall()
frame = _wrap_result(data, columns, index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates)
return frame | def read_query(self, sql, index_col=None, coerce_float=True,
parse_dates=None, params=None, chunksize=None):
"""Read SQL query into a DataFrame.
Parameters
----------
sql : string
SQL query to be executed.
index_col : string, optional, default: None
Column name to use as index for the returned DataFrame object.
coerce_float : boolean, default True
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict
corresponds to the keyword arguments of
:func:`pandas.to_datetime` Especially useful with databases
without native Datetime support, such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number
of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql
"""
args = _convert_params(sql, params)
result = self.execute(*args)
columns = result.keys()
if chunksize is not None:
return self._query_iterator(result, chunksize, columns,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates)
else:
data = result.fetchall()
frame = _wrap_result(data, columns, index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates)
return frame | [
"Read",
"SQL",
"query",
"into",
"a",
"DataFrame",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L1045-L1102 | [
"def",
"read_query",
"(",
"self",
",",
"sql",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
",",
"params",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"args",
"=",
"_convert_params",
"(",
"sql",
",",
"params",
")",
"result",
"=",
"self",
".",
"execute",
"(",
"*",
"args",
")",
"columns",
"=",
"result",
".",
"keys",
"(",
")",
"if",
"chunksize",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_query_iterator",
"(",
"result",
",",
"chunksize",
",",
"columns",
",",
"index_col",
"=",
"index_col",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
")",
"else",
":",
"data",
"=",
"result",
".",
"fetchall",
"(",
")",
"frame",
"=",
"_wrap_result",
"(",
"data",
",",
"columns",
",",
"index_col",
"=",
"index_col",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
")",
"return",
"frame"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLDatabase.to_sql | Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame
name : string
Name of SQL table.
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
schema : string, default None
Name of SQL schema in database to write to (if database flavor
supports this). If specified, this overwrites the default
schema of the SQLDatabase object.
chunksize : int, default None
If not None, then rows will be written in batches of this size at a
time. If None, all rows will be written at once.
dtype : single type or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type. If all columns are of the same type, one
single value can be used.
method : {None', 'multi', callable}, default None
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0 | pandas/io/sql.py | def to_sql(self, frame, name, if_exists='fail', index=True,
index_label=None, schema=None, chunksize=None, dtype=None,
method=None):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame
name : string
Name of SQL table.
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
schema : string, default None
Name of SQL schema in database to write to (if database flavor
supports this). If specified, this overwrites the default
schema of the SQLDatabase object.
chunksize : int, default None
If not None, then rows will be written in batches of this size at a
time. If None, all rows will be written at once.
dtype : single type or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type. If all columns are of the same type, one
single value can be used.
method : {None', 'multi', callable}, default None
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if dtype and not is_dict_like(dtype):
dtype = {col_name: dtype for col_name in frame}
if dtype is not None:
from sqlalchemy.types import to_instance, TypeEngine
for col, my_type in dtype.items():
if not isinstance(to_instance(my_type), TypeEngine):
raise ValueError('The type of {column} is not a '
'SQLAlchemy type '.format(column=col))
table = SQLTable(name, self, frame=frame, index=index,
if_exists=if_exists, index_label=index_label,
schema=schema, dtype=dtype)
table.create()
table.insert(chunksize, method=method)
if (not name.isdigit() and not name.islower()):
# check for potentially case sensitivity issues (GH7815)
# Only check when name is not a number and name is not lower case
engine = self.connectable.engine
with self.connectable.connect() as conn:
table_names = engine.table_names(
schema=schema or self.meta.schema,
connection=conn,
)
if name not in table_names:
msg = (
"The provided table name '{0}' is not found exactly as "
"such in the database after writing the table, possibly "
"due to case sensitivity issues. Consider using lower "
"case table names."
).format(name)
warnings.warn(msg, UserWarning) | def to_sql(self, frame, name, if_exists='fail', index=True,
index_label=None, schema=None, chunksize=None, dtype=None,
method=None):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame
name : string
Name of SQL table.
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
schema : string, default None
Name of SQL schema in database to write to (if database flavor
supports this). If specified, this overwrites the default
schema of the SQLDatabase object.
chunksize : int, default None
If not None, then rows will be written in batches of this size at a
time. If None, all rows will be written at once.
dtype : single type or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type. If all columns are of the same type, one
single value can be used.
method : {None', 'multi', callable}, default None
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if dtype and not is_dict_like(dtype):
dtype = {col_name: dtype for col_name in frame}
if dtype is not None:
from sqlalchemy.types import to_instance, TypeEngine
for col, my_type in dtype.items():
if not isinstance(to_instance(my_type), TypeEngine):
raise ValueError('The type of {column} is not a '
'SQLAlchemy type '.format(column=col))
table = SQLTable(name, self, frame=frame, index=index,
if_exists=if_exists, index_label=index_label,
schema=schema, dtype=dtype)
table.create()
table.insert(chunksize, method=method)
if (not name.isdigit() and not name.islower()):
# check for potentially case sensitivity issues (GH7815)
# Only check when name is not a number and name is not lower case
engine = self.connectable.engine
with self.connectable.connect() as conn:
table_names = engine.table_names(
schema=schema or self.meta.schema,
connection=conn,
)
if name not in table_names:
msg = (
"The provided table name '{0}' is not found exactly as "
"such in the database after writing the table, possibly "
"due to case sensitivity issues. Consider using lower "
"case table names."
).format(name)
warnings.warn(msg, UserWarning) | [
"Write",
"records",
"stored",
"in",
"a",
"DataFrame",
"to",
"a",
"SQL",
"database",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L1106-L1181 | [
"def",
"to_sql",
"(",
"self",
",",
"frame",
",",
"name",
",",
"if_exists",
"=",
"'fail'",
",",
"index",
"=",
"True",
",",
"index_label",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"if",
"dtype",
"and",
"not",
"is_dict_like",
"(",
"dtype",
")",
":",
"dtype",
"=",
"{",
"col_name",
":",
"dtype",
"for",
"col_name",
"in",
"frame",
"}",
"if",
"dtype",
"is",
"not",
"None",
":",
"from",
"sqlalchemy",
".",
"types",
"import",
"to_instance",
",",
"TypeEngine",
"for",
"col",
",",
"my_type",
"in",
"dtype",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"to_instance",
"(",
"my_type",
")",
",",
"TypeEngine",
")",
":",
"raise",
"ValueError",
"(",
"'The type of {column} is not a '",
"'SQLAlchemy type '",
".",
"format",
"(",
"column",
"=",
"col",
")",
")",
"table",
"=",
"SQLTable",
"(",
"name",
",",
"self",
",",
"frame",
"=",
"frame",
",",
"index",
"=",
"index",
",",
"if_exists",
"=",
"if_exists",
",",
"index_label",
"=",
"index_label",
",",
"schema",
"=",
"schema",
",",
"dtype",
"=",
"dtype",
")",
"table",
".",
"create",
"(",
")",
"table",
".",
"insert",
"(",
"chunksize",
",",
"method",
"=",
"method",
")",
"if",
"(",
"not",
"name",
".",
"isdigit",
"(",
")",
"and",
"not",
"name",
".",
"islower",
"(",
")",
")",
":",
"# check for potentially case sensitivity issues (GH7815)",
"# Only check when name is not a number and name is not lower case",
"engine",
"=",
"self",
".",
"connectable",
".",
"engine",
"with",
"self",
".",
"connectable",
".",
"connect",
"(",
")",
"as",
"conn",
":",
"table_names",
"=",
"engine",
".",
"table_names",
"(",
"schema",
"=",
"schema",
"or",
"self",
".",
"meta",
".",
"schema",
",",
"connection",
"=",
"conn",
",",
")",
"if",
"name",
"not",
"in",
"table_names",
":",
"msg",
"=",
"(",
"\"The provided table name '{0}' is not found exactly as \"",
"\"such in the database after writing the table, possibly \"",
"\"due to case sensitivity issues. Consider using lower \"",
"\"case table names.\"",
")",
".",
"format",
"(",
"name",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"UserWarning",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLiteTable._create_table_setup | Return a list of SQL statements that creates a table reflecting the
structure of a DataFrame. The first entry will be a CREATE TABLE
statement while the rest will be CREATE INDEX statements. | pandas/io/sql.py | def _create_table_setup(self):
"""
Return a list of SQL statements that creates a table reflecting the
structure of a DataFrame. The first entry will be a CREATE TABLE
statement while the rest will be CREATE INDEX statements.
"""
column_names_and_types = self._get_column_names_and_types(
self._sql_type_name
)
pat = re.compile(r'\s+')
column_names = [col_name for col_name, _, _ in column_names_and_types]
if any(map(pat.search, column_names)):
warnings.warn(_SAFE_NAMES_WARNING, stacklevel=6)
escape = _get_valid_sqlite_name
create_tbl_stmts = [escape(cname) + ' ' + ctype
for cname, ctype, _ in column_names_and_types]
if self.keys is not None and len(self.keys):
if not is_list_like(self.keys):
keys = [self.keys]
else:
keys = self.keys
cnames_br = ", ".join(escape(c) for c in keys)
create_tbl_stmts.append(
"CONSTRAINT {tbl}_pk PRIMARY KEY ({cnames_br})".format(
tbl=self.name, cnames_br=cnames_br))
create_stmts = ["CREATE TABLE " + escape(self.name) + " (\n" +
',\n '.join(create_tbl_stmts) + "\n)"]
ix_cols = [cname for cname, _, is_index in column_names_and_types
if is_index]
if len(ix_cols):
cnames = "_".join(ix_cols)
cnames_br = ",".join(escape(c) for c in ix_cols)
create_stmts.append(
"CREATE INDEX " + escape("ix_" + self.name + "_" + cnames) +
"ON " + escape(self.name) + " (" + cnames_br + ")")
return create_stmts | def _create_table_setup(self):
"""
Return a list of SQL statements that creates a table reflecting the
structure of a DataFrame. The first entry will be a CREATE TABLE
statement while the rest will be CREATE INDEX statements.
"""
column_names_and_types = self._get_column_names_and_types(
self._sql_type_name
)
pat = re.compile(r'\s+')
column_names = [col_name for col_name, _, _ in column_names_and_types]
if any(map(pat.search, column_names)):
warnings.warn(_SAFE_NAMES_WARNING, stacklevel=6)
escape = _get_valid_sqlite_name
create_tbl_stmts = [escape(cname) + ' ' + ctype
for cname, ctype, _ in column_names_and_types]
if self.keys is not None and len(self.keys):
if not is_list_like(self.keys):
keys = [self.keys]
else:
keys = self.keys
cnames_br = ", ".join(escape(c) for c in keys)
create_tbl_stmts.append(
"CONSTRAINT {tbl}_pk PRIMARY KEY ({cnames_br})".format(
tbl=self.name, cnames_br=cnames_br))
create_stmts = ["CREATE TABLE " + escape(self.name) + " (\n" +
',\n '.join(create_tbl_stmts) + "\n)"]
ix_cols = [cname for cname, _, is_index in column_names_and_types
if is_index]
if len(ix_cols):
cnames = "_".join(ix_cols)
cnames_br = ",".join(escape(c) for c in ix_cols)
create_stmts.append(
"CREATE INDEX " + escape("ix_" + self.name + "_" + cnames) +
"ON " + escape(self.name) + " (" + cnames_br + ")")
return create_stmts | [
"Return",
"a",
"list",
"of",
"SQL",
"statements",
"that",
"creates",
"a",
"table",
"reflecting",
"the",
"structure",
"of",
"a",
"DataFrame",
".",
"The",
"first",
"entry",
"will",
"be",
"a",
"CREATE",
"TABLE",
"statement",
"while",
"the",
"rest",
"will",
"be",
"CREATE",
"INDEX",
"statements",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L1311-L1353 | [
"def",
"_create_table_setup",
"(",
"self",
")",
":",
"column_names_and_types",
"=",
"self",
".",
"_get_column_names_and_types",
"(",
"self",
".",
"_sql_type_name",
")",
"pat",
"=",
"re",
".",
"compile",
"(",
"r'\\s+'",
")",
"column_names",
"=",
"[",
"col_name",
"for",
"col_name",
",",
"_",
",",
"_",
"in",
"column_names_and_types",
"]",
"if",
"any",
"(",
"map",
"(",
"pat",
".",
"search",
",",
"column_names",
")",
")",
":",
"warnings",
".",
"warn",
"(",
"_SAFE_NAMES_WARNING",
",",
"stacklevel",
"=",
"6",
")",
"escape",
"=",
"_get_valid_sqlite_name",
"create_tbl_stmts",
"=",
"[",
"escape",
"(",
"cname",
")",
"+",
"' '",
"+",
"ctype",
"for",
"cname",
",",
"ctype",
",",
"_",
"in",
"column_names_and_types",
"]",
"if",
"self",
".",
"keys",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"keys",
")",
":",
"if",
"not",
"is_list_like",
"(",
"self",
".",
"keys",
")",
":",
"keys",
"=",
"[",
"self",
".",
"keys",
"]",
"else",
":",
"keys",
"=",
"self",
".",
"keys",
"cnames_br",
"=",
"\", \"",
".",
"join",
"(",
"escape",
"(",
"c",
")",
"for",
"c",
"in",
"keys",
")",
"create_tbl_stmts",
".",
"append",
"(",
"\"CONSTRAINT {tbl}_pk PRIMARY KEY ({cnames_br})\"",
".",
"format",
"(",
"tbl",
"=",
"self",
".",
"name",
",",
"cnames_br",
"=",
"cnames_br",
")",
")",
"create_stmts",
"=",
"[",
"\"CREATE TABLE \"",
"+",
"escape",
"(",
"self",
".",
"name",
")",
"+",
"\" (\\n\"",
"+",
"',\\n '",
".",
"join",
"(",
"create_tbl_stmts",
")",
"+",
"\"\\n)\"",
"]",
"ix_cols",
"=",
"[",
"cname",
"for",
"cname",
",",
"_",
",",
"is_index",
"in",
"column_names_and_types",
"if",
"is_index",
"]",
"if",
"len",
"(",
"ix_cols",
")",
":",
"cnames",
"=",
"\"_\"",
".",
"join",
"(",
"ix_cols",
")",
"cnames_br",
"=",
"\",\"",
".",
"join",
"(",
"escape",
"(",
"c",
")",
"for",
"c",
"in",
"ix_cols",
")",
"create_stmts",
".",
"append",
"(",
"\"CREATE INDEX \"",
"+",
"escape",
"(",
"\"ix_\"",
"+",
"self",
".",
"name",
"+",
"\"_\"",
"+",
"cnames",
")",
"+",
"\"ON \"",
"+",
"escape",
"(",
"self",
".",
"name",
")",
"+",
"\" (\"",
"+",
"cnames_br",
"+",
"\")\"",
")",
"return",
"create_stmts"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLiteDatabase._query_iterator | Return generator through chunked result set | pandas/io/sql.py | def _query_iterator(cursor, chunksize, columns, index_col=None,
coerce_float=True, parse_dates=None):
"""Return generator through chunked result set"""
while True:
data = cursor.fetchmany(chunksize)
if type(data) == tuple:
data = list(data)
if not data:
cursor.close()
break
else:
yield _wrap_result(data, columns, index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates) | def _query_iterator(cursor, chunksize, columns, index_col=None,
coerce_float=True, parse_dates=None):
"""Return generator through chunked result set"""
while True:
data = cursor.fetchmany(chunksize)
if type(data) == tuple:
data = list(data)
if not data:
cursor.close()
break
else:
yield _wrap_result(data, columns, index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates) | [
"Return",
"generator",
"through",
"chunked",
"result",
"set"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L1438-L1452 | [
"def",
"_query_iterator",
"(",
"cursor",
",",
"chunksize",
",",
"columns",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
")",
":",
"while",
"True",
":",
"data",
"=",
"cursor",
".",
"fetchmany",
"(",
"chunksize",
")",
"if",
"type",
"(",
"data",
")",
"==",
"tuple",
":",
"data",
"=",
"list",
"(",
"data",
")",
"if",
"not",
"data",
":",
"cursor",
".",
"close",
"(",
")",
"break",
"else",
":",
"yield",
"_wrap_result",
"(",
"data",
",",
"columns",
",",
"index_col",
"=",
"index_col",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | SQLiteDatabase.to_sql | Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame: DataFrame
name: string
Name of SQL table.
if_exists: {'fail', 'replace', 'append'}, default 'fail'
fail: If table exists, do nothing.
replace: If table exists, drop it, recreate it, and insert data.
append: If table exists, insert data. Create if it does not exist.
index : boolean, default True
Write DataFrame index as a column
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
schema : string, default None
Ignored parameter included for compatibility with SQLAlchemy
version of ``to_sql``.
chunksize : int, default None
If not None, then rows will be written in batches of this
size at a time. If None, all rows will be written at once.
dtype : single type or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a string. If all columns are of the same type, one single value
can be used.
method : {None, 'multi', callable}, default None
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0 | pandas/io/sql.py | def to_sql(self, frame, name, if_exists='fail', index=True,
index_label=None, schema=None, chunksize=None, dtype=None,
method=None):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame: DataFrame
name: string
Name of SQL table.
if_exists: {'fail', 'replace', 'append'}, default 'fail'
fail: If table exists, do nothing.
replace: If table exists, drop it, recreate it, and insert data.
append: If table exists, insert data. Create if it does not exist.
index : boolean, default True
Write DataFrame index as a column
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
schema : string, default None
Ignored parameter included for compatibility with SQLAlchemy
version of ``to_sql``.
chunksize : int, default None
If not None, then rows will be written in batches of this
size at a time. If None, all rows will be written at once.
dtype : single type or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a string. If all columns are of the same type, one single value
can be used.
method : {None, 'multi', callable}, default None
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if dtype and not is_dict_like(dtype):
dtype = {col_name: dtype for col_name in frame}
if dtype is not None:
for col, my_type in dtype.items():
if not isinstance(my_type, str):
raise ValueError('{column} ({type!s}) not a string'.format(
column=col, type=my_type))
table = SQLiteTable(name, self, frame=frame, index=index,
if_exists=if_exists, index_label=index_label,
dtype=dtype)
table.create()
table.insert(chunksize, method) | def to_sql(self, frame, name, if_exists='fail', index=True,
index_label=None, schema=None, chunksize=None, dtype=None,
method=None):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame: DataFrame
name: string
Name of SQL table.
if_exists: {'fail', 'replace', 'append'}, default 'fail'
fail: If table exists, do nothing.
replace: If table exists, drop it, recreate it, and insert data.
append: If table exists, insert data. Create if it does not exist.
index : boolean, default True
Write DataFrame index as a column
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
schema : string, default None
Ignored parameter included for compatibility with SQLAlchemy
version of ``to_sql``.
chunksize : int, default None
If not None, then rows will be written in batches of this
size at a time. If None, all rows will be written at once.
dtype : single type or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a string. If all columns are of the same type, one single value
can be used.
method : {None, 'multi', callable}, default None
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if dtype and not is_dict_like(dtype):
dtype = {col_name: dtype for col_name in frame}
if dtype is not None:
for col, my_type in dtype.items():
if not isinstance(my_type, str):
raise ValueError('{column} ({type!s}) not a string'.format(
column=col, type=my_type))
table = SQLiteTable(name, self, frame=frame, index=index,
if_exists=if_exists, index_label=index_label,
dtype=dtype)
table.create()
table.insert(chunksize, method) | [
"Write",
"records",
"stored",
"in",
"a",
"DataFrame",
"to",
"a",
"SQL",
"database",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L1481-L1537 | [
"def",
"to_sql",
"(",
"self",
",",
"frame",
",",
"name",
",",
"if_exists",
"=",
"'fail'",
",",
"index",
"=",
"True",
",",
"index_label",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"if",
"dtype",
"and",
"not",
"is_dict_like",
"(",
"dtype",
")",
":",
"dtype",
"=",
"{",
"col_name",
":",
"dtype",
"for",
"col_name",
"in",
"frame",
"}",
"if",
"dtype",
"is",
"not",
"None",
":",
"for",
"col",
",",
"my_type",
"in",
"dtype",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"my_type",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"'{column} ({type!s}) not a string'",
".",
"format",
"(",
"column",
"=",
"col",
",",
"type",
"=",
"my_type",
")",
")",
"table",
"=",
"SQLiteTable",
"(",
"name",
",",
"self",
",",
"frame",
"=",
"frame",
",",
"index",
"=",
"index",
",",
"if_exists",
"=",
"if_exists",
",",
"index_label",
"=",
"index_label",
",",
"dtype",
"=",
"dtype",
")",
"table",
".",
"create",
"(",
")",
"table",
".",
"insert",
"(",
"chunksize",
",",
"method",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _maybe_to_categorical | Coerce to a categorical if a series is given.
Internal use ONLY. | pandas/core/arrays/categorical.py | def _maybe_to_categorical(array):
"""
Coerce to a categorical if a series is given.
Internal use ONLY.
"""
if isinstance(array, (ABCSeries, ABCCategoricalIndex)):
return array._values
elif isinstance(array, np.ndarray):
return Categorical(array)
return array | def _maybe_to_categorical(array):
"""
Coerce to a categorical if a series is given.
Internal use ONLY.
"""
if isinstance(array, (ABCSeries, ABCCategoricalIndex)):
return array._values
elif isinstance(array, np.ndarray):
return Categorical(array)
return array | [
"Coerce",
"to",
"a",
"categorical",
"if",
"a",
"series",
"is",
"given",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L131-L141 | [
"def",
"_maybe_to_categorical",
"(",
"array",
")",
":",
"if",
"isinstance",
"(",
"array",
",",
"(",
"ABCSeries",
",",
"ABCCategoricalIndex",
")",
")",
":",
"return",
"array",
".",
"_values",
"elif",
"isinstance",
"(",
"array",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"Categorical",
"(",
"array",
")",
"return",
"array"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | contains | Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``container``.
Parameters
----------
cat : :class:`Categorical`or :class:`categoricalIndex`
key : a hashable object
The key to check membership for.
container : Container (e.g. list-like or mapping)
The container to check for membership in.
Returns
-------
is_in : bool
True if ``key`` is in ``self.categories`` and location of
``key`` in ``categories`` is in ``container``, else False.
Notes
-----
This method does not check for NaN values. Do that separately
before calling this method. | pandas/core/arrays/categorical.py | def contains(cat, key, container):
"""
Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``container``.
Parameters
----------
cat : :class:`Categorical`or :class:`categoricalIndex`
key : a hashable object
The key to check membership for.
container : Container (e.g. list-like or mapping)
The container to check for membership in.
Returns
-------
is_in : bool
True if ``key`` is in ``self.categories`` and location of
``key`` in ``categories`` is in ``container``, else False.
Notes
-----
This method does not check for NaN values. Do that separately
before calling this method.
"""
hash(key)
# get location of key in categories.
# If a KeyError, the key isn't in categories, so logically
# can't be in container either.
try:
loc = cat.categories.get_loc(key)
except KeyError:
return False
# loc is the location of key in categories, but also the *value*
# for key in container. So, `key` may be in categories,
# but still not in `container`. Example ('b' in categories,
# but not in values):
# 'b' in Categorical(['a'], categories=['a', 'b']) # False
if is_scalar(loc):
return loc in container
else:
# if categories is an IntervalIndex, loc is an array.
return any(loc_ in container for loc_ in loc) | def contains(cat, key, container):
"""
Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``container``.
Parameters
----------
cat : :class:`Categorical`or :class:`categoricalIndex`
key : a hashable object
The key to check membership for.
container : Container (e.g. list-like or mapping)
The container to check for membership in.
Returns
-------
is_in : bool
True if ``key`` is in ``self.categories`` and location of
``key`` in ``categories`` is in ``container``, else False.
Notes
-----
This method does not check for NaN values. Do that separately
before calling this method.
"""
hash(key)
# get location of key in categories.
# If a KeyError, the key isn't in categories, so logically
# can't be in container either.
try:
loc = cat.categories.get_loc(key)
except KeyError:
return False
# loc is the location of key in categories, but also the *value*
# for key in container. So, `key` may be in categories,
# but still not in `container`. Example ('b' in categories,
# but not in values):
# 'b' in Categorical(['a'], categories=['a', 'b']) # False
if is_scalar(loc):
return loc in container
else:
# if categories is an IntervalIndex, loc is an array.
return any(loc_ in container for loc_ in loc) | [
"Helper",
"for",
"membership",
"check",
"for",
"key",
"in",
"cat",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L144-L192 | [
"def",
"contains",
"(",
"cat",
",",
"key",
",",
"container",
")",
":",
"hash",
"(",
"key",
")",
"# get location of key in categories.",
"# If a KeyError, the key isn't in categories, so logically",
"# can't be in container either.",
"try",
":",
"loc",
"=",
"cat",
".",
"categories",
".",
"get_loc",
"(",
"key",
")",
"except",
"KeyError",
":",
"return",
"False",
"# loc is the location of key in categories, but also the *value*",
"# for key in container. So, `key` may be in categories,",
"# but still not in `container`. Example ('b' in categories,",
"# but not in values):",
"# 'b' in Categorical(['a'], categories=['a', 'b']) # False",
"if",
"is_scalar",
"(",
"loc",
")",
":",
"return",
"loc",
"in",
"container",
"else",
":",
"# if categories is an IntervalIndex, loc is an array.",
"return",
"any",
"(",
"loc_",
"in",
"container",
"for",
"loc_",
"in",
"loc",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _get_codes_for_values | utility routine to turn values into codes given the specified categories | pandas/core/arrays/categorical.py | def _get_codes_for_values(values, categories):
"""
utility routine to turn values into codes given the specified categories
"""
from pandas.core.algorithms import _get_data_algo, _hashtables
dtype_equal = is_dtype_equal(values.dtype, categories.dtype)
if dtype_equal:
# To prevent erroneous dtype coercion in _get_data_algo, retrieve
# the underlying numpy array. gh-22702
values = getattr(values, '_ndarray_values', values)
categories = getattr(categories, '_ndarray_values', categories)
elif (is_extension_array_dtype(categories.dtype) and
is_object_dtype(values)):
# Support inferring the correct extension dtype from an array of
# scalar objects. e.g.
# Categorical(array[Period, Period], categories=PeriodIndex(...))
try:
values = (
categories.dtype.construct_array_type()._from_sequence(values)
)
except Exception:
# but that may fail for any reason, so fall back to object
values = ensure_object(values)
categories = ensure_object(categories)
else:
values = ensure_object(values)
categories = ensure_object(categories)
(hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables)
(_, _), cats = _get_data_algo(categories, _hashtables)
t = hash_klass(len(cats))
t.map_locations(cats)
return coerce_indexer_dtype(t.lookup(vals), cats) | def _get_codes_for_values(values, categories):
"""
utility routine to turn values into codes given the specified categories
"""
from pandas.core.algorithms import _get_data_algo, _hashtables
dtype_equal = is_dtype_equal(values.dtype, categories.dtype)
if dtype_equal:
# To prevent erroneous dtype coercion in _get_data_algo, retrieve
# the underlying numpy array. gh-22702
values = getattr(values, '_ndarray_values', values)
categories = getattr(categories, '_ndarray_values', categories)
elif (is_extension_array_dtype(categories.dtype) and
is_object_dtype(values)):
# Support inferring the correct extension dtype from an array of
# scalar objects. e.g.
# Categorical(array[Period, Period], categories=PeriodIndex(...))
try:
values = (
categories.dtype.construct_array_type()._from_sequence(values)
)
except Exception:
# but that may fail for any reason, so fall back to object
values = ensure_object(values)
categories = ensure_object(categories)
else:
values = ensure_object(values)
categories = ensure_object(categories)
(hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables)
(_, _), cats = _get_data_algo(categories, _hashtables)
t = hash_klass(len(cats))
t.map_locations(cats)
return coerce_indexer_dtype(t.lookup(vals), cats) | [
"utility",
"routine",
"to",
"turn",
"values",
"into",
"codes",
"given",
"the",
"specified",
"categories"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2549-L2582 | [
"def",
"_get_codes_for_values",
"(",
"values",
",",
"categories",
")",
":",
"from",
"pandas",
".",
"core",
".",
"algorithms",
"import",
"_get_data_algo",
",",
"_hashtables",
"dtype_equal",
"=",
"is_dtype_equal",
"(",
"values",
".",
"dtype",
",",
"categories",
".",
"dtype",
")",
"if",
"dtype_equal",
":",
"# To prevent erroneous dtype coercion in _get_data_algo, retrieve",
"# the underlying numpy array. gh-22702",
"values",
"=",
"getattr",
"(",
"values",
",",
"'_ndarray_values'",
",",
"values",
")",
"categories",
"=",
"getattr",
"(",
"categories",
",",
"'_ndarray_values'",
",",
"categories",
")",
"elif",
"(",
"is_extension_array_dtype",
"(",
"categories",
".",
"dtype",
")",
"and",
"is_object_dtype",
"(",
"values",
")",
")",
":",
"# Support inferring the correct extension dtype from an array of",
"# scalar objects. e.g.",
"# Categorical(array[Period, Period], categories=PeriodIndex(...))",
"try",
":",
"values",
"=",
"(",
"categories",
".",
"dtype",
".",
"construct_array_type",
"(",
")",
".",
"_from_sequence",
"(",
"values",
")",
")",
"except",
"Exception",
":",
"# but that may fail for any reason, so fall back to object",
"values",
"=",
"ensure_object",
"(",
"values",
")",
"categories",
"=",
"ensure_object",
"(",
"categories",
")",
"else",
":",
"values",
"=",
"ensure_object",
"(",
"values",
")",
"categories",
"=",
"ensure_object",
"(",
"categories",
")",
"(",
"hash_klass",
",",
"vec_klass",
")",
",",
"vals",
"=",
"_get_data_algo",
"(",
"values",
",",
"_hashtables",
")",
"(",
"_",
",",
"_",
")",
",",
"cats",
"=",
"_get_data_algo",
"(",
"categories",
",",
"_hashtables",
")",
"t",
"=",
"hash_klass",
"(",
"len",
"(",
"cats",
")",
")",
"t",
".",
"map_locations",
"(",
"cats",
")",
"return",
"coerce_indexer_dtype",
"(",
"t",
".",
"lookup",
"(",
"vals",
")",
",",
"cats",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _recode_for_categories | Convert a set of codes for to a new set of categories
Parameters
----------
codes : array
old_categories, new_categories : Index
Returns
-------
new_codes : array
Examples
--------
>>> old_cat = pd.Index(['b', 'a', 'c'])
>>> new_cat = pd.Index(['a', 'b'])
>>> codes = np.array([0, 1, 1, 2])
>>> _recode_for_categories(codes, old_cat, new_cat)
array([ 1, 0, 0, -1]) | pandas/core/arrays/categorical.py | def _recode_for_categories(codes, old_categories, new_categories):
"""
Convert a set of codes for to a new set of categories
Parameters
----------
codes : array
old_categories, new_categories : Index
Returns
-------
new_codes : array
Examples
--------
>>> old_cat = pd.Index(['b', 'a', 'c'])
>>> new_cat = pd.Index(['a', 'b'])
>>> codes = np.array([0, 1, 1, 2])
>>> _recode_for_categories(codes, old_cat, new_cat)
array([ 1, 0, 0, -1])
"""
from pandas.core.algorithms import take_1d
if len(old_categories) == 0:
# All null anyway, so just retain the nulls
return codes.copy()
elif new_categories.equals(old_categories):
# Same categories, so no need to actually recode
return codes.copy()
indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories),
new_categories)
new_codes = take_1d(indexer, codes.copy(), fill_value=-1)
return new_codes | def _recode_for_categories(codes, old_categories, new_categories):
"""
Convert a set of codes for to a new set of categories
Parameters
----------
codes : array
old_categories, new_categories : Index
Returns
-------
new_codes : array
Examples
--------
>>> old_cat = pd.Index(['b', 'a', 'c'])
>>> new_cat = pd.Index(['a', 'b'])
>>> codes = np.array([0, 1, 1, 2])
>>> _recode_for_categories(codes, old_cat, new_cat)
array([ 1, 0, 0, -1])
"""
from pandas.core.algorithms import take_1d
if len(old_categories) == 0:
# All null anyway, so just retain the nulls
return codes.copy()
elif new_categories.equals(old_categories):
# Same categories, so no need to actually recode
return codes.copy()
indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories),
new_categories)
new_codes = take_1d(indexer, codes.copy(), fill_value=-1)
return new_codes | [
"Convert",
"a",
"set",
"of",
"codes",
"for",
"to",
"a",
"new",
"set",
"of",
"categories"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2585-L2617 | [
"def",
"_recode_for_categories",
"(",
"codes",
",",
"old_categories",
",",
"new_categories",
")",
":",
"from",
"pandas",
".",
"core",
".",
"algorithms",
"import",
"take_1d",
"if",
"len",
"(",
"old_categories",
")",
"==",
"0",
":",
"# All null anyway, so just retain the nulls",
"return",
"codes",
".",
"copy",
"(",
")",
"elif",
"new_categories",
".",
"equals",
"(",
"old_categories",
")",
":",
"# Same categories, so no need to actually recode",
"return",
"codes",
".",
"copy",
"(",
")",
"indexer",
"=",
"coerce_indexer_dtype",
"(",
"new_categories",
".",
"get_indexer",
"(",
"old_categories",
")",
",",
"new_categories",
")",
"new_codes",
"=",
"take_1d",
"(",
"indexer",
",",
"codes",
".",
"copy",
"(",
")",
",",
"fill_value",
"=",
"-",
"1",
")",
"return",
"new_codes"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _factorize_from_iterable | Factorize an input `values` into `categories` and `codes`. Preserves
categorical dtype in `categories`.
*This is an internal function*
Parameters
----------
values : list-like
Returns
-------
codes : ndarray
categories : Index
If `values` has a categorical dtype, then `categories` is
a CategoricalIndex keeping the categories and order of `values`. | pandas/core/arrays/categorical.py | def _factorize_from_iterable(values):
"""
Factorize an input `values` into `categories` and `codes`. Preserves
categorical dtype in `categories`.
*This is an internal function*
Parameters
----------
values : list-like
Returns
-------
codes : ndarray
categories : Index
If `values` has a categorical dtype, then `categories` is
a CategoricalIndex keeping the categories and order of `values`.
"""
from pandas.core.indexes.category import CategoricalIndex
if not is_list_like(values):
raise TypeError("Input must be list-like")
if is_categorical(values):
if isinstance(values, (ABCCategoricalIndex, ABCSeries)):
values = values._values
categories = CategoricalIndex(values.categories, dtype=values.dtype)
codes = values.codes
else:
# The value of ordered is irrelevant since we don't use cat as such,
# but only the resulting categories, the order of which is independent
# from ordered. Set ordered to False as default. See GH #15457
cat = Categorical(values, ordered=False)
categories = cat.categories
codes = cat.codes
return codes, categories | def _factorize_from_iterable(values):
"""
Factorize an input `values` into `categories` and `codes`. Preserves
categorical dtype in `categories`.
*This is an internal function*
Parameters
----------
values : list-like
Returns
-------
codes : ndarray
categories : Index
If `values` has a categorical dtype, then `categories` is
a CategoricalIndex keeping the categories and order of `values`.
"""
from pandas.core.indexes.category import CategoricalIndex
if not is_list_like(values):
raise TypeError("Input must be list-like")
if is_categorical(values):
if isinstance(values, (ABCCategoricalIndex, ABCSeries)):
values = values._values
categories = CategoricalIndex(values.categories, dtype=values.dtype)
codes = values.codes
else:
# The value of ordered is irrelevant since we don't use cat as such,
# but only the resulting categories, the order of which is independent
# from ordered. Set ordered to False as default. See GH #15457
cat = Categorical(values, ordered=False)
categories = cat.categories
codes = cat.codes
return codes, categories | [
"Factorize",
"an",
"input",
"values",
"into",
"categories",
"and",
"codes",
".",
"Preserves",
"categorical",
"dtype",
"in",
"categories",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2635-L2670 | [
"def",
"_factorize_from_iterable",
"(",
"values",
")",
":",
"from",
"pandas",
".",
"core",
".",
"indexes",
".",
"category",
"import",
"CategoricalIndex",
"if",
"not",
"is_list_like",
"(",
"values",
")",
":",
"raise",
"TypeError",
"(",
"\"Input must be list-like\"",
")",
"if",
"is_categorical",
"(",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"(",
"ABCCategoricalIndex",
",",
"ABCSeries",
")",
")",
":",
"values",
"=",
"values",
".",
"_values",
"categories",
"=",
"CategoricalIndex",
"(",
"values",
".",
"categories",
",",
"dtype",
"=",
"values",
".",
"dtype",
")",
"codes",
"=",
"values",
".",
"codes",
"else",
":",
"# The value of ordered is irrelevant since we don't use cat as such,",
"# but only the resulting categories, the order of which is independent",
"# from ordered. Set ordered to False as default. See GH #15457",
"cat",
"=",
"Categorical",
"(",
"values",
",",
"ordered",
"=",
"False",
")",
"categories",
"=",
"cat",
".",
"categories",
"codes",
"=",
"cat",
".",
"codes",
"return",
"codes",
",",
"categories"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _factorize_from_iterables | A higher-level wrapper over `_factorize_from_iterable`.
*This is an internal function*
Parameters
----------
iterables : list-like of list-likes
Returns
-------
codes_list : list of ndarrays
categories_list : list of Indexes
Notes
-----
See `_factorize_from_iterable` for more info. | pandas/core/arrays/categorical.py | def _factorize_from_iterables(iterables):
"""
A higher-level wrapper over `_factorize_from_iterable`.
*This is an internal function*
Parameters
----------
iterables : list-like of list-likes
Returns
-------
codes_list : list of ndarrays
categories_list : list of Indexes
Notes
-----
See `_factorize_from_iterable` for more info.
"""
if len(iterables) == 0:
# For consistency, it should return a list of 2 lists.
return [[], []]
return map(list, lzip(*[_factorize_from_iterable(it) for it in iterables])) | def _factorize_from_iterables(iterables):
"""
A higher-level wrapper over `_factorize_from_iterable`.
*This is an internal function*
Parameters
----------
iterables : list-like of list-likes
Returns
-------
codes_list : list of ndarrays
categories_list : list of Indexes
Notes
-----
See `_factorize_from_iterable` for more info.
"""
if len(iterables) == 0:
# For consistency, it should return a list of 2 lists.
return [[], []]
return map(list, lzip(*[_factorize_from_iterable(it) for it in iterables])) | [
"A",
"higher",
"-",
"level",
"wrapper",
"over",
"_factorize_from_iterable",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2673-L2695 | [
"def",
"_factorize_from_iterables",
"(",
"iterables",
")",
":",
"if",
"len",
"(",
"iterables",
")",
"==",
"0",
":",
"# For consistency, it should return a list of 2 lists.",
"return",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"return",
"map",
"(",
"list",
",",
"lzip",
"(",
"*",
"[",
"_factorize_from_iterable",
"(",
"it",
")",
"for",
"it",
"in",
"iterables",
"]",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.copy | Copy constructor. | pandas/core/arrays/categorical.py | def copy(self):
"""
Copy constructor.
"""
return self._constructor(values=self._codes.copy(),
dtype=self.dtype,
fastpath=True) | def copy(self):
"""
Copy constructor.
"""
return self._constructor(values=self._codes.copy(),
dtype=self.dtype,
fastpath=True) | [
"Copy",
"constructor",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L455-L461 | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"_constructor",
"(",
"values",
"=",
"self",
".",
"_codes",
".",
"copy",
"(",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.astype | Coerce this type to another dtype
Parameters
----------
dtype : numpy dtype or pandas type
copy : bool, default True
By default, astype always returns a newly allocated object.
If copy is set to False and dtype is categorical, the original
object is returned.
.. versionadded:: 0.19.0 | pandas/core/arrays/categorical.py | def astype(self, dtype, copy=True):
"""
Coerce this type to another dtype
Parameters
----------
dtype : numpy dtype or pandas type
copy : bool, default True
By default, astype always returns a newly allocated object.
If copy is set to False and dtype is categorical, the original
object is returned.
.. versionadded:: 0.19.0
"""
if is_categorical_dtype(dtype):
# GH 10696/18593
dtype = self.dtype.update_dtype(dtype)
self = self.copy() if copy else self
if dtype == self.dtype:
return self
return self._set_dtype(dtype)
return np.array(self, dtype=dtype, copy=copy) | def astype(self, dtype, copy=True):
"""
Coerce this type to another dtype
Parameters
----------
dtype : numpy dtype or pandas type
copy : bool, default True
By default, astype always returns a newly allocated object.
If copy is set to False and dtype is categorical, the original
object is returned.
.. versionadded:: 0.19.0
"""
if is_categorical_dtype(dtype):
# GH 10696/18593
dtype = self.dtype.update_dtype(dtype)
self = self.copy() if copy else self
if dtype == self.dtype:
return self
return self._set_dtype(dtype)
return np.array(self, dtype=dtype, copy=copy) | [
"Coerce",
"this",
"type",
"to",
"another",
"dtype"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L463-L485 | [
"def",
"astype",
"(",
"self",
",",
"dtype",
",",
"copy",
"=",
"True",
")",
":",
"if",
"is_categorical_dtype",
"(",
"dtype",
")",
":",
"# GH 10696/18593",
"dtype",
"=",
"self",
".",
"dtype",
".",
"update_dtype",
"(",
"dtype",
")",
"self",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"copy",
"else",
"self",
"if",
"dtype",
"==",
"self",
".",
"dtype",
":",
"return",
"self",
"return",
"self",
".",
"_set_dtype",
"(",
"dtype",
")",
"return",
"np",
".",
"array",
"(",
"self",
",",
"dtype",
"=",
"dtype",
",",
"copy",
"=",
"copy",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._from_inferred_categories | Construct a Categorical from inferred values.
For inferred categories (`dtype` is None) the categories are sorted.
For explicit `dtype`, the `inferred_categories` are cast to the
appropriate type.
Parameters
----------
inferred_categories : Index
inferred_codes : Index
dtype : CategoricalDtype or 'category'
true_values : list, optional
If none are provided, the default ones are
"True", "TRUE", and "true."
Returns
-------
Categorical | pandas/core/arrays/categorical.py | def _from_inferred_categories(cls, inferred_categories, inferred_codes,
dtype, true_values=None):
"""
Construct a Categorical from inferred values.
For inferred categories (`dtype` is None) the categories are sorted.
For explicit `dtype`, the `inferred_categories` are cast to the
appropriate type.
Parameters
----------
inferred_categories : Index
inferred_codes : Index
dtype : CategoricalDtype or 'category'
true_values : list, optional
If none are provided, the default ones are
"True", "TRUE", and "true."
Returns
-------
Categorical
"""
from pandas import Index, to_numeric, to_datetime, to_timedelta
cats = Index(inferred_categories)
known_categories = (isinstance(dtype, CategoricalDtype) and
dtype.categories is not None)
if known_categories:
# Convert to a specialized type with `dtype` if specified.
if dtype.categories.is_numeric():
cats = to_numeric(inferred_categories, errors="coerce")
elif is_datetime64_dtype(dtype.categories):
cats = to_datetime(inferred_categories, errors="coerce")
elif is_timedelta64_dtype(dtype.categories):
cats = to_timedelta(inferred_categories, errors="coerce")
elif dtype.categories.is_boolean():
if true_values is None:
true_values = ["True", "TRUE", "true"]
cats = cats.isin(true_values)
if known_categories:
# Recode from observation order to dtype.categories order.
categories = dtype.categories
codes = _recode_for_categories(inferred_codes, cats, categories)
elif not cats.is_monotonic_increasing:
# Sort categories and recode for unknown categories.
unsorted = cats.copy()
categories = cats.sort_values()
codes = _recode_for_categories(inferred_codes, unsorted,
categories)
dtype = CategoricalDtype(categories, ordered=False)
else:
dtype = CategoricalDtype(cats, ordered=False)
codes = inferred_codes
return cls(codes, dtype=dtype, fastpath=True) | def _from_inferred_categories(cls, inferred_categories, inferred_codes,
dtype, true_values=None):
"""
Construct a Categorical from inferred values.
For inferred categories (`dtype` is None) the categories are sorted.
For explicit `dtype`, the `inferred_categories` are cast to the
appropriate type.
Parameters
----------
inferred_categories : Index
inferred_codes : Index
dtype : CategoricalDtype or 'category'
true_values : list, optional
If none are provided, the default ones are
"True", "TRUE", and "true."
Returns
-------
Categorical
"""
from pandas import Index, to_numeric, to_datetime, to_timedelta
cats = Index(inferred_categories)
known_categories = (isinstance(dtype, CategoricalDtype) and
dtype.categories is not None)
if known_categories:
# Convert to a specialized type with `dtype` if specified.
if dtype.categories.is_numeric():
cats = to_numeric(inferred_categories, errors="coerce")
elif is_datetime64_dtype(dtype.categories):
cats = to_datetime(inferred_categories, errors="coerce")
elif is_timedelta64_dtype(dtype.categories):
cats = to_timedelta(inferred_categories, errors="coerce")
elif dtype.categories.is_boolean():
if true_values is None:
true_values = ["True", "TRUE", "true"]
cats = cats.isin(true_values)
if known_categories:
# Recode from observation order to dtype.categories order.
categories = dtype.categories
codes = _recode_for_categories(inferred_codes, cats, categories)
elif not cats.is_monotonic_increasing:
# Sort categories and recode for unknown categories.
unsorted = cats.copy()
categories = cats.sort_values()
codes = _recode_for_categories(inferred_codes, unsorted,
categories)
dtype = CategoricalDtype(categories, ordered=False)
else:
dtype = CategoricalDtype(cats, ordered=False)
codes = inferred_codes
return cls(codes, dtype=dtype, fastpath=True) | [
"Construct",
"a",
"Categorical",
"from",
"inferred",
"values",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L528-L586 | [
"def",
"_from_inferred_categories",
"(",
"cls",
",",
"inferred_categories",
",",
"inferred_codes",
",",
"dtype",
",",
"true_values",
"=",
"None",
")",
":",
"from",
"pandas",
"import",
"Index",
",",
"to_numeric",
",",
"to_datetime",
",",
"to_timedelta",
"cats",
"=",
"Index",
"(",
"inferred_categories",
")",
"known_categories",
"=",
"(",
"isinstance",
"(",
"dtype",
",",
"CategoricalDtype",
")",
"and",
"dtype",
".",
"categories",
"is",
"not",
"None",
")",
"if",
"known_categories",
":",
"# Convert to a specialized type with `dtype` if specified.",
"if",
"dtype",
".",
"categories",
".",
"is_numeric",
"(",
")",
":",
"cats",
"=",
"to_numeric",
"(",
"inferred_categories",
",",
"errors",
"=",
"\"coerce\"",
")",
"elif",
"is_datetime64_dtype",
"(",
"dtype",
".",
"categories",
")",
":",
"cats",
"=",
"to_datetime",
"(",
"inferred_categories",
",",
"errors",
"=",
"\"coerce\"",
")",
"elif",
"is_timedelta64_dtype",
"(",
"dtype",
".",
"categories",
")",
":",
"cats",
"=",
"to_timedelta",
"(",
"inferred_categories",
",",
"errors",
"=",
"\"coerce\"",
")",
"elif",
"dtype",
".",
"categories",
".",
"is_boolean",
"(",
")",
":",
"if",
"true_values",
"is",
"None",
":",
"true_values",
"=",
"[",
"\"True\"",
",",
"\"TRUE\"",
",",
"\"true\"",
"]",
"cats",
"=",
"cats",
".",
"isin",
"(",
"true_values",
")",
"if",
"known_categories",
":",
"# Recode from observation order to dtype.categories order.",
"categories",
"=",
"dtype",
".",
"categories",
"codes",
"=",
"_recode_for_categories",
"(",
"inferred_codes",
",",
"cats",
",",
"categories",
")",
"elif",
"not",
"cats",
".",
"is_monotonic_increasing",
":",
"# Sort categories and recode for unknown categories.",
"unsorted",
"=",
"cats",
".",
"copy",
"(",
")",
"categories",
"=",
"cats",
".",
"sort_values",
"(",
")",
"codes",
"=",
"_recode_for_categories",
"(",
"inferred_codes",
",",
"unsorted",
",",
"categories",
")",
"dtype",
"=",
"CategoricalDtype",
"(",
"categories",
",",
"ordered",
"=",
"False",
")",
"else",
":",
"dtype",
"=",
"CategoricalDtype",
"(",
"cats",
",",
"ordered",
"=",
"False",
")",
"codes",
"=",
"inferred_codes",
"return",
"cls",
"(",
"codes",
",",
"dtype",
"=",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.from_codes | Make a Categorical type from codes and categories or dtype.
This constructor is useful if you already have codes and
categories/dtype and so do not need the (computation intensive)
factorization step, which is usually done on the constructor.
If your data does not follow this convention, please use the normal
constructor.
Parameters
----------
codes : array-like, integers
An integer array, where each integer points to a category in
categories or dtype.categories, or else is -1 for NaN.
categories : index-like, optional
The categories for the categorical. Items need to be unique.
If the categories are not given here, then they must be provided
in `dtype`.
ordered : bool, optional
Whether or not this categorical is treated as an ordered
categorical. If not given here or in `dtype`, the resulting
categorical will be unordered.
dtype : CategoricalDtype or the string "category", optional
If :class:`CategoricalDtype`, cannot be used together with
`categories` or `ordered`.
.. versionadded:: 0.24.0
When `dtype` is provided, neither `categories` nor `ordered`
should be provided.
Examples
--------
>>> dtype = pd.CategoricalDtype(['a', 'b'], ordered=True)
>>> pd.Categorical.from_codes(codes=[0, 1, 0, 1], dtype=dtype)
[a, b, a, b]
Categories (2, object): [a < b] | pandas/core/arrays/categorical.py | def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
"""
Make a Categorical type from codes and categories or dtype.
This constructor is useful if you already have codes and
categories/dtype and so do not need the (computation intensive)
factorization step, which is usually done on the constructor.
If your data does not follow this convention, please use the normal
constructor.
Parameters
----------
codes : array-like, integers
An integer array, where each integer points to a category in
categories or dtype.categories, or else is -1 for NaN.
categories : index-like, optional
The categories for the categorical. Items need to be unique.
If the categories are not given here, then they must be provided
in `dtype`.
ordered : bool, optional
Whether or not this categorical is treated as an ordered
categorical. If not given here or in `dtype`, the resulting
categorical will be unordered.
dtype : CategoricalDtype or the string "category", optional
If :class:`CategoricalDtype`, cannot be used together with
`categories` or `ordered`.
.. versionadded:: 0.24.0
When `dtype` is provided, neither `categories` nor `ordered`
should be provided.
Examples
--------
>>> dtype = pd.CategoricalDtype(['a', 'b'], ordered=True)
>>> pd.Categorical.from_codes(codes=[0, 1, 0, 1], dtype=dtype)
[a, b, a, b]
Categories (2, object): [a < b]
"""
dtype = CategoricalDtype._from_values_or_dtype(categories=categories,
ordered=ordered,
dtype=dtype)
if dtype.categories is None:
msg = ("The categories must be provided in 'categories' or "
"'dtype'. Both were None.")
raise ValueError(msg)
codes = np.asarray(codes) # #21767
if not is_integer_dtype(codes):
msg = "codes need to be array-like integers"
if is_float_dtype(codes):
icodes = codes.astype('i8')
if (icodes == codes).all():
msg = None
codes = icodes
warn(("float codes will be disallowed in the future and "
"raise a ValueError"), FutureWarning, stacklevel=2)
if msg:
raise ValueError(msg)
if len(codes) and (
codes.max() >= len(dtype.categories) or codes.min() < -1):
raise ValueError("codes need to be between -1 and "
"len(categories)-1")
return cls(codes, dtype=dtype, fastpath=True) | def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
"""
Make a Categorical type from codes and categories or dtype.
This constructor is useful if you already have codes and
categories/dtype and so do not need the (computation intensive)
factorization step, which is usually done on the constructor.
If your data does not follow this convention, please use the normal
constructor.
Parameters
----------
codes : array-like, integers
An integer array, where each integer points to a category in
categories or dtype.categories, or else is -1 for NaN.
categories : index-like, optional
The categories for the categorical. Items need to be unique.
If the categories are not given here, then they must be provided
in `dtype`.
ordered : bool, optional
Whether or not this categorical is treated as an ordered
categorical. If not given here or in `dtype`, the resulting
categorical will be unordered.
dtype : CategoricalDtype or the string "category", optional
If :class:`CategoricalDtype`, cannot be used together with
`categories` or `ordered`.
.. versionadded:: 0.24.0
When `dtype` is provided, neither `categories` nor `ordered`
should be provided.
Examples
--------
>>> dtype = pd.CategoricalDtype(['a', 'b'], ordered=True)
>>> pd.Categorical.from_codes(codes=[0, 1, 0, 1], dtype=dtype)
[a, b, a, b]
Categories (2, object): [a < b]
"""
dtype = CategoricalDtype._from_values_or_dtype(categories=categories,
ordered=ordered,
dtype=dtype)
if dtype.categories is None:
msg = ("The categories must be provided in 'categories' or "
"'dtype'. Both were None.")
raise ValueError(msg)
codes = np.asarray(codes) # #21767
if not is_integer_dtype(codes):
msg = "codes need to be array-like integers"
if is_float_dtype(codes):
icodes = codes.astype('i8')
if (icodes == codes).all():
msg = None
codes = icodes
warn(("float codes will be disallowed in the future and "
"raise a ValueError"), FutureWarning, stacklevel=2)
if msg:
raise ValueError(msg)
if len(codes) and (
codes.max() >= len(dtype.categories) or codes.min() < -1):
raise ValueError("codes need to be between -1 and "
"len(categories)-1")
return cls(codes, dtype=dtype, fastpath=True) | [
"Make",
"a",
"Categorical",
"type",
"from",
"codes",
"and",
"categories",
"or",
"dtype",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L589-L655 | [
"def",
"from_codes",
"(",
"cls",
",",
"codes",
",",
"categories",
"=",
"None",
",",
"ordered",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"dtype",
"=",
"CategoricalDtype",
".",
"_from_values_or_dtype",
"(",
"categories",
"=",
"categories",
",",
"ordered",
"=",
"ordered",
",",
"dtype",
"=",
"dtype",
")",
"if",
"dtype",
".",
"categories",
"is",
"None",
":",
"msg",
"=",
"(",
"\"The categories must be provided in 'categories' or \"",
"\"'dtype'. Both were None.\"",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"codes",
"=",
"np",
".",
"asarray",
"(",
"codes",
")",
"# #21767",
"if",
"not",
"is_integer_dtype",
"(",
"codes",
")",
":",
"msg",
"=",
"\"codes need to be array-like integers\"",
"if",
"is_float_dtype",
"(",
"codes",
")",
":",
"icodes",
"=",
"codes",
".",
"astype",
"(",
"'i8'",
")",
"if",
"(",
"icodes",
"==",
"codes",
")",
".",
"all",
"(",
")",
":",
"msg",
"=",
"None",
"codes",
"=",
"icodes",
"warn",
"(",
"(",
"\"float codes will be disallowed in the future and \"",
"\"raise a ValueError\"",
")",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"msg",
":",
"raise",
"ValueError",
"(",
"msg",
")",
"if",
"len",
"(",
"codes",
")",
"and",
"(",
"codes",
".",
"max",
"(",
")",
">=",
"len",
"(",
"dtype",
".",
"categories",
")",
"or",
"codes",
".",
"min",
"(",
")",
"<",
"-",
"1",
")",
":",
"raise",
"ValueError",
"(",
"\"codes need to be between -1 and \"",
"\"len(categories)-1\"",
")",
"return",
"cls",
"(",
"codes",
",",
"dtype",
"=",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._get_codes | Get the codes.
Returns
-------
codes : integer array view
A non writable view of the `codes` array. | pandas/core/arrays/categorical.py | def _get_codes(self):
"""
Get the codes.
Returns
-------
codes : integer array view
A non writable view of the `codes` array.
"""
v = self._codes.view()
v.flags.writeable = False
return v | def _get_codes(self):
"""
Get the codes.
Returns
-------
codes : integer array view
A non writable view of the `codes` array.
"""
v = self._codes.view()
v.flags.writeable = False
return v | [
"Get",
"the",
"codes",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L659-L670 | [
"def",
"_get_codes",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"_codes",
".",
"view",
"(",
")",
"v",
".",
"flags",
".",
"writeable",
"=",
"False",
"return",
"v"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._set_categories | Sets new categories inplace
Parameters
----------
fastpath : bool, default False
Don't perform validation of the categories for uniqueness or nulls
Examples
--------
>>> c = pd.Categorical(['a', 'b'])
>>> c
[a, b]
Categories (2, object): [a, b]
>>> c._set_categories(pd.Index(['a', 'c']))
>>> c
[a, c]
Categories (2, object): [a, c] | pandas/core/arrays/categorical.py | def _set_categories(self, categories, fastpath=False):
"""
Sets new categories inplace
Parameters
----------
fastpath : bool, default False
Don't perform validation of the categories for uniqueness or nulls
Examples
--------
>>> c = pd.Categorical(['a', 'b'])
>>> c
[a, b]
Categories (2, object): [a, b]
>>> c._set_categories(pd.Index(['a', 'c']))
>>> c
[a, c]
Categories (2, object): [a, c]
"""
if fastpath:
new_dtype = CategoricalDtype._from_fastpath(categories,
self.ordered)
else:
new_dtype = CategoricalDtype(categories, ordered=self.ordered)
if (not fastpath and self.dtype.categories is not None and
len(new_dtype.categories) != len(self.dtype.categories)):
raise ValueError("new categories need to have the same number of "
"items than the old categories!")
self._dtype = new_dtype | def _set_categories(self, categories, fastpath=False):
"""
Sets new categories inplace
Parameters
----------
fastpath : bool, default False
Don't perform validation of the categories for uniqueness or nulls
Examples
--------
>>> c = pd.Categorical(['a', 'b'])
>>> c
[a, b]
Categories (2, object): [a, b]
>>> c._set_categories(pd.Index(['a', 'c']))
>>> c
[a, c]
Categories (2, object): [a, c]
"""
if fastpath:
new_dtype = CategoricalDtype._from_fastpath(categories,
self.ordered)
else:
new_dtype = CategoricalDtype(categories, ordered=self.ordered)
if (not fastpath and self.dtype.categories is not None and
len(new_dtype.categories) != len(self.dtype.categories)):
raise ValueError("new categories need to have the same number of "
"items than the old categories!")
self._dtype = new_dtype | [
"Sets",
"new",
"categories",
"inplace"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L680-L712 | [
"def",
"_set_categories",
"(",
"self",
",",
"categories",
",",
"fastpath",
"=",
"False",
")",
":",
"if",
"fastpath",
":",
"new_dtype",
"=",
"CategoricalDtype",
".",
"_from_fastpath",
"(",
"categories",
",",
"self",
".",
"ordered",
")",
"else",
":",
"new_dtype",
"=",
"CategoricalDtype",
"(",
"categories",
",",
"ordered",
"=",
"self",
".",
"ordered",
")",
"if",
"(",
"not",
"fastpath",
"and",
"self",
".",
"dtype",
".",
"categories",
"is",
"not",
"None",
"and",
"len",
"(",
"new_dtype",
".",
"categories",
")",
"!=",
"len",
"(",
"self",
".",
"dtype",
".",
"categories",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"new categories need to have the same number of \"",
"\"items than the old categories!\"",
")",
"self",
".",
"_dtype",
"=",
"new_dtype"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._set_dtype | Internal method for directly updating the CategoricalDtype
Parameters
----------
dtype : CategoricalDtype
Notes
-----
We don't do any validation here. It's assumed that the dtype is
a (valid) instance of `CategoricalDtype`. | pandas/core/arrays/categorical.py | def _set_dtype(self, dtype):
"""
Internal method for directly updating the CategoricalDtype
Parameters
----------
dtype : CategoricalDtype
Notes
-----
We don't do any validation here. It's assumed that the dtype is
a (valid) instance of `CategoricalDtype`.
"""
codes = _recode_for_categories(self.codes, self.categories,
dtype.categories)
return type(self)(codes, dtype=dtype, fastpath=True) | def _set_dtype(self, dtype):
"""
Internal method for directly updating the CategoricalDtype
Parameters
----------
dtype : CategoricalDtype
Notes
-----
We don't do any validation here. It's assumed that the dtype is
a (valid) instance of `CategoricalDtype`.
"""
codes = _recode_for_categories(self.codes, self.categories,
dtype.categories)
return type(self)(codes, dtype=dtype, fastpath=True) | [
"Internal",
"method",
"for",
"directly",
"updating",
"the",
"CategoricalDtype"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L714-L729 | [
"def",
"_set_dtype",
"(",
"self",
",",
"dtype",
")",
":",
"codes",
"=",
"_recode_for_categories",
"(",
"self",
".",
"codes",
",",
"self",
".",
"categories",
",",
"dtype",
".",
"categories",
")",
"return",
"type",
"(",
"self",
")",
"(",
"codes",
",",
"dtype",
"=",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.set_ordered | Set the ordered attribute to the boolean value.
Parameters
----------
value : bool
Set whether this categorical is ordered (True) or not (False).
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to the value. | pandas/core/arrays/categorical.py | def set_ordered(self, value, inplace=False):
"""
Set the ordered attribute to the boolean value.
Parameters
----------
value : bool
Set whether this categorical is ordered (True) or not (False).
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to the value.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
new_dtype = CategoricalDtype(self.categories, ordered=value)
cat = self if inplace else self.copy()
cat._dtype = new_dtype
if not inplace:
return cat | def set_ordered(self, value, inplace=False):
"""
Set the ordered attribute to the boolean value.
Parameters
----------
value : bool
Set whether this categorical is ordered (True) or not (False).
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to the value.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
new_dtype = CategoricalDtype(self.categories, ordered=value)
cat = self if inplace else self.copy()
cat._dtype = new_dtype
if not inplace:
return cat | [
"Set",
"the",
"ordered",
"attribute",
"to",
"the",
"boolean",
"value",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L731-L748 | [
"def",
"set_ordered",
"(",
"self",
",",
"value",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"new_dtype",
"=",
"CategoricalDtype",
"(",
"self",
".",
"categories",
",",
"ordered",
"=",
"value",
")",
"cat",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
")",
"cat",
".",
"_dtype",
"=",
"new_dtype",
"if",
"not",
"inplace",
":",
"return",
"cat"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.as_ordered | Set the Categorical to be ordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to True. | pandas/core/arrays/categorical.py | def as_ordered(self, inplace=False):
"""
Set the Categorical to be ordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to True.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
return self.set_ordered(True, inplace=inplace) | def as_ordered(self, inplace=False):
"""
Set the Categorical to be ordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to True.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
return self.set_ordered(True, inplace=inplace) | [
"Set",
"the",
"Categorical",
"to",
"be",
"ordered",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L750-L761 | [
"def",
"as_ordered",
"(",
"self",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"return",
"self",
".",
"set_ordered",
"(",
"True",
",",
"inplace",
"=",
"inplace",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.as_unordered | Set the Categorical to be unordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to False. | pandas/core/arrays/categorical.py | def as_unordered(self, inplace=False):
"""
Set the Categorical to be unordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to False.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
return self.set_ordered(False, inplace=inplace) | def as_unordered(self, inplace=False):
"""
Set the Categorical to be unordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to False.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
return self.set_ordered(False, inplace=inplace) | [
"Set",
"the",
"Categorical",
"to",
"be",
"unordered",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L763-L774 | [
"def",
"as_unordered",
"(",
"self",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"return",
"self",
".",
"set_ordered",
"(",
"False",
",",
"inplace",
"=",
"inplace",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.set_categories | Set the categories to the specified new_categories.
`new_categories` can include new categories (which will result in
unused categories) or remove old categories (which results in values
set to NaN). If `rename==True`, the categories will simple be renamed
(less or more items than in old categories will result in values set to
NaN or in unused categories respectively).
This method can be used to perform more than one action of adding,
removing, and reordering simultaneously and is therefore faster than
performing the individual steps via the more specialised methods.
On the other hand this methods does not do checks (e.g., whether the
old categories are included in the new categories on a reorder), which
can result in surprising changes, for example when using special string
dtypes on python3, which does not considers a S1 string equal to a
single char python string.
Parameters
----------
new_categories : Index-like
The categories in new order.
ordered : bool, default False
Whether or not the categorical is treated as a ordered categorical.
If not given, do not change the ordered information.
rename : bool, default False
Whether or not the new_categories should be considered as a rename
of the old categories or as reordered categories.
inplace : bool, default False
Whether or not to reorder the categories in-place or return a copy
of this categorical with reordered categories.
Returns
-------
Categorical with reordered categories or None if inplace.
Raises
------
ValueError
If new_categories does not validate as categories
See Also
--------
rename_categories
reorder_categories
add_categories
remove_categories
remove_unused_categories | pandas/core/arrays/categorical.py | def set_categories(self, new_categories, ordered=None, rename=False,
inplace=False):
"""
Set the categories to the specified new_categories.
`new_categories` can include new categories (which will result in
unused categories) or remove old categories (which results in values
set to NaN). If `rename==True`, the categories will simple be renamed
(less or more items than in old categories will result in values set to
NaN or in unused categories respectively).
This method can be used to perform more than one action of adding,
removing, and reordering simultaneously and is therefore faster than
performing the individual steps via the more specialised methods.
On the other hand this methods does not do checks (e.g., whether the
old categories are included in the new categories on a reorder), which
can result in surprising changes, for example when using special string
dtypes on python3, which does not considers a S1 string equal to a
single char python string.
Parameters
----------
new_categories : Index-like
The categories in new order.
ordered : bool, default False
Whether or not the categorical is treated as a ordered categorical.
If not given, do not change the ordered information.
rename : bool, default False
Whether or not the new_categories should be considered as a rename
of the old categories or as reordered categories.
inplace : bool, default False
Whether or not to reorder the categories in-place or return a copy
of this categorical with reordered categories.
Returns
-------
Categorical with reordered categories or None if inplace.
Raises
------
ValueError
If new_categories does not validate as categories
See Also
--------
rename_categories
reorder_categories
add_categories
remove_categories
remove_unused_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if ordered is None:
ordered = self.dtype.ordered
new_dtype = CategoricalDtype(new_categories, ordered=ordered)
cat = self if inplace else self.copy()
if rename:
if (cat.dtype.categories is not None and
len(new_dtype.categories) < len(cat.dtype.categories)):
# remove all _codes which are larger and set to -1/NaN
cat._codes[cat._codes >= len(new_dtype.categories)] = -1
else:
codes = _recode_for_categories(cat.codes, cat.categories,
new_dtype.categories)
cat._codes = codes
cat._dtype = new_dtype
if not inplace:
return cat | def set_categories(self, new_categories, ordered=None, rename=False,
inplace=False):
"""
Set the categories to the specified new_categories.
`new_categories` can include new categories (which will result in
unused categories) or remove old categories (which results in values
set to NaN). If `rename==True`, the categories will simple be renamed
(less or more items than in old categories will result in values set to
NaN or in unused categories respectively).
This method can be used to perform more than one action of adding,
removing, and reordering simultaneously and is therefore faster than
performing the individual steps via the more specialised methods.
On the other hand this methods does not do checks (e.g., whether the
old categories are included in the new categories on a reorder), which
can result in surprising changes, for example when using special string
dtypes on python3, which does not considers a S1 string equal to a
single char python string.
Parameters
----------
new_categories : Index-like
The categories in new order.
ordered : bool, default False
Whether or not the categorical is treated as a ordered categorical.
If not given, do not change the ordered information.
rename : bool, default False
Whether or not the new_categories should be considered as a rename
of the old categories or as reordered categories.
inplace : bool, default False
Whether or not to reorder the categories in-place or return a copy
of this categorical with reordered categories.
Returns
-------
Categorical with reordered categories or None if inplace.
Raises
------
ValueError
If new_categories does not validate as categories
See Also
--------
rename_categories
reorder_categories
add_categories
remove_categories
remove_unused_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if ordered is None:
ordered = self.dtype.ordered
new_dtype = CategoricalDtype(new_categories, ordered=ordered)
cat = self if inplace else self.copy()
if rename:
if (cat.dtype.categories is not None and
len(new_dtype.categories) < len(cat.dtype.categories)):
# remove all _codes which are larger and set to -1/NaN
cat._codes[cat._codes >= len(new_dtype.categories)] = -1
else:
codes = _recode_for_categories(cat.codes, cat.categories,
new_dtype.categories)
cat._codes = codes
cat._dtype = new_dtype
if not inplace:
return cat | [
"Set",
"the",
"categories",
"to",
"the",
"specified",
"new_categories",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L776-L846 | [
"def",
"set_categories",
"(",
"self",
",",
"new_categories",
",",
"ordered",
"=",
"None",
",",
"rename",
"=",
"False",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"ordered",
"is",
"None",
":",
"ordered",
"=",
"self",
".",
"dtype",
".",
"ordered",
"new_dtype",
"=",
"CategoricalDtype",
"(",
"new_categories",
",",
"ordered",
"=",
"ordered",
")",
"cat",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
")",
"if",
"rename",
":",
"if",
"(",
"cat",
".",
"dtype",
".",
"categories",
"is",
"not",
"None",
"and",
"len",
"(",
"new_dtype",
".",
"categories",
")",
"<",
"len",
"(",
"cat",
".",
"dtype",
".",
"categories",
")",
")",
":",
"# remove all _codes which are larger and set to -1/NaN",
"cat",
".",
"_codes",
"[",
"cat",
".",
"_codes",
">=",
"len",
"(",
"new_dtype",
".",
"categories",
")",
"]",
"=",
"-",
"1",
"else",
":",
"codes",
"=",
"_recode_for_categories",
"(",
"cat",
".",
"codes",
",",
"cat",
".",
"categories",
",",
"new_dtype",
".",
"categories",
")",
"cat",
".",
"_codes",
"=",
"codes",
"cat",
".",
"_dtype",
"=",
"new_dtype",
"if",
"not",
"inplace",
":",
"return",
"cat"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.rename_categories | Rename categories.
Parameters
----------
new_categories : list-like, dict-like or callable
* list-like: all items must be unique and the number of items in
the new categories must match the existing number of categories.
* dict-like: specifies a mapping from
old categories to new. Categories not contained in the mapping
are passed through and extra categories in the mapping are
ignored.
.. versionadded:: 0.21.0
* callable : a callable that is called on all items in the old
categories and whose return values comprise the new categories.
.. versionadded:: 0.23.0
.. warning::
Currently, Series are considered list like. In a future version
of pandas they'll be considered dict-like.
inplace : bool, default False
Whether or not to rename the categories inplace or return a copy of
this categorical with renamed categories.
Returns
-------
cat : Categorical or None
With ``inplace=False``, the new categorical is returned.
With ``inplace=True``, there is no return value.
Raises
------
ValueError
If new categories are list-like and do not have the same number of
items than the current categories or do not validate as categories
See Also
--------
reorder_categories
add_categories
remove_categories
remove_unused_categories
set_categories
Examples
--------
>>> c = pd.Categorical(['a', 'a', 'b'])
>>> c.rename_categories([0, 1])
[0, 0, 1]
Categories (2, int64): [0, 1]
For dict-like ``new_categories``, extra keys are ignored and
categories not in the dictionary are passed through
>>> c.rename_categories({'a': 'A', 'c': 'C'})
[A, A, b]
Categories (2, object): [A, b]
You may also provide a callable to create the new categories
>>> c.rename_categories(lambda x: x.upper())
[A, A, B]
Categories (2, object): [A, B] | pandas/core/arrays/categorical.py | def rename_categories(self, new_categories, inplace=False):
"""
Rename categories.
Parameters
----------
new_categories : list-like, dict-like or callable
* list-like: all items must be unique and the number of items in
the new categories must match the existing number of categories.
* dict-like: specifies a mapping from
old categories to new. Categories not contained in the mapping
are passed through and extra categories in the mapping are
ignored.
.. versionadded:: 0.21.0
* callable : a callable that is called on all items in the old
categories and whose return values comprise the new categories.
.. versionadded:: 0.23.0
.. warning::
Currently, Series are considered list like. In a future version
of pandas they'll be considered dict-like.
inplace : bool, default False
Whether or not to rename the categories inplace or return a copy of
this categorical with renamed categories.
Returns
-------
cat : Categorical or None
With ``inplace=False``, the new categorical is returned.
With ``inplace=True``, there is no return value.
Raises
------
ValueError
If new categories are list-like and do not have the same number of
items than the current categories or do not validate as categories
See Also
--------
reorder_categories
add_categories
remove_categories
remove_unused_categories
set_categories
Examples
--------
>>> c = pd.Categorical(['a', 'a', 'b'])
>>> c.rename_categories([0, 1])
[0, 0, 1]
Categories (2, int64): [0, 1]
For dict-like ``new_categories``, extra keys are ignored and
categories not in the dictionary are passed through
>>> c.rename_categories({'a': 'A', 'c': 'C'})
[A, A, b]
Categories (2, object): [A, b]
You may also provide a callable to create the new categories
>>> c.rename_categories(lambda x: x.upper())
[A, A, B]
Categories (2, object): [A, B]
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
cat = self if inplace else self.copy()
if isinstance(new_categories, ABCSeries):
msg = ("Treating Series 'new_categories' as a list-like and using "
"the values. In a future version, 'rename_categories' will "
"treat Series like a dictionary.\n"
"For dict-like, use 'new_categories.to_dict()'\n"
"For list-like, use 'new_categories.values'.")
warn(msg, FutureWarning, stacklevel=2)
new_categories = list(new_categories)
if is_dict_like(new_categories):
cat.categories = [new_categories.get(item, item)
for item in cat.categories]
elif callable(new_categories):
cat.categories = [new_categories(item) for item in cat.categories]
else:
cat.categories = new_categories
if not inplace:
return cat | def rename_categories(self, new_categories, inplace=False):
"""
Rename categories.
Parameters
----------
new_categories : list-like, dict-like or callable
* list-like: all items must be unique and the number of items in
the new categories must match the existing number of categories.
* dict-like: specifies a mapping from
old categories to new. Categories not contained in the mapping
are passed through and extra categories in the mapping are
ignored.
.. versionadded:: 0.21.0
* callable : a callable that is called on all items in the old
categories and whose return values comprise the new categories.
.. versionadded:: 0.23.0
.. warning::
Currently, Series are considered list like. In a future version
of pandas they'll be considered dict-like.
inplace : bool, default False
Whether or not to rename the categories inplace or return a copy of
this categorical with renamed categories.
Returns
-------
cat : Categorical or None
With ``inplace=False``, the new categorical is returned.
With ``inplace=True``, there is no return value.
Raises
------
ValueError
If new categories are list-like and do not have the same number of
items than the current categories or do not validate as categories
See Also
--------
reorder_categories
add_categories
remove_categories
remove_unused_categories
set_categories
Examples
--------
>>> c = pd.Categorical(['a', 'a', 'b'])
>>> c.rename_categories([0, 1])
[0, 0, 1]
Categories (2, int64): [0, 1]
For dict-like ``new_categories``, extra keys are ignored and
categories not in the dictionary are passed through
>>> c.rename_categories({'a': 'A', 'c': 'C'})
[A, A, b]
Categories (2, object): [A, b]
You may also provide a callable to create the new categories
>>> c.rename_categories(lambda x: x.upper())
[A, A, B]
Categories (2, object): [A, B]
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
cat = self if inplace else self.copy()
if isinstance(new_categories, ABCSeries):
msg = ("Treating Series 'new_categories' as a list-like and using "
"the values. In a future version, 'rename_categories' will "
"treat Series like a dictionary.\n"
"For dict-like, use 'new_categories.to_dict()'\n"
"For list-like, use 'new_categories.values'.")
warn(msg, FutureWarning, stacklevel=2)
new_categories = list(new_categories)
if is_dict_like(new_categories):
cat.categories = [new_categories.get(item, item)
for item in cat.categories]
elif callable(new_categories):
cat.categories = [new_categories(item) for item in cat.categories]
else:
cat.categories = new_categories
if not inplace:
return cat | [
"Rename",
"categories",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L848-L940 | [
"def",
"rename_categories",
"(",
"self",
",",
"new_categories",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"cat",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
")",
"if",
"isinstance",
"(",
"new_categories",
",",
"ABCSeries",
")",
":",
"msg",
"=",
"(",
"\"Treating Series 'new_categories' as a list-like and using \"",
"\"the values. In a future version, 'rename_categories' will \"",
"\"treat Series like a dictionary.\\n\"",
"\"For dict-like, use 'new_categories.to_dict()'\\n\"",
"\"For list-like, use 'new_categories.values'.\"",
")",
"warn",
"(",
"msg",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"new_categories",
"=",
"list",
"(",
"new_categories",
")",
"if",
"is_dict_like",
"(",
"new_categories",
")",
":",
"cat",
".",
"categories",
"=",
"[",
"new_categories",
".",
"get",
"(",
"item",
",",
"item",
")",
"for",
"item",
"in",
"cat",
".",
"categories",
"]",
"elif",
"callable",
"(",
"new_categories",
")",
":",
"cat",
".",
"categories",
"=",
"[",
"new_categories",
"(",
"item",
")",
"for",
"item",
"in",
"cat",
".",
"categories",
"]",
"else",
":",
"cat",
".",
"categories",
"=",
"new_categories",
"if",
"not",
"inplace",
":",
"return",
"cat"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.reorder_categories | Reorder categories as specified in new_categories.
`new_categories` need to include all old categories and no new category
items.
Parameters
----------
new_categories : Index-like
The categories in new order.
ordered : bool, optional
Whether or not the categorical is treated as a ordered categorical.
If not given, do not change the ordered information.
inplace : bool, default False
Whether or not to reorder the categories inplace or return a copy of
this categorical with reordered categories.
Returns
-------
cat : Categorical with reordered categories or None if inplace.
Raises
------
ValueError
If the new categories do not contain all old category items or any
new ones
See Also
--------
rename_categories
add_categories
remove_categories
remove_unused_categories
set_categories | pandas/core/arrays/categorical.py | def reorder_categories(self, new_categories, ordered=None, inplace=False):
"""
Reorder categories as specified in new_categories.
`new_categories` need to include all old categories and no new category
items.
Parameters
----------
new_categories : Index-like
The categories in new order.
ordered : bool, optional
Whether or not the categorical is treated as a ordered categorical.
If not given, do not change the ordered information.
inplace : bool, default False
Whether or not to reorder the categories inplace or return a copy of
this categorical with reordered categories.
Returns
-------
cat : Categorical with reordered categories or None if inplace.
Raises
------
ValueError
If the new categories do not contain all old category items or any
new ones
See Also
--------
rename_categories
add_categories
remove_categories
remove_unused_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if set(self.dtype.categories) != set(new_categories):
raise ValueError("items in new_categories are not the same as in "
"old categories")
return self.set_categories(new_categories, ordered=ordered,
inplace=inplace) | def reorder_categories(self, new_categories, ordered=None, inplace=False):
"""
Reorder categories as specified in new_categories.
`new_categories` need to include all old categories and no new category
items.
Parameters
----------
new_categories : Index-like
The categories in new order.
ordered : bool, optional
Whether or not the categorical is treated as a ordered categorical.
If not given, do not change the ordered information.
inplace : bool, default False
Whether or not to reorder the categories inplace or return a copy of
this categorical with reordered categories.
Returns
-------
cat : Categorical with reordered categories or None if inplace.
Raises
------
ValueError
If the new categories do not contain all old category items or any
new ones
See Also
--------
rename_categories
add_categories
remove_categories
remove_unused_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if set(self.dtype.categories) != set(new_categories):
raise ValueError("items in new_categories are not the same as in "
"old categories")
return self.set_categories(new_categories, ordered=ordered,
inplace=inplace) | [
"Reorder",
"categories",
"as",
"specified",
"in",
"new_categories",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L942-L983 | [
"def",
"reorder_categories",
"(",
"self",
",",
"new_categories",
",",
"ordered",
"=",
"None",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"set",
"(",
"self",
".",
"dtype",
".",
"categories",
")",
"!=",
"set",
"(",
"new_categories",
")",
":",
"raise",
"ValueError",
"(",
"\"items in new_categories are not the same as in \"",
"\"old categories\"",
")",
"return",
"self",
".",
"set_categories",
"(",
"new_categories",
",",
"ordered",
"=",
"ordered",
",",
"inplace",
"=",
"inplace",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.add_categories | Add new categories.
`new_categories` will be included at the last/highest place in the
categories and will be unused directly after this call.
Parameters
----------
new_categories : category or list-like of category
The new categories to be included.
inplace : bool, default False
Whether or not to add the categories inplace or return a copy of
this categorical with added categories.
Returns
-------
cat : Categorical with new categories added or None if inplace.
Raises
------
ValueError
If the new categories include old categories or do not validate as
categories
See Also
--------
rename_categories
reorder_categories
remove_categories
remove_unused_categories
set_categories | pandas/core/arrays/categorical.py | def add_categories(self, new_categories, inplace=False):
"""
Add new categories.
`new_categories` will be included at the last/highest place in the
categories and will be unused directly after this call.
Parameters
----------
new_categories : category or list-like of category
The new categories to be included.
inplace : bool, default False
Whether or not to add the categories inplace or return a copy of
this categorical with added categories.
Returns
-------
cat : Categorical with new categories added or None if inplace.
Raises
------
ValueError
If the new categories include old categories or do not validate as
categories
See Also
--------
rename_categories
reorder_categories
remove_categories
remove_unused_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if not is_list_like(new_categories):
new_categories = [new_categories]
already_included = set(new_categories) & set(self.dtype.categories)
if len(already_included) != 0:
msg = ("new categories must not include old categories: "
"{already_included!s}")
raise ValueError(msg.format(already_included=already_included))
new_categories = list(self.dtype.categories) + list(new_categories)
new_dtype = CategoricalDtype(new_categories, self.ordered)
cat = self if inplace else self.copy()
cat._dtype = new_dtype
cat._codes = coerce_indexer_dtype(cat._codes, new_dtype.categories)
if not inplace:
return cat | def add_categories(self, new_categories, inplace=False):
"""
Add new categories.
`new_categories` will be included at the last/highest place in the
categories and will be unused directly after this call.
Parameters
----------
new_categories : category or list-like of category
The new categories to be included.
inplace : bool, default False
Whether or not to add the categories inplace or return a copy of
this categorical with added categories.
Returns
-------
cat : Categorical with new categories added or None if inplace.
Raises
------
ValueError
If the new categories include old categories or do not validate as
categories
See Also
--------
rename_categories
reorder_categories
remove_categories
remove_unused_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if not is_list_like(new_categories):
new_categories = [new_categories]
already_included = set(new_categories) & set(self.dtype.categories)
if len(already_included) != 0:
msg = ("new categories must not include old categories: "
"{already_included!s}")
raise ValueError(msg.format(already_included=already_included))
new_categories = list(self.dtype.categories) + list(new_categories)
new_dtype = CategoricalDtype(new_categories, self.ordered)
cat = self if inplace else self.copy()
cat._dtype = new_dtype
cat._codes = coerce_indexer_dtype(cat._codes, new_dtype.categories)
if not inplace:
return cat | [
"Add",
"new",
"categories",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L985-L1033 | [
"def",
"add_categories",
"(",
"self",
",",
"new_categories",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"not",
"is_list_like",
"(",
"new_categories",
")",
":",
"new_categories",
"=",
"[",
"new_categories",
"]",
"already_included",
"=",
"set",
"(",
"new_categories",
")",
"&",
"set",
"(",
"self",
".",
"dtype",
".",
"categories",
")",
"if",
"len",
"(",
"already_included",
")",
"!=",
"0",
":",
"msg",
"=",
"(",
"\"new categories must not include old categories: \"",
"\"{already_included!s}\"",
")",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"already_included",
"=",
"already_included",
")",
")",
"new_categories",
"=",
"list",
"(",
"self",
".",
"dtype",
".",
"categories",
")",
"+",
"list",
"(",
"new_categories",
")",
"new_dtype",
"=",
"CategoricalDtype",
"(",
"new_categories",
",",
"self",
".",
"ordered",
")",
"cat",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
")",
"cat",
".",
"_dtype",
"=",
"new_dtype",
"cat",
".",
"_codes",
"=",
"coerce_indexer_dtype",
"(",
"cat",
".",
"_codes",
",",
"new_dtype",
".",
"categories",
")",
"if",
"not",
"inplace",
":",
"return",
"cat"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.remove_categories | Remove the specified categories.
`removals` must be included in the old categories. Values which were in
the removed categories will be set to NaN
Parameters
----------
removals : category or list of categories
The categories which should be removed.
inplace : bool, default False
Whether or not to remove the categories inplace or return a copy of
this categorical with removed categories.
Returns
-------
cat : Categorical with removed categories or None if inplace.
Raises
------
ValueError
If the removals are not contained in the categories
See Also
--------
rename_categories
reorder_categories
add_categories
remove_unused_categories
set_categories | pandas/core/arrays/categorical.py | def remove_categories(self, removals, inplace=False):
"""
Remove the specified categories.
`removals` must be included in the old categories. Values which were in
the removed categories will be set to NaN
Parameters
----------
removals : category or list of categories
The categories which should be removed.
inplace : bool, default False
Whether or not to remove the categories inplace or return a copy of
this categorical with removed categories.
Returns
-------
cat : Categorical with removed categories or None if inplace.
Raises
------
ValueError
If the removals are not contained in the categories
See Also
--------
rename_categories
reorder_categories
add_categories
remove_unused_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if not is_list_like(removals):
removals = [removals]
removal_set = set(list(removals))
not_included = removal_set - set(self.dtype.categories)
new_categories = [c for c in self.dtype.categories
if c not in removal_set]
# GH 10156
if any(isna(removals)):
not_included = [x for x in not_included if notna(x)]
new_categories = [x for x in new_categories if notna(x)]
if len(not_included) != 0:
msg = "removals must all be in old categories: {not_included!s}"
raise ValueError(msg.format(not_included=not_included))
return self.set_categories(new_categories, ordered=self.ordered,
rename=False, inplace=inplace) | def remove_categories(self, removals, inplace=False):
"""
Remove the specified categories.
`removals` must be included in the old categories. Values which were in
the removed categories will be set to NaN
Parameters
----------
removals : category or list of categories
The categories which should be removed.
inplace : bool, default False
Whether or not to remove the categories inplace or return a copy of
this categorical with removed categories.
Returns
-------
cat : Categorical with removed categories or None if inplace.
Raises
------
ValueError
If the removals are not contained in the categories
See Also
--------
rename_categories
reorder_categories
add_categories
remove_unused_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if not is_list_like(removals):
removals = [removals]
removal_set = set(list(removals))
not_included = removal_set - set(self.dtype.categories)
new_categories = [c for c in self.dtype.categories
if c not in removal_set]
# GH 10156
if any(isna(removals)):
not_included = [x for x in not_included if notna(x)]
new_categories = [x for x in new_categories if notna(x)]
if len(not_included) != 0:
msg = "removals must all be in old categories: {not_included!s}"
raise ValueError(msg.format(not_included=not_included))
return self.set_categories(new_categories, ordered=self.ordered,
rename=False, inplace=inplace) | [
"Remove",
"the",
"specified",
"categories",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1035-L1086 | [
"def",
"remove_categories",
"(",
"self",
",",
"removals",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"not",
"is_list_like",
"(",
"removals",
")",
":",
"removals",
"=",
"[",
"removals",
"]",
"removal_set",
"=",
"set",
"(",
"list",
"(",
"removals",
")",
")",
"not_included",
"=",
"removal_set",
"-",
"set",
"(",
"self",
".",
"dtype",
".",
"categories",
")",
"new_categories",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"dtype",
".",
"categories",
"if",
"c",
"not",
"in",
"removal_set",
"]",
"# GH 10156",
"if",
"any",
"(",
"isna",
"(",
"removals",
")",
")",
":",
"not_included",
"=",
"[",
"x",
"for",
"x",
"in",
"not_included",
"if",
"notna",
"(",
"x",
")",
"]",
"new_categories",
"=",
"[",
"x",
"for",
"x",
"in",
"new_categories",
"if",
"notna",
"(",
"x",
")",
"]",
"if",
"len",
"(",
"not_included",
")",
"!=",
"0",
":",
"msg",
"=",
"\"removals must all be in old categories: {not_included!s}\"",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"not_included",
"=",
"not_included",
")",
")",
"return",
"self",
".",
"set_categories",
"(",
"new_categories",
",",
"ordered",
"=",
"self",
".",
"ordered",
",",
"rename",
"=",
"False",
",",
"inplace",
"=",
"inplace",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.remove_unused_categories | Remove categories which are not used.
Parameters
----------
inplace : bool, default False
Whether or not to drop unused categories inplace or return a copy of
this categorical with unused categories dropped.
Returns
-------
cat : Categorical with unused categories dropped or None if inplace.
See Also
--------
rename_categories
reorder_categories
add_categories
remove_categories
set_categories | pandas/core/arrays/categorical.py | def remove_unused_categories(self, inplace=False):
"""
Remove categories which are not used.
Parameters
----------
inplace : bool, default False
Whether or not to drop unused categories inplace or return a copy of
this categorical with unused categories dropped.
Returns
-------
cat : Categorical with unused categories dropped or None if inplace.
See Also
--------
rename_categories
reorder_categories
add_categories
remove_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
cat = self if inplace else self.copy()
idx, inv = np.unique(cat._codes, return_inverse=True)
if idx.size != 0 and idx[0] == -1: # na sentinel
idx, inv = idx[1:], inv - 1
new_categories = cat.dtype.categories.take(idx)
new_dtype = CategoricalDtype._from_fastpath(new_categories,
ordered=self.ordered)
cat._dtype = new_dtype
cat._codes = coerce_indexer_dtype(inv, new_dtype.categories)
if not inplace:
return cat | def remove_unused_categories(self, inplace=False):
"""
Remove categories which are not used.
Parameters
----------
inplace : bool, default False
Whether or not to drop unused categories inplace or return a copy of
this categorical with unused categories dropped.
Returns
-------
cat : Categorical with unused categories dropped or None if inplace.
See Also
--------
rename_categories
reorder_categories
add_categories
remove_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
cat = self if inplace else self.copy()
idx, inv = np.unique(cat._codes, return_inverse=True)
if idx.size != 0 and idx[0] == -1: # na sentinel
idx, inv = idx[1:], inv - 1
new_categories = cat.dtype.categories.take(idx)
new_dtype = CategoricalDtype._from_fastpath(new_categories,
ordered=self.ordered)
cat._dtype = new_dtype
cat._codes = coerce_indexer_dtype(inv, new_dtype.categories)
if not inplace:
return cat | [
"Remove",
"categories",
"which",
"are",
"not",
"used",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1088-L1124 | [
"def",
"remove_unused_categories",
"(",
"self",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"cat",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
")",
"idx",
",",
"inv",
"=",
"np",
".",
"unique",
"(",
"cat",
".",
"_codes",
",",
"return_inverse",
"=",
"True",
")",
"if",
"idx",
".",
"size",
"!=",
"0",
"and",
"idx",
"[",
"0",
"]",
"==",
"-",
"1",
":",
"# na sentinel",
"idx",
",",
"inv",
"=",
"idx",
"[",
"1",
":",
"]",
",",
"inv",
"-",
"1",
"new_categories",
"=",
"cat",
".",
"dtype",
".",
"categories",
".",
"take",
"(",
"idx",
")",
"new_dtype",
"=",
"CategoricalDtype",
".",
"_from_fastpath",
"(",
"new_categories",
",",
"ordered",
"=",
"self",
".",
"ordered",
")",
"cat",
".",
"_dtype",
"=",
"new_dtype",
"cat",
".",
"_codes",
"=",
"coerce_indexer_dtype",
"(",
"inv",
",",
"new_dtype",
".",
"categories",
")",
"if",
"not",
"inplace",
":",
"return",
"cat"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.map | Map categories using input correspondence (dict, Series, or function).
Maps the categories to new categories. If the mapping correspondence is
one-to-one the result is a :class:`~pandas.Categorical` which has the
same order property as the original, otherwise a :class:`~pandas.Index`
is returned. NaN values are unaffected.
If a `dict` or :class:`~pandas.Series` is used any unmapped category is
mapped to `NaN`. Note that if this happens an :class:`~pandas.Index`
will be returned.
Parameters
----------
mapper : function, dict, or Series
Mapping correspondence.
Returns
-------
pandas.Categorical or pandas.Index
Mapped categorical.
See Also
--------
CategoricalIndex.map : Apply a mapping correspondence on a
:class:`~pandas.CategoricalIndex`.
Index.map : Apply a mapping correspondence on an
:class:`~pandas.Index`.
Series.map : Apply a mapping correspondence on a
:class:`~pandas.Series`.
Series.apply : Apply more complex functions on a
:class:`~pandas.Series`.
Examples
--------
>>> cat = pd.Categorical(['a', 'b', 'c'])
>>> cat
[a, b, c]
Categories (3, object): [a, b, c]
>>> cat.map(lambda x: x.upper())
[A, B, C]
Categories (3, object): [A, B, C]
>>> cat.map({'a': 'first', 'b': 'second', 'c': 'third'})
[first, second, third]
Categories (3, object): [first, second, third]
If the mapping is one-to-one the ordering of the categories is
preserved:
>>> cat = pd.Categorical(['a', 'b', 'c'], ordered=True)
>>> cat
[a, b, c]
Categories (3, object): [a < b < c]
>>> cat.map({'a': 3, 'b': 2, 'c': 1})
[3, 2, 1]
Categories (3, int64): [3 < 2 < 1]
If the mapping is not one-to-one an :class:`~pandas.Index` is returned:
>>> cat.map({'a': 'first', 'b': 'second', 'c': 'first'})
Index(['first', 'second', 'first'], dtype='object')
If a `dict` is used, all unmapped categories are mapped to `NaN` and
the result is an :class:`~pandas.Index`:
>>> cat.map({'a': 'first', 'b': 'second'})
Index(['first', 'second', nan], dtype='object') | pandas/core/arrays/categorical.py | def map(self, mapper):
"""
Map categories using input correspondence (dict, Series, or function).
Maps the categories to new categories. If the mapping correspondence is
one-to-one the result is a :class:`~pandas.Categorical` which has the
same order property as the original, otherwise a :class:`~pandas.Index`
is returned. NaN values are unaffected.
If a `dict` or :class:`~pandas.Series` is used any unmapped category is
mapped to `NaN`. Note that if this happens an :class:`~pandas.Index`
will be returned.
Parameters
----------
mapper : function, dict, or Series
Mapping correspondence.
Returns
-------
pandas.Categorical or pandas.Index
Mapped categorical.
See Also
--------
CategoricalIndex.map : Apply a mapping correspondence on a
:class:`~pandas.CategoricalIndex`.
Index.map : Apply a mapping correspondence on an
:class:`~pandas.Index`.
Series.map : Apply a mapping correspondence on a
:class:`~pandas.Series`.
Series.apply : Apply more complex functions on a
:class:`~pandas.Series`.
Examples
--------
>>> cat = pd.Categorical(['a', 'b', 'c'])
>>> cat
[a, b, c]
Categories (3, object): [a, b, c]
>>> cat.map(lambda x: x.upper())
[A, B, C]
Categories (3, object): [A, B, C]
>>> cat.map({'a': 'first', 'b': 'second', 'c': 'third'})
[first, second, third]
Categories (3, object): [first, second, third]
If the mapping is one-to-one the ordering of the categories is
preserved:
>>> cat = pd.Categorical(['a', 'b', 'c'], ordered=True)
>>> cat
[a, b, c]
Categories (3, object): [a < b < c]
>>> cat.map({'a': 3, 'b': 2, 'c': 1})
[3, 2, 1]
Categories (3, int64): [3 < 2 < 1]
If the mapping is not one-to-one an :class:`~pandas.Index` is returned:
>>> cat.map({'a': 'first', 'b': 'second', 'c': 'first'})
Index(['first', 'second', 'first'], dtype='object')
If a `dict` is used, all unmapped categories are mapped to `NaN` and
the result is an :class:`~pandas.Index`:
>>> cat.map({'a': 'first', 'b': 'second'})
Index(['first', 'second', nan], dtype='object')
"""
new_categories = self.categories.map(mapper)
try:
return self.from_codes(self._codes.copy(),
categories=new_categories,
ordered=self.ordered)
except ValueError:
# NA values are represented in self._codes with -1
# np.take causes NA values to take final element in new_categories
if np.any(self._codes == -1):
new_categories = new_categories.insert(len(new_categories),
np.nan)
return np.take(new_categories, self._codes) | def map(self, mapper):
"""
Map categories using input correspondence (dict, Series, or function).
Maps the categories to new categories. If the mapping correspondence is
one-to-one the result is a :class:`~pandas.Categorical` which has the
same order property as the original, otherwise a :class:`~pandas.Index`
is returned. NaN values are unaffected.
If a `dict` or :class:`~pandas.Series` is used any unmapped category is
mapped to `NaN`. Note that if this happens an :class:`~pandas.Index`
will be returned.
Parameters
----------
mapper : function, dict, or Series
Mapping correspondence.
Returns
-------
pandas.Categorical or pandas.Index
Mapped categorical.
See Also
--------
CategoricalIndex.map : Apply a mapping correspondence on a
:class:`~pandas.CategoricalIndex`.
Index.map : Apply a mapping correspondence on an
:class:`~pandas.Index`.
Series.map : Apply a mapping correspondence on a
:class:`~pandas.Series`.
Series.apply : Apply more complex functions on a
:class:`~pandas.Series`.
Examples
--------
>>> cat = pd.Categorical(['a', 'b', 'c'])
>>> cat
[a, b, c]
Categories (3, object): [a, b, c]
>>> cat.map(lambda x: x.upper())
[A, B, C]
Categories (3, object): [A, B, C]
>>> cat.map({'a': 'first', 'b': 'second', 'c': 'third'})
[first, second, third]
Categories (3, object): [first, second, third]
If the mapping is one-to-one the ordering of the categories is
preserved:
>>> cat = pd.Categorical(['a', 'b', 'c'], ordered=True)
>>> cat
[a, b, c]
Categories (3, object): [a < b < c]
>>> cat.map({'a': 3, 'b': 2, 'c': 1})
[3, 2, 1]
Categories (3, int64): [3 < 2 < 1]
If the mapping is not one-to-one an :class:`~pandas.Index` is returned:
>>> cat.map({'a': 'first', 'b': 'second', 'c': 'first'})
Index(['first', 'second', 'first'], dtype='object')
If a `dict` is used, all unmapped categories are mapped to `NaN` and
the result is an :class:`~pandas.Index`:
>>> cat.map({'a': 'first', 'b': 'second'})
Index(['first', 'second', nan], dtype='object')
"""
new_categories = self.categories.map(mapper)
try:
return self.from_codes(self._codes.copy(),
categories=new_categories,
ordered=self.ordered)
except ValueError:
# NA values are represented in self._codes with -1
# np.take causes NA values to take final element in new_categories
if np.any(self._codes == -1):
new_categories = new_categories.insert(len(new_categories),
np.nan)
return np.take(new_categories, self._codes) | [
"Map",
"categories",
"using",
"input",
"correspondence",
"(",
"dict",
"Series",
"or",
"function",
")",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1126-L1206 | [
"def",
"map",
"(",
"self",
",",
"mapper",
")",
":",
"new_categories",
"=",
"self",
".",
"categories",
".",
"map",
"(",
"mapper",
")",
"try",
":",
"return",
"self",
".",
"from_codes",
"(",
"self",
".",
"_codes",
".",
"copy",
"(",
")",
",",
"categories",
"=",
"new_categories",
",",
"ordered",
"=",
"self",
".",
"ordered",
")",
"except",
"ValueError",
":",
"# NA values are represented in self._codes with -1",
"# np.take causes NA values to take final element in new_categories",
"if",
"np",
".",
"any",
"(",
"self",
".",
"_codes",
"==",
"-",
"1",
")",
":",
"new_categories",
"=",
"new_categories",
".",
"insert",
"(",
"len",
"(",
"new_categories",
")",
",",
"np",
".",
"nan",
")",
"return",
"np",
".",
"take",
"(",
"new_categories",
",",
"self",
".",
"_codes",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.shift | Shift Categorical by desired number of periods.
Parameters
----------
periods : int
Number of periods to move, can be positive or negative
fill_value : object, optional
The scalar value to use for newly introduced missing values.
.. versionadded:: 0.24.0
Returns
-------
shifted : Categorical | pandas/core/arrays/categorical.py | def shift(self, periods, fill_value=None):
"""
Shift Categorical by desired number of periods.
Parameters
----------
periods : int
Number of periods to move, can be positive or negative
fill_value : object, optional
The scalar value to use for newly introduced missing values.
.. versionadded:: 0.24.0
Returns
-------
shifted : Categorical
"""
# since categoricals always have ndim == 1, an axis parameter
# doesn't make any sense here.
codes = self.codes
if codes.ndim > 1:
raise NotImplementedError("Categorical with ndim > 1.")
if np.prod(codes.shape) and (periods != 0):
codes = np.roll(codes, ensure_platform_int(periods), axis=0)
if isna(fill_value):
fill_value = -1
elif fill_value in self.categories:
fill_value = self.categories.get_loc(fill_value)
else:
raise ValueError("'fill_value={}' is not present "
"in this Categorical's "
"categories".format(fill_value))
if periods > 0:
codes[:periods] = fill_value
else:
codes[periods:] = fill_value
return self.from_codes(codes, dtype=self.dtype) | def shift(self, periods, fill_value=None):
"""
Shift Categorical by desired number of periods.
Parameters
----------
periods : int
Number of periods to move, can be positive or negative
fill_value : object, optional
The scalar value to use for newly introduced missing values.
.. versionadded:: 0.24.0
Returns
-------
shifted : Categorical
"""
# since categoricals always have ndim == 1, an axis parameter
# doesn't make any sense here.
codes = self.codes
if codes.ndim > 1:
raise NotImplementedError("Categorical with ndim > 1.")
if np.prod(codes.shape) and (periods != 0):
codes = np.roll(codes, ensure_platform_int(periods), axis=0)
if isna(fill_value):
fill_value = -1
elif fill_value in self.categories:
fill_value = self.categories.get_loc(fill_value)
else:
raise ValueError("'fill_value={}' is not present "
"in this Categorical's "
"categories".format(fill_value))
if periods > 0:
codes[:periods] = fill_value
else:
codes[periods:] = fill_value
return self.from_codes(codes, dtype=self.dtype) | [
"Shift",
"Categorical",
"by",
"desired",
"number",
"of",
"periods",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1230-L1267 | [
"def",
"shift",
"(",
"self",
",",
"periods",
",",
"fill_value",
"=",
"None",
")",
":",
"# since categoricals always have ndim == 1, an axis parameter",
"# doesn't make any sense here.",
"codes",
"=",
"self",
".",
"codes",
"if",
"codes",
".",
"ndim",
">",
"1",
":",
"raise",
"NotImplementedError",
"(",
"\"Categorical with ndim > 1.\"",
")",
"if",
"np",
".",
"prod",
"(",
"codes",
".",
"shape",
")",
"and",
"(",
"periods",
"!=",
"0",
")",
":",
"codes",
"=",
"np",
".",
"roll",
"(",
"codes",
",",
"ensure_platform_int",
"(",
"periods",
")",
",",
"axis",
"=",
"0",
")",
"if",
"isna",
"(",
"fill_value",
")",
":",
"fill_value",
"=",
"-",
"1",
"elif",
"fill_value",
"in",
"self",
".",
"categories",
":",
"fill_value",
"=",
"self",
".",
"categories",
".",
"get_loc",
"(",
"fill_value",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"'fill_value={}' is not present \"",
"\"in this Categorical's \"",
"\"categories\"",
".",
"format",
"(",
"fill_value",
")",
")",
"if",
"periods",
">",
"0",
":",
"codes",
"[",
":",
"periods",
"]",
"=",
"fill_value",
"else",
":",
"codes",
"[",
"periods",
":",
"]",
"=",
"fill_value",
"return",
"self",
".",
"from_codes",
"(",
"codes",
",",
"dtype",
"=",
"self",
".",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.memory_usage | Memory usage of my values
Parameters
----------
deep : bool
Introspect the data deeply, interrogate
`object` dtypes for system-level memory consumption
Returns
-------
bytes used
Notes
-----
Memory usage does not include memory consumed by elements that
are not components of the array if deep=False
See Also
--------
numpy.ndarray.nbytes | pandas/core/arrays/categorical.py | def memory_usage(self, deep=False):
"""
Memory usage of my values
Parameters
----------
deep : bool
Introspect the data deeply, interrogate
`object` dtypes for system-level memory consumption
Returns
-------
bytes used
Notes
-----
Memory usage does not include memory consumed by elements that
are not components of the array if deep=False
See Also
--------
numpy.ndarray.nbytes
"""
return self._codes.nbytes + self.dtype.categories.memory_usage(
deep=deep) | def memory_usage(self, deep=False):
"""
Memory usage of my values
Parameters
----------
deep : bool
Introspect the data deeply, interrogate
`object` dtypes for system-level memory consumption
Returns
-------
bytes used
Notes
-----
Memory usage does not include memory consumed by elements that
are not components of the array if deep=False
See Also
--------
numpy.ndarray.nbytes
"""
return self._codes.nbytes + self.dtype.categories.memory_usage(
deep=deep) | [
"Memory",
"usage",
"of",
"my",
"values"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1331-L1355 | [
"def",
"memory_usage",
"(",
"self",
",",
"deep",
"=",
"False",
")",
":",
"return",
"self",
".",
"_codes",
".",
"nbytes",
"+",
"self",
".",
"dtype",
".",
"categories",
".",
"memory_usage",
"(",
"deep",
"=",
"deep",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.value_counts | Return a Series containing counts of each category.
Every category will have an entry, even those with a count of 0.
Parameters
----------
dropna : bool, default True
Don't include counts of NaN.
Returns
-------
counts : Series
See Also
--------
Series.value_counts | pandas/core/arrays/categorical.py | def value_counts(self, dropna=True):
"""
Return a Series containing counts of each category.
Every category will have an entry, even those with a count of 0.
Parameters
----------
dropna : bool, default True
Don't include counts of NaN.
Returns
-------
counts : Series
See Also
--------
Series.value_counts
"""
from numpy import bincount
from pandas import Series, CategoricalIndex
code, cat = self._codes, self.categories
ncat, mask = len(cat), 0 <= code
ix, clean = np.arange(ncat), mask.all()
if dropna or clean:
obs = code if clean else code[mask]
count = bincount(obs, minlength=ncat or None)
else:
count = bincount(np.where(mask, code, ncat))
ix = np.append(ix, -1)
ix = self._constructor(ix, dtype=self.dtype,
fastpath=True)
return Series(count, index=CategoricalIndex(ix), dtype='int64') | def value_counts(self, dropna=True):
"""
Return a Series containing counts of each category.
Every category will have an entry, even those with a count of 0.
Parameters
----------
dropna : bool, default True
Don't include counts of NaN.
Returns
-------
counts : Series
See Also
--------
Series.value_counts
"""
from numpy import bincount
from pandas import Series, CategoricalIndex
code, cat = self._codes, self.categories
ncat, mask = len(cat), 0 <= code
ix, clean = np.arange(ncat), mask.all()
if dropna or clean:
obs = code if clean else code[mask]
count = bincount(obs, minlength=ncat or None)
else:
count = bincount(np.where(mask, code, ncat))
ix = np.append(ix, -1)
ix = self._constructor(ix, dtype=self.dtype,
fastpath=True)
return Series(count, index=CategoricalIndex(ix), dtype='int64') | [
"Return",
"a",
"Series",
"containing",
"counts",
"of",
"each",
"category",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1438-L1475 | [
"def",
"value_counts",
"(",
"self",
",",
"dropna",
"=",
"True",
")",
":",
"from",
"numpy",
"import",
"bincount",
"from",
"pandas",
"import",
"Series",
",",
"CategoricalIndex",
"code",
",",
"cat",
"=",
"self",
".",
"_codes",
",",
"self",
".",
"categories",
"ncat",
",",
"mask",
"=",
"len",
"(",
"cat",
")",
",",
"0",
"<=",
"code",
"ix",
",",
"clean",
"=",
"np",
".",
"arange",
"(",
"ncat",
")",
",",
"mask",
".",
"all",
"(",
")",
"if",
"dropna",
"or",
"clean",
":",
"obs",
"=",
"code",
"if",
"clean",
"else",
"code",
"[",
"mask",
"]",
"count",
"=",
"bincount",
"(",
"obs",
",",
"minlength",
"=",
"ncat",
"or",
"None",
")",
"else",
":",
"count",
"=",
"bincount",
"(",
"np",
".",
"where",
"(",
"mask",
",",
"code",
",",
"ncat",
")",
")",
"ix",
"=",
"np",
".",
"append",
"(",
"ix",
",",
"-",
"1",
")",
"ix",
"=",
"self",
".",
"_constructor",
"(",
"ix",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"fastpath",
"=",
"True",
")",
"return",
"Series",
"(",
"count",
",",
"index",
"=",
"CategoricalIndex",
"(",
"ix",
")",
",",
"dtype",
"=",
"'int64'",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.get_values | Return the values.
For internal compatibility with pandas formatting.
Returns
-------
numpy.array
A numpy array of the same dtype as categorical.categories.dtype or
Index if datetime / periods. | pandas/core/arrays/categorical.py | def get_values(self):
"""
Return the values.
For internal compatibility with pandas formatting.
Returns
-------
numpy.array
A numpy array of the same dtype as categorical.categories.dtype or
Index if datetime / periods.
"""
# if we are a datetime and period index, return Index to keep metadata
if is_datetimelike(self.categories):
return self.categories.take(self._codes, fill_value=np.nan)
elif is_integer_dtype(self.categories) and -1 in self._codes:
return self.categories.astype("object").take(self._codes,
fill_value=np.nan)
return np.array(self) | def get_values(self):
"""
Return the values.
For internal compatibility with pandas formatting.
Returns
-------
numpy.array
A numpy array of the same dtype as categorical.categories.dtype or
Index if datetime / periods.
"""
# if we are a datetime and period index, return Index to keep metadata
if is_datetimelike(self.categories):
return self.categories.take(self._codes, fill_value=np.nan)
elif is_integer_dtype(self.categories) and -1 in self._codes:
return self.categories.astype("object").take(self._codes,
fill_value=np.nan)
return np.array(self) | [
"Return",
"the",
"values",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1477-L1495 | [
"def",
"get_values",
"(",
"self",
")",
":",
"# if we are a datetime and period index, return Index to keep metadata",
"if",
"is_datetimelike",
"(",
"self",
".",
"categories",
")",
":",
"return",
"self",
".",
"categories",
".",
"take",
"(",
"self",
".",
"_codes",
",",
"fill_value",
"=",
"np",
".",
"nan",
")",
"elif",
"is_integer_dtype",
"(",
"self",
".",
"categories",
")",
"and",
"-",
"1",
"in",
"self",
".",
"_codes",
":",
"return",
"self",
".",
"categories",
".",
"astype",
"(",
"\"object\"",
")",
".",
"take",
"(",
"self",
".",
"_codes",
",",
"fill_value",
"=",
"np",
".",
"nan",
")",
"return",
"np",
".",
"array",
"(",
"self",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.sort_values | Sort the Categorical by category value returning a new
Categorical by default.
While an ordering is applied to the category values, sorting in this
context refers more to organizing and grouping together based on
matching category values. Thus, this function can be called on an
unordered Categorical instance unlike the functions 'Categorical.min'
and 'Categorical.max'.
Parameters
----------
inplace : bool, default False
Do operation in place.
ascending : bool, default True
Order ascending. Passing False orders descending. The
ordering parameter provides the method by which the
category values are organized.
na_position : {'first', 'last'} (optional, default='last')
'first' puts NaNs at the beginning
'last' puts NaNs at the end
Returns
-------
Categorical or None
See Also
--------
Categorical.sort
Series.sort_values
Examples
--------
>>> c = pd.Categorical([1, 2, 2, 1, 5])
>>> c
[1, 2, 2, 1, 5]
Categories (3, int64): [1, 2, 5]
>>> c.sort_values()
[1, 1, 2, 2, 5]
Categories (3, int64): [1, 2, 5]
>>> c.sort_values(ascending=False)
[5, 2, 2, 1, 1]
Categories (3, int64): [1, 2, 5]
Inplace sorting can be done as well:
>>> c.sort_values(inplace=True)
>>> c
[1, 1, 2, 2, 5]
Categories (3, int64): [1, 2, 5]
>>>
>>> c = pd.Categorical([1, 2, 2, 1, 5])
'sort_values' behaviour with NaNs. Note that 'na_position'
is independent of the 'ascending' parameter:
>>> c = pd.Categorical([np.nan, 2, 2, np.nan, 5])
>>> c
[NaN, 2.0, 2.0, NaN, 5.0]
Categories (2, int64): [2, 5]
>>> c.sort_values()
[2.0, 2.0, 5.0, NaN, NaN]
Categories (2, int64): [2, 5]
>>> c.sort_values(ascending=False)
[5.0, 2.0, 2.0, NaN, NaN]
Categories (2, int64): [2, 5]
>>> c.sort_values(na_position='first')
[NaN, NaN, 2.0, 2.0, 5.0]
Categories (2, int64): [2, 5]
>>> c.sort_values(ascending=False, na_position='first')
[NaN, NaN, 5.0, 2.0, 2.0]
Categories (2, int64): [2, 5] | pandas/core/arrays/categorical.py | def sort_values(self, inplace=False, ascending=True, na_position='last'):
"""
Sort the Categorical by category value returning a new
Categorical by default.
While an ordering is applied to the category values, sorting in this
context refers more to organizing and grouping together based on
matching category values. Thus, this function can be called on an
unordered Categorical instance unlike the functions 'Categorical.min'
and 'Categorical.max'.
Parameters
----------
inplace : bool, default False
Do operation in place.
ascending : bool, default True
Order ascending. Passing False orders descending. The
ordering parameter provides the method by which the
category values are organized.
na_position : {'first', 'last'} (optional, default='last')
'first' puts NaNs at the beginning
'last' puts NaNs at the end
Returns
-------
Categorical or None
See Also
--------
Categorical.sort
Series.sort_values
Examples
--------
>>> c = pd.Categorical([1, 2, 2, 1, 5])
>>> c
[1, 2, 2, 1, 5]
Categories (3, int64): [1, 2, 5]
>>> c.sort_values()
[1, 1, 2, 2, 5]
Categories (3, int64): [1, 2, 5]
>>> c.sort_values(ascending=False)
[5, 2, 2, 1, 1]
Categories (3, int64): [1, 2, 5]
Inplace sorting can be done as well:
>>> c.sort_values(inplace=True)
>>> c
[1, 1, 2, 2, 5]
Categories (3, int64): [1, 2, 5]
>>>
>>> c = pd.Categorical([1, 2, 2, 1, 5])
'sort_values' behaviour with NaNs. Note that 'na_position'
is independent of the 'ascending' parameter:
>>> c = pd.Categorical([np.nan, 2, 2, np.nan, 5])
>>> c
[NaN, 2.0, 2.0, NaN, 5.0]
Categories (2, int64): [2, 5]
>>> c.sort_values()
[2.0, 2.0, 5.0, NaN, NaN]
Categories (2, int64): [2, 5]
>>> c.sort_values(ascending=False)
[5.0, 2.0, 2.0, NaN, NaN]
Categories (2, int64): [2, 5]
>>> c.sort_values(na_position='first')
[NaN, NaN, 2.0, 2.0, 5.0]
Categories (2, int64): [2, 5]
>>> c.sort_values(ascending=False, na_position='first')
[NaN, NaN, 5.0, 2.0, 2.0]
Categories (2, int64): [2, 5]
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if na_position not in ['last', 'first']:
msg = 'invalid na_position: {na_position!r}'
raise ValueError(msg.format(na_position=na_position))
sorted_idx = nargsort(self,
ascending=ascending,
na_position=na_position)
if inplace:
self._codes = self._codes[sorted_idx]
else:
return self._constructor(values=self._codes[sorted_idx],
dtype=self.dtype,
fastpath=True) | def sort_values(self, inplace=False, ascending=True, na_position='last'):
"""
Sort the Categorical by category value returning a new
Categorical by default.
While an ordering is applied to the category values, sorting in this
context refers more to organizing and grouping together based on
matching category values. Thus, this function can be called on an
unordered Categorical instance unlike the functions 'Categorical.min'
and 'Categorical.max'.
Parameters
----------
inplace : bool, default False
Do operation in place.
ascending : bool, default True
Order ascending. Passing False orders descending. The
ordering parameter provides the method by which the
category values are organized.
na_position : {'first', 'last'} (optional, default='last')
'first' puts NaNs at the beginning
'last' puts NaNs at the end
Returns
-------
Categorical or None
See Also
--------
Categorical.sort
Series.sort_values
Examples
--------
>>> c = pd.Categorical([1, 2, 2, 1, 5])
>>> c
[1, 2, 2, 1, 5]
Categories (3, int64): [1, 2, 5]
>>> c.sort_values()
[1, 1, 2, 2, 5]
Categories (3, int64): [1, 2, 5]
>>> c.sort_values(ascending=False)
[5, 2, 2, 1, 1]
Categories (3, int64): [1, 2, 5]
Inplace sorting can be done as well:
>>> c.sort_values(inplace=True)
>>> c
[1, 1, 2, 2, 5]
Categories (3, int64): [1, 2, 5]
>>>
>>> c = pd.Categorical([1, 2, 2, 1, 5])
'sort_values' behaviour with NaNs. Note that 'na_position'
is independent of the 'ascending' parameter:
>>> c = pd.Categorical([np.nan, 2, 2, np.nan, 5])
>>> c
[NaN, 2.0, 2.0, NaN, 5.0]
Categories (2, int64): [2, 5]
>>> c.sort_values()
[2.0, 2.0, 5.0, NaN, NaN]
Categories (2, int64): [2, 5]
>>> c.sort_values(ascending=False)
[5.0, 2.0, 2.0, NaN, NaN]
Categories (2, int64): [2, 5]
>>> c.sort_values(na_position='first')
[NaN, NaN, 2.0, 2.0, 5.0]
Categories (2, int64): [2, 5]
>>> c.sort_values(ascending=False, na_position='first')
[NaN, NaN, 5.0, 2.0, 2.0]
Categories (2, int64): [2, 5]
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if na_position not in ['last', 'first']:
msg = 'invalid na_position: {na_position!r}'
raise ValueError(msg.format(na_position=na_position))
sorted_idx = nargsort(self,
ascending=ascending,
na_position=na_position)
if inplace:
self._codes = self._codes[sorted_idx]
else:
return self._constructor(values=self._codes[sorted_idx],
dtype=self.dtype,
fastpath=True) | [
"Sort",
"the",
"Categorical",
"by",
"category",
"value",
"returning",
"a",
"new",
"Categorical",
"by",
"default",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1554-L1642 | [
"def",
"sort_values",
"(",
"self",
",",
"inplace",
"=",
"False",
",",
"ascending",
"=",
"True",
",",
"na_position",
"=",
"'last'",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"na_position",
"not",
"in",
"[",
"'last'",
",",
"'first'",
"]",
":",
"msg",
"=",
"'invalid na_position: {na_position!r}'",
"raise",
"ValueError",
"(",
"msg",
".",
"format",
"(",
"na_position",
"=",
"na_position",
")",
")",
"sorted_idx",
"=",
"nargsort",
"(",
"self",
",",
"ascending",
"=",
"ascending",
",",
"na_position",
"=",
"na_position",
")",
"if",
"inplace",
":",
"self",
".",
"_codes",
"=",
"self",
".",
"_codes",
"[",
"sorted_idx",
"]",
"else",
":",
"return",
"self",
".",
"_constructor",
"(",
"values",
"=",
"self",
".",
"_codes",
"[",
"sorted_idx",
"]",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._values_for_rank | For correctly ranking ordered categorical data. See GH#15420
Ordered categorical data should be ranked on the basis of
codes with -1 translated to NaN.
Returns
-------
numpy.array | pandas/core/arrays/categorical.py | def _values_for_rank(self):
"""
For correctly ranking ordered categorical data. See GH#15420
Ordered categorical data should be ranked on the basis of
codes with -1 translated to NaN.
Returns
-------
numpy.array
"""
from pandas import Series
if self.ordered:
values = self.codes
mask = values == -1
if mask.any():
values = values.astype('float64')
values[mask] = np.nan
elif self.categories.is_numeric():
values = np.array(self)
else:
# reorder the categories (so rank can use the float codes)
# instead of passing an object array to rank
values = np.array(
self.rename_categories(Series(self.categories).rank().values)
)
return values | def _values_for_rank(self):
"""
For correctly ranking ordered categorical data. See GH#15420
Ordered categorical data should be ranked on the basis of
codes with -1 translated to NaN.
Returns
-------
numpy.array
"""
from pandas import Series
if self.ordered:
values = self.codes
mask = values == -1
if mask.any():
values = values.astype('float64')
values[mask] = np.nan
elif self.categories.is_numeric():
values = np.array(self)
else:
# reorder the categories (so rank can use the float codes)
# instead of passing an object array to rank
values = np.array(
self.rename_categories(Series(self.categories).rank().values)
)
return values | [
"For",
"correctly",
"ranking",
"ordered",
"categorical",
"data",
".",
"See",
"GH#15420"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1644-L1671 | [
"def",
"_values_for_rank",
"(",
"self",
")",
":",
"from",
"pandas",
"import",
"Series",
"if",
"self",
".",
"ordered",
":",
"values",
"=",
"self",
".",
"codes",
"mask",
"=",
"values",
"==",
"-",
"1",
"if",
"mask",
".",
"any",
"(",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"'float64'",
")",
"values",
"[",
"mask",
"]",
"=",
"np",
".",
"nan",
"elif",
"self",
".",
"categories",
".",
"is_numeric",
"(",
")",
":",
"values",
"=",
"np",
".",
"array",
"(",
"self",
")",
"else",
":",
"# reorder the categories (so rank can use the float codes)",
"# instead of passing an object array to rank",
"values",
"=",
"np",
".",
"array",
"(",
"self",
".",
"rename_categories",
"(",
"Series",
"(",
"self",
".",
"categories",
")",
".",
"rank",
"(",
")",
".",
"values",
")",
")",
"return",
"values"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.fillna | Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series
If a scalar value is passed it is used to fill all missing values.
Alternatively, a Series or dict can be used to fill in different
values for each index. The value should not be a list. The
value(s) passed should either be in the categories or should be
NaN.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
limit : int, default None
(Not implemented yet for Categorical!)
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill. In other words, if there is
a gap with more than this number of consecutive NaNs, it will only
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled.
Returns
-------
filled : Categorical with NA/NaN filled | pandas/core/arrays/categorical.py | def fillna(self, value=None, method=None, limit=None):
"""
Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series
If a scalar value is passed it is used to fill all missing values.
Alternatively, a Series or dict can be used to fill in different
values for each index. The value should not be a list. The
value(s) passed should either be in the categories or should be
NaN.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
limit : int, default None
(Not implemented yet for Categorical!)
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill. In other words, if there is
a gap with more than this number of consecutive NaNs, it will only
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled.
Returns
-------
filled : Categorical with NA/NaN filled
"""
value, method = validate_fillna_kwargs(
value, method, validate_scalar_dict_value=False
)
if value is None:
value = np.nan
if limit is not None:
raise NotImplementedError("specifying a limit for fillna has not "
"been implemented yet")
codes = self._codes
# pad / bfill
if method is not None:
values = self.to_dense().reshape(-1, len(self))
values = interpolate_2d(values, method, 0, None,
value).astype(self.categories.dtype)[0]
codes = _get_codes_for_values(values, self.categories)
else:
# If value is a dict or a Series (a dict value has already
# been converted to a Series)
if isinstance(value, ABCSeries):
if not value[~value.isin(self.categories)].isna().all():
raise ValueError("fill value must be in categories")
values_codes = _get_codes_for_values(value, self.categories)
indexer = np.where(values_codes != -1)
codes[indexer] = values_codes[values_codes != -1]
# If value is not a dict or Series it should be a scalar
elif is_hashable(value):
if not isna(value) and value not in self.categories:
raise ValueError("fill value must be in categories")
mask = codes == -1
if mask.any():
codes = codes.copy()
if isna(value):
codes[mask] = -1
else:
codes[mask] = self.categories.get_loc(value)
else:
raise TypeError('"value" parameter must be a scalar, dict '
'or Series, but you passed a '
'"{0}"'.format(type(value).__name__))
return self._constructor(codes, dtype=self.dtype, fastpath=True) | def fillna(self, value=None, method=None, limit=None):
"""
Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series
If a scalar value is passed it is used to fill all missing values.
Alternatively, a Series or dict can be used to fill in different
values for each index. The value should not be a list. The
value(s) passed should either be in the categories or should be
NaN.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
limit : int, default None
(Not implemented yet for Categorical!)
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill. In other words, if there is
a gap with more than this number of consecutive NaNs, it will only
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled.
Returns
-------
filled : Categorical with NA/NaN filled
"""
value, method = validate_fillna_kwargs(
value, method, validate_scalar_dict_value=False
)
if value is None:
value = np.nan
if limit is not None:
raise NotImplementedError("specifying a limit for fillna has not "
"been implemented yet")
codes = self._codes
# pad / bfill
if method is not None:
values = self.to_dense().reshape(-1, len(self))
values = interpolate_2d(values, method, 0, None,
value).astype(self.categories.dtype)[0]
codes = _get_codes_for_values(values, self.categories)
else:
# If value is a dict or a Series (a dict value has already
# been converted to a Series)
if isinstance(value, ABCSeries):
if not value[~value.isin(self.categories)].isna().all():
raise ValueError("fill value must be in categories")
values_codes = _get_codes_for_values(value, self.categories)
indexer = np.where(values_codes != -1)
codes[indexer] = values_codes[values_codes != -1]
# If value is not a dict or Series it should be a scalar
elif is_hashable(value):
if not isna(value) and value not in self.categories:
raise ValueError("fill value must be in categories")
mask = codes == -1
if mask.any():
codes = codes.copy()
if isna(value):
codes[mask] = -1
else:
codes[mask] = self.categories.get_loc(value)
else:
raise TypeError('"value" parameter must be a scalar, dict '
'or Series, but you passed a '
'"{0}"'.format(type(value).__name__))
return self._constructor(codes, dtype=self.dtype, fastpath=True) | [
"Fill",
"NA",
"/",
"NaN",
"values",
"using",
"the",
"specified",
"method",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1711-L1790 | [
"def",
"fillna",
"(",
"self",
",",
"value",
"=",
"None",
",",
"method",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"value",
",",
"method",
"=",
"validate_fillna_kwargs",
"(",
"value",
",",
"method",
",",
"validate_scalar_dict_value",
"=",
"False",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"np",
".",
"nan",
"if",
"limit",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"specifying a limit for fillna has not \"",
"\"been implemented yet\"",
")",
"codes",
"=",
"self",
".",
"_codes",
"# pad / bfill",
"if",
"method",
"is",
"not",
"None",
":",
"values",
"=",
"self",
".",
"to_dense",
"(",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"len",
"(",
"self",
")",
")",
"values",
"=",
"interpolate_2d",
"(",
"values",
",",
"method",
",",
"0",
",",
"None",
",",
"value",
")",
".",
"astype",
"(",
"self",
".",
"categories",
".",
"dtype",
")",
"[",
"0",
"]",
"codes",
"=",
"_get_codes_for_values",
"(",
"values",
",",
"self",
".",
"categories",
")",
"else",
":",
"# If value is a dict or a Series (a dict value has already",
"# been converted to a Series)",
"if",
"isinstance",
"(",
"value",
",",
"ABCSeries",
")",
":",
"if",
"not",
"value",
"[",
"~",
"value",
".",
"isin",
"(",
"self",
".",
"categories",
")",
"]",
".",
"isna",
"(",
")",
".",
"all",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"fill value must be in categories\"",
")",
"values_codes",
"=",
"_get_codes_for_values",
"(",
"value",
",",
"self",
".",
"categories",
")",
"indexer",
"=",
"np",
".",
"where",
"(",
"values_codes",
"!=",
"-",
"1",
")",
"codes",
"[",
"indexer",
"]",
"=",
"values_codes",
"[",
"values_codes",
"!=",
"-",
"1",
"]",
"# If value is not a dict or Series it should be a scalar",
"elif",
"is_hashable",
"(",
"value",
")",
":",
"if",
"not",
"isna",
"(",
"value",
")",
"and",
"value",
"not",
"in",
"self",
".",
"categories",
":",
"raise",
"ValueError",
"(",
"\"fill value must be in categories\"",
")",
"mask",
"=",
"codes",
"==",
"-",
"1",
"if",
"mask",
".",
"any",
"(",
")",
":",
"codes",
"=",
"codes",
".",
"copy",
"(",
")",
"if",
"isna",
"(",
"value",
")",
":",
"codes",
"[",
"mask",
"]",
"=",
"-",
"1",
"else",
":",
"codes",
"[",
"mask",
"]",
"=",
"self",
".",
"categories",
".",
"get_loc",
"(",
"value",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'\"value\" parameter must be a scalar, dict '",
"'or Series, but you passed a '",
"'\"{0}\"'",
".",
"format",
"(",
"type",
"(",
"value",
")",
".",
"__name__",
")",
")",
"return",
"self",
".",
"_constructor",
"(",
"codes",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.take_nd | Take elements from the Categorical.
Parameters
----------
indexer : sequence of int
The indices in `self` to take. The meaning of negative values in
`indexer` depends on the value of `allow_fill`.
allow_fill : bool, default None
How to handle negative values in `indexer`.
* False: negative values in `indices` indicate positional indices
from the right. This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate missing values
(the default). These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
.. versionchanged:: 0.23.0
Deprecated the default value of `allow_fill`. The deprecated
default is ``True``. In the future, this will change to
``False``.
fill_value : object
The value to use for `indices` that are missing (-1), when
``allow_fill=True``. This should be the category, i.e. a value
in ``self.categories``, not a code.
Returns
-------
Categorical
This Categorical will have the same categories and ordered as
`self`.
See Also
--------
Series.take : Similar method for Series.
numpy.ndarray.take : Similar method for NumPy arrays.
Examples
--------
>>> cat = pd.Categorical(['a', 'a', 'b'])
>>> cat
[a, a, b]
Categories (2, object): [a, b]
Specify ``allow_fill==False`` to have negative indices mean indexing
from the right.
>>> cat.take([0, -1, -2], allow_fill=False)
[a, b, a]
Categories (2, object): [a, b]
With ``allow_fill=True``, indices equal to ``-1`` mean "missing"
values that should be filled with the `fill_value`, which is
``np.nan`` by default.
>>> cat.take([0, -1, -1], allow_fill=True)
[a, NaN, NaN]
Categories (2, object): [a, b]
The fill value can be specified.
>>> cat.take([0, -1, -1], allow_fill=True, fill_value='a')
[a, a, a]
Categories (3, object): [a, b]
Specifying a fill value that's not in ``self.categories``
will raise a ``TypeError``. | pandas/core/arrays/categorical.py | def take_nd(self, indexer, allow_fill=None, fill_value=None):
"""
Take elements from the Categorical.
Parameters
----------
indexer : sequence of int
The indices in `self` to take. The meaning of negative values in
`indexer` depends on the value of `allow_fill`.
allow_fill : bool, default None
How to handle negative values in `indexer`.
* False: negative values in `indices` indicate positional indices
from the right. This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate missing values
(the default). These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
.. versionchanged:: 0.23.0
Deprecated the default value of `allow_fill`. The deprecated
default is ``True``. In the future, this will change to
``False``.
fill_value : object
The value to use for `indices` that are missing (-1), when
``allow_fill=True``. This should be the category, i.e. a value
in ``self.categories``, not a code.
Returns
-------
Categorical
This Categorical will have the same categories and ordered as
`self`.
See Also
--------
Series.take : Similar method for Series.
numpy.ndarray.take : Similar method for NumPy arrays.
Examples
--------
>>> cat = pd.Categorical(['a', 'a', 'b'])
>>> cat
[a, a, b]
Categories (2, object): [a, b]
Specify ``allow_fill==False`` to have negative indices mean indexing
from the right.
>>> cat.take([0, -1, -2], allow_fill=False)
[a, b, a]
Categories (2, object): [a, b]
With ``allow_fill=True``, indices equal to ``-1`` mean "missing"
values that should be filled with the `fill_value`, which is
``np.nan`` by default.
>>> cat.take([0, -1, -1], allow_fill=True)
[a, NaN, NaN]
Categories (2, object): [a, b]
The fill value can be specified.
>>> cat.take([0, -1, -1], allow_fill=True, fill_value='a')
[a, a, a]
Categories (3, object): [a, b]
Specifying a fill value that's not in ``self.categories``
will raise a ``TypeError``.
"""
indexer = np.asarray(indexer, dtype=np.intp)
if allow_fill is None:
if (indexer < 0).any():
warn(_take_msg, FutureWarning, stacklevel=2)
allow_fill = True
dtype = self.dtype
if isna(fill_value):
fill_value = -1
elif allow_fill:
# convert user-provided `fill_value` to codes
if fill_value in self.categories:
fill_value = self.categories.get_loc(fill_value)
else:
msg = (
"'fill_value' ('{}') is not in this Categorical's "
"categories."
)
raise TypeError(msg.format(fill_value))
codes = take(self._codes, indexer, allow_fill=allow_fill,
fill_value=fill_value)
result = type(self).from_codes(codes, dtype=dtype)
return result | def take_nd(self, indexer, allow_fill=None, fill_value=None):
"""
Take elements from the Categorical.
Parameters
----------
indexer : sequence of int
The indices in `self` to take. The meaning of negative values in
`indexer` depends on the value of `allow_fill`.
allow_fill : bool, default None
How to handle negative values in `indexer`.
* False: negative values in `indices` indicate positional indices
from the right. This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate missing values
(the default). These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
.. versionchanged:: 0.23.0
Deprecated the default value of `allow_fill`. The deprecated
default is ``True``. In the future, this will change to
``False``.
fill_value : object
The value to use for `indices` that are missing (-1), when
``allow_fill=True``. This should be the category, i.e. a value
in ``self.categories``, not a code.
Returns
-------
Categorical
This Categorical will have the same categories and ordered as
`self`.
See Also
--------
Series.take : Similar method for Series.
numpy.ndarray.take : Similar method for NumPy arrays.
Examples
--------
>>> cat = pd.Categorical(['a', 'a', 'b'])
>>> cat
[a, a, b]
Categories (2, object): [a, b]
Specify ``allow_fill==False`` to have negative indices mean indexing
from the right.
>>> cat.take([0, -1, -2], allow_fill=False)
[a, b, a]
Categories (2, object): [a, b]
With ``allow_fill=True``, indices equal to ``-1`` mean "missing"
values that should be filled with the `fill_value`, which is
``np.nan`` by default.
>>> cat.take([0, -1, -1], allow_fill=True)
[a, NaN, NaN]
Categories (2, object): [a, b]
The fill value can be specified.
>>> cat.take([0, -1, -1], allow_fill=True, fill_value='a')
[a, a, a]
Categories (3, object): [a, b]
Specifying a fill value that's not in ``self.categories``
will raise a ``TypeError``.
"""
indexer = np.asarray(indexer, dtype=np.intp)
if allow_fill is None:
if (indexer < 0).any():
warn(_take_msg, FutureWarning, stacklevel=2)
allow_fill = True
dtype = self.dtype
if isna(fill_value):
fill_value = -1
elif allow_fill:
# convert user-provided `fill_value` to codes
if fill_value in self.categories:
fill_value = self.categories.get_loc(fill_value)
else:
msg = (
"'fill_value' ('{}') is not in this Categorical's "
"categories."
)
raise TypeError(msg.format(fill_value))
codes = take(self._codes, indexer, allow_fill=allow_fill,
fill_value=fill_value)
result = type(self).from_codes(codes, dtype=dtype)
return result | [
"Take",
"elements",
"from",
"the",
"Categorical",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1792-L1889 | [
"def",
"take_nd",
"(",
"self",
",",
"indexer",
",",
"allow_fill",
"=",
"None",
",",
"fill_value",
"=",
"None",
")",
":",
"indexer",
"=",
"np",
".",
"asarray",
"(",
"indexer",
",",
"dtype",
"=",
"np",
".",
"intp",
")",
"if",
"allow_fill",
"is",
"None",
":",
"if",
"(",
"indexer",
"<",
"0",
")",
".",
"any",
"(",
")",
":",
"warn",
"(",
"_take_msg",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"allow_fill",
"=",
"True",
"dtype",
"=",
"self",
".",
"dtype",
"if",
"isna",
"(",
"fill_value",
")",
":",
"fill_value",
"=",
"-",
"1",
"elif",
"allow_fill",
":",
"# convert user-provided `fill_value` to codes",
"if",
"fill_value",
"in",
"self",
".",
"categories",
":",
"fill_value",
"=",
"self",
".",
"categories",
".",
"get_loc",
"(",
"fill_value",
")",
"else",
":",
"msg",
"=",
"(",
"\"'fill_value' ('{}') is not in this Categorical's \"",
"\"categories.\"",
")",
"raise",
"TypeError",
"(",
"msg",
".",
"format",
"(",
"fill_value",
")",
")",
"codes",
"=",
"take",
"(",
"self",
".",
"_codes",
",",
"indexer",
",",
"allow_fill",
"=",
"allow_fill",
",",
"fill_value",
"=",
"fill_value",
")",
"result",
"=",
"type",
"(",
"self",
")",
".",
"from_codes",
"(",
"codes",
",",
"dtype",
"=",
"dtype",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._slice | Return a slice of myself.
For internal compatibility with numpy arrays. | pandas/core/arrays/categorical.py | def _slice(self, slicer):
"""
Return a slice of myself.
For internal compatibility with numpy arrays.
"""
# only allow 1 dimensional slicing, but can
# in a 2-d case be passd (slice(None),....)
if isinstance(slicer, tuple) and len(slicer) == 2:
if not com.is_null_slice(slicer[0]):
raise AssertionError("invalid slicing for a 1-ndim "
"categorical")
slicer = slicer[1]
codes = self._codes[slicer]
return self._constructor(values=codes, dtype=self.dtype, fastpath=True) | def _slice(self, slicer):
"""
Return a slice of myself.
For internal compatibility with numpy arrays.
"""
# only allow 1 dimensional slicing, but can
# in a 2-d case be passd (slice(None),....)
if isinstance(slicer, tuple) and len(slicer) == 2:
if not com.is_null_slice(slicer[0]):
raise AssertionError("invalid slicing for a 1-ndim "
"categorical")
slicer = slicer[1]
codes = self._codes[slicer]
return self._constructor(values=codes, dtype=self.dtype, fastpath=True) | [
"Return",
"a",
"slice",
"of",
"myself",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1893-L1909 | [
"def",
"_slice",
"(",
"self",
",",
"slicer",
")",
":",
"# only allow 1 dimensional slicing, but can",
"# in a 2-d case be passd (slice(None),....)",
"if",
"isinstance",
"(",
"slicer",
",",
"tuple",
")",
"and",
"len",
"(",
"slicer",
")",
"==",
"2",
":",
"if",
"not",
"com",
".",
"is_null_slice",
"(",
"slicer",
"[",
"0",
"]",
")",
":",
"raise",
"AssertionError",
"(",
"\"invalid slicing for a 1-ndim \"",
"\"categorical\"",
")",
"slicer",
"=",
"slicer",
"[",
"1",
"]",
"codes",
"=",
"self",
".",
"_codes",
"[",
"slicer",
"]",
"return",
"self",
".",
"_constructor",
"(",
"values",
"=",
"codes",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._tidy_repr | a short repr displaying only max_vals and an optional (but default
footer) | pandas/core/arrays/categorical.py | def _tidy_repr(self, max_vals=10, footer=True):
""" a short repr displaying only max_vals and an optional (but default
footer)
"""
num = max_vals // 2
head = self[:num]._get_repr(length=False, footer=False)
tail = self[-(max_vals - num):]._get_repr(length=False, footer=False)
result = '{head}, ..., {tail}'.format(head=head[:-1], tail=tail[1:])
if footer:
result = '{result}\n{footer}'.format(
result=result, footer=self._repr_footer())
return str(result) | def _tidy_repr(self, max_vals=10, footer=True):
""" a short repr displaying only max_vals and an optional (but default
footer)
"""
num = max_vals // 2
head = self[:num]._get_repr(length=False, footer=False)
tail = self[-(max_vals - num):]._get_repr(length=False, footer=False)
result = '{head}, ..., {tail}'.format(head=head[:-1], tail=tail[1:])
if footer:
result = '{result}\n{footer}'.format(
result=result, footer=self._repr_footer())
return str(result) | [
"a",
"short",
"repr",
"displaying",
"only",
"max_vals",
"and",
"an",
"optional",
"(",
"but",
"default",
"footer",
")"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1933-L1946 | [
"def",
"_tidy_repr",
"(",
"self",
",",
"max_vals",
"=",
"10",
",",
"footer",
"=",
"True",
")",
":",
"num",
"=",
"max_vals",
"//",
"2",
"head",
"=",
"self",
"[",
":",
"num",
"]",
".",
"_get_repr",
"(",
"length",
"=",
"False",
",",
"footer",
"=",
"False",
")",
"tail",
"=",
"self",
"[",
"-",
"(",
"max_vals",
"-",
"num",
")",
":",
"]",
".",
"_get_repr",
"(",
"length",
"=",
"False",
",",
"footer",
"=",
"False",
")",
"result",
"=",
"'{head}, ..., {tail}'",
".",
"format",
"(",
"head",
"=",
"head",
"[",
":",
"-",
"1",
"]",
",",
"tail",
"=",
"tail",
"[",
"1",
":",
"]",
")",
"if",
"footer",
":",
"result",
"=",
"'{result}\\n{footer}'",
".",
"format",
"(",
"result",
"=",
"result",
",",
"footer",
"=",
"self",
".",
"_repr_footer",
"(",
")",
")",
"return",
"str",
"(",
"result",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._repr_categories | return the base repr for the categories | pandas/core/arrays/categorical.py | def _repr_categories(self):
"""
return the base repr for the categories
"""
max_categories = (10 if get_option("display.max_categories") == 0 else
get_option("display.max_categories"))
from pandas.io.formats import format as fmt
if len(self.categories) > max_categories:
num = max_categories // 2
head = fmt.format_array(self.categories[:num], None)
tail = fmt.format_array(self.categories[-num:], None)
category_strs = head + ["..."] + tail
else:
category_strs = fmt.format_array(self.categories, None)
# Strip all leading spaces, which format_array adds for columns...
category_strs = [x.strip() for x in category_strs]
return category_strs | def _repr_categories(self):
"""
return the base repr for the categories
"""
max_categories = (10 if get_option("display.max_categories") == 0 else
get_option("display.max_categories"))
from pandas.io.formats import format as fmt
if len(self.categories) > max_categories:
num = max_categories // 2
head = fmt.format_array(self.categories[:num], None)
tail = fmt.format_array(self.categories[-num:], None)
category_strs = head + ["..."] + tail
else:
category_strs = fmt.format_array(self.categories, None)
# Strip all leading spaces, which format_array adds for columns...
category_strs = [x.strip() for x in category_strs]
return category_strs | [
"return",
"the",
"base",
"repr",
"for",
"the",
"categories"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1948-L1965 | [
"def",
"_repr_categories",
"(",
"self",
")",
":",
"max_categories",
"=",
"(",
"10",
"if",
"get_option",
"(",
"\"display.max_categories\"",
")",
"==",
"0",
"else",
"get_option",
"(",
"\"display.max_categories\"",
")",
")",
"from",
"pandas",
".",
"io",
".",
"formats",
"import",
"format",
"as",
"fmt",
"if",
"len",
"(",
"self",
".",
"categories",
")",
">",
"max_categories",
":",
"num",
"=",
"max_categories",
"//",
"2",
"head",
"=",
"fmt",
".",
"format_array",
"(",
"self",
".",
"categories",
"[",
":",
"num",
"]",
",",
"None",
")",
"tail",
"=",
"fmt",
".",
"format_array",
"(",
"self",
".",
"categories",
"[",
"-",
"num",
":",
"]",
",",
"None",
")",
"category_strs",
"=",
"head",
"+",
"[",
"\"...\"",
"]",
"+",
"tail",
"else",
":",
"category_strs",
"=",
"fmt",
".",
"format_array",
"(",
"self",
".",
"categories",
",",
"None",
")",
"# Strip all leading spaces, which format_array adds for columns...",
"category_strs",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"category_strs",
"]",
"return",
"category_strs"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._repr_categories_info | Returns a string representation of the footer. | pandas/core/arrays/categorical.py | def _repr_categories_info(self):
"""
Returns a string representation of the footer.
"""
category_strs = self._repr_categories()
dtype = getattr(self.categories, 'dtype_str',
str(self.categories.dtype))
levheader = "Categories ({length}, {dtype}): ".format(
length=len(self.categories), dtype=dtype)
width, height = get_terminal_size()
max_width = get_option("display.width") or width
if console.in_ipython_frontend():
# 0 = no breaks
max_width = 0
levstring = ""
start = True
cur_col_len = len(levheader) # header
sep_len, sep = (3, " < ") if self.ordered else (2, ", ")
linesep = sep.rstrip() + "\n" # remove whitespace
for val in category_strs:
if max_width != 0 and cur_col_len + sep_len + len(val) > max_width:
levstring += linesep + (" " * (len(levheader) + 1))
cur_col_len = len(levheader) + 1 # header + a whitespace
elif not start:
levstring += sep
cur_col_len += len(val)
levstring += val
start = False
# replace to simple save space by
return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]" | def _repr_categories_info(self):
"""
Returns a string representation of the footer.
"""
category_strs = self._repr_categories()
dtype = getattr(self.categories, 'dtype_str',
str(self.categories.dtype))
levheader = "Categories ({length}, {dtype}): ".format(
length=len(self.categories), dtype=dtype)
width, height = get_terminal_size()
max_width = get_option("display.width") or width
if console.in_ipython_frontend():
# 0 = no breaks
max_width = 0
levstring = ""
start = True
cur_col_len = len(levheader) # header
sep_len, sep = (3, " < ") if self.ordered else (2, ", ")
linesep = sep.rstrip() + "\n" # remove whitespace
for val in category_strs:
if max_width != 0 and cur_col_len + sep_len + len(val) > max_width:
levstring += linesep + (" " * (len(levheader) + 1))
cur_col_len = len(levheader) + 1 # header + a whitespace
elif not start:
levstring += sep
cur_col_len += len(val)
levstring += val
start = False
# replace to simple save space by
return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]" | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"footer",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L1967-L1998 | [
"def",
"_repr_categories_info",
"(",
"self",
")",
":",
"category_strs",
"=",
"self",
".",
"_repr_categories",
"(",
")",
"dtype",
"=",
"getattr",
"(",
"self",
".",
"categories",
",",
"'dtype_str'",
",",
"str",
"(",
"self",
".",
"categories",
".",
"dtype",
")",
")",
"levheader",
"=",
"\"Categories ({length}, {dtype}): \"",
".",
"format",
"(",
"length",
"=",
"len",
"(",
"self",
".",
"categories",
")",
",",
"dtype",
"=",
"dtype",
")",
"width",
",",
"height",
"=",
"get_terminal_size",
"(",
")",
"max_width",
"=",
"get_option",
"(",
"\"display.width\"",
")",
"or",
"width",
"if",
"console",
".",
"in_ipython_frontend",
"(",
")",
":",
"# 0 = no breaks",
"max_width",
"=",
"0",
"levstring",
"=",
"\"\"",
"start",
"=",
"True",
"cur_col_len",
"=",
"len",
"(",
"levheader",
")",
"# header",
"sep_len",
",",
"sep",
"=",
"(",
"3",
",",
"\" < \"",
")",
"if",
"self",
".",
"ordered",
"else",
"(",
"2",
",",
"\", \"",
")",
"linesep",
"=",
"sep",
".",
"rstrip",
"(",
")",
"+",
"\"\\n\"",
"# remove whitespace",
"for",
"val",
"in",
"category_strs",
":",
"if",
"max_width",
"!=",
"0",
"and",
"cur_col_len",
"+",
"sep_len",
"+",
"len",
"(",
"val",
")",
">",
"max_width",
":",
"levstring",
"+=",
"linesep",
"+",
"(",
"\" \"",
"*",
"(",
"len",
"(",
"levheader",
")",
"+",
"1",
")",
")",
"cur_col_len",
"=",
"len",
"(",
"levheader",
")",
"+",
"1",
"# header + a whitespace",
"elif",
"not",
"start",
":",
"levstring",
"+=",
"sep",
"cur_col_len",
"+=",
"len",
"(",
"val",
")",
"levstring",
"+=",
"val",
"start",
"=",
"False",
"# replace to simple save space by",
"return",
"levheader",
"+",
"\"[\"",
"+",
"levstring",
".",
"replace",
"(",
"\" < ... < \"",
",",
"\" ... \"",
")",
"+",
"\"]\""
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._maybe_coerce_indexer | return an indexer coerced to the codes dtype | pandas/core/arrays/categorical.py | def _maybe_coerce_indexer(self, indexer):
"""
return an indexer coerced to the codes dtype
"""
if isinstance(indexer, np.ndarray) and indexer.dtype.kind == 'i':
indexer = indexer.astype(self._codes.dtype)
return indexer | def _maybe_coerce_indexer(self, indexer):
"""
return an indexer coerced to the codes dtype
"""
if isinstance(indexer, np.ndarray) and indexer.dtype.kind == 'i':
indexer = indexer.astype(self._codes.dtype)
return indexer | [
"return",
"an",
"indexer",
"coerced",
"to",
"the",
"codes",
"dtype"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2031-L2037 | [
"def",
"_maybe_coerce_indexer",
"(",
"self",
",",
"indexer",
")",
":",
"if",
"isinstance",
"(",
"indexer",
",",
"np",
".",
"ndarray",
")",
"and",
"indexer",
".",
"dtype",
".",
"kind",
"==",
"'i'",
":",
"indexer",
"=",
"indexer",
".",
"astype",
"(",
"self",
".",
"_codes",
".",
"dtype",
")",
"return",
"indexer"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical._reverse_indexer | Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
[a, a, b, c, a]
Categories (3, object): [a, b, c]
In [3]: c.categories
Out[3]: Index(['a', 'b', 'c'], dtype='object')
In [4]: c.codes
Out[4]: array([0, 0, 1, 2, 0], dtype=int8)
In [5]: c._reverse_indexer()
Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])} | pandas/core/arrays/categorical.py | def _reverse_indexer(self):
"""
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
[a, a, b, c, a]
Categories (3, object): [a, b, c]
In [3]: c.categories
Out[3]: Index(['a', 'b', 'c'], dtype='object')
In [4]: c.codes
Out[4]: array([0, 0, 1, 2, 0], dtype=int8)
In [5]: c._reverse_indexer()
Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}
"""
categories = self.categories
r, counts = libalgos.groupsort_indexer(self.codes.astype('int64'),
categories.size)
counts = counts.cumsum()
result = (r[start:end] for start, end in zip(counts, counts[1:]))
result = dict(zip(categories, result))
return result | def _reverse_indexer(self):
"""
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
[a, a, b, c, a]
Categories (3, object): [a, b, c]
In [3]: c.categories
Out[3]: Index(['a', 'b', 'c'], dtype='object')
In [4]: c.codes
Out[4]: array([0, 0, 1, 2, 0], dtype=int8)
In [5]: c._reverse_indexer()
Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}
"""
categories = self.categories
r, counts = libalgos.groupsort_indexer(self.codes.astype('int64'),
categories.size)
counts = counts.cumsum()
result = (r[start:end] for start, end in zip(counts, counts[1:]))
result = dict(zip(categories, result))
return result | [
"Compute",
"the",
"inverse",
"of",
"a",
"categorical",
"returning",
"a",
"dict",
"of",
"categories",
"-",
">",
"indexers",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2119-L2155 | [
"def",
"_reverse_indexer",
"(",
"self",
")",
":",
"categories",
"=",
"self",
".",
"categories",
"r",
",",
"counts",
"=",
"libalgos",
".",
"groupsort_indexer",
"(",
"self",
".",
"codes",
".",
"astype",
"(",
"'int64'",
")",
",",
"categories",
".",
"size",
")",
"counts",
"=",
"counts",
".",
"cumsum",
"(",
")",
"result",
"=",
"(",
"r",
"[",
"start",
":",
"end",
"]",
"for",
"start",
",",
"end",
"in",
"zip",
"(",
"counts",
",",
"counts",
"[",
"1",
":",
"]",
")",
")",
"result",
"=",
"dict",
"(",
"zip",
"(",
"categories",
",",
"result",
")",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.min | The minimum value of the object.
Only ordered `Categoricals` have a minimum!
Raises
------
TypeError
If the `Categorical` is not `ordered`.
Returns
-------
min : the minimum of this `Categorical` | pandas/core/arrays/categorical.py | def min(self, numeric_only=None, **kwargs):
"""
The minimum value of the object.
Only ordered `Categoricals` have a minimum!
Raises
------
TypeError
If the `Categorical` is not `ordered`.
Returns
-------
min : the minimum of this `Categorical`
"""
self.check_for_ordered('min')
if numeric_only:
good = self._codes != -1
pointer = self._codes[good].min(**kwargs)
else:
pointer = self._codes.min(**kwargs)
if pointer == -1:
return np.nan
else:
return self.categories[pointer] | def min(self, numeric_only=None, **kwargs):
"""
The minimum value of the object.
Only ordered `Categoricals` have a minimum!
Raises
------
TypeError
If the `Categorical` is not `ordered`.
Returns
-------
min : the minimum of this `Categorical`
"""
self.check_for_ordered('min')
if numeric_only:
good = self._codes != -1
pointer = self._codes[good].min(**kwargs)
else:
pointer = self._codes.min(**kwargs)
if pointer == -1:
return np.nan
else:
return self.categories[pointer] | [
"The",
"minimum",
"value",
"of",
"the",
"object",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2165-L2189 | [
"def",
"min",
"(",
"self",
",",
"numeric_only",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"check_for_ordered",
"(",
"'min'",
")",
"if",
"numeric_only",
":",
"good",
"=",
"self",
".",
"_codes",
"!=",
"-",
"1",
"pointer",
"=",
"self",
".",
"_codes",
"[",
"good",
"]",
".",
"min",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"pointer",
"=",
"self",
".",
"_codes",
".",
"min",
"(",
"*",
"*",
"kwargs",
")",
"if",
"pointer",
"==",
"-",
"1",
":",
"return",
"np",
".",
"nan",
"else",
":",
"return",
"self",
".",
"categories",
"[",
"pointer",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.mode | Returns the mode(s) of the Categorical.
Always returns `Categorical` even if only one value.
Parameters
----------
dropna : bool, default True
Don't consider counts of NaN/NaT.
.. versionadded:: 0.24.0
Returns
-------
modes : `Categorical` (sorted) | pandas/core/arrays/categorical.py | def mode(self, dropna=True):
"""
Returns the mode(s) of the Categorical.
Always returns `Categorical` even if only one value.
Parameters
----------
dropna : bool, default True
Don't consider counts of NaN/NaT.
.. versionadded:: 0.24.0
Returns
-------
modes : `Categorical` (sorted)
"""
import pandas._libs.hashtable as htable
codes = self._codes
if dropna:
good = self._codes != -1
codes = self._codes[good]
codes = sorted(htable.mode_int64(ensure_int64(codes), dropna))
return self._constructor(values=codes, dtype=self.dtype, fastpath=True) | def mode(self, dropna=True):
"""
Returns the mode(s) of the Categorical.
Always returns `Categorical` even if only one value.
Parameters
----------
dropna : bool, default True
Don't consider counts of NaN/NaT.
.. versionadded:: 0.24.0
Returns
-------
modes : `Categorical` (sorted)
"""
import pandas._libs.hashtable as htable
codes = self._codes
if dropna:
good = self._codes != -1
codes = self._codes[good]
codes = sorted(htable.mode_int64(ensure_int64(codes), dropna))
return self._constructor(values=codes, dtype=self.dtype, fastpath=True) | [
"Returns",
"the",
"mode",
"(",
"s",
")",
"of",
"the",
"Categorical",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2217-L2241 | [
"def",
"mode",
"(",
"self",
",",
"dropna",
"=",
"True",
")",
":",
"import",
"pandas",
".",
"_libs",
".",
"hashtable",
"as",
"htable",
"codes",
"=",
"self",
".",
"_codes",
"if",
"dropna",
":",
"good",
"=",
"self",
".",
"_codes",
"!=",
"-",
"1",
"codes",
"=",
"self",
".",
"_codes",
"[",
"good",
"]",
"codes",
"=",
"sorted",
"(",
"htable",
".",
"mode_int64",
"(",
"ensure_int64",
"(",
"codes",
")",
",",
"dropna",
")",
")",
"return",
"self",
".",
"_constructor",
"(",
"values",
"=",
"codes",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.unique | Return the ``Categorical`` which ``categories`` and ``codes`` are
unique. Unused categories are NOT returned.
- unordered category: values and categories are sorted by appearance
order.
- ordered category: values are sorted by appearance order, categories
keeps existing order.
Returns
-------
unique values : ``Categorical``
Examples
--------
An unordered Categorical will return categories in the
order of appearance.
>>> pd.Categorical(list('baabc'))
[b, a, c]
Categories (3, object): [b, a, c]
>>> pd.Categorical(list('baabc'), categories=list('abc'))
[b, a, c]
Categories (3, object): [b, a, c]
An ordered Categorical preserves the category ordering.
>>> pd.Categorical(list('baabc'),
... categories=list('abc'),
... ordered=True)
[b, a, c]
Categories (3, object): [a < b < c]
See Also
--------
unique
CategoricalIndex.unique
Series.unique | pandas/core/arrays/categorical.py | def unique(self):
"""
Return the ``Categorical`` which ``categories`` and ``codes`` are
unique. Unused categories are NOT returned.
- unordered category: values and categories are sorted by appearance
order.
- ordered category: values are sorted by appearance order, categories
keeps existing order.
Returns
-------
unique values : ``Categorical``
Examples
--------
An unordered Categorical will return categories in the
order of appearance.
>>> pd.Categorical(list('baabc'))
[b, a, c]
Categories (3, object): [b, a, c]
>>> pd.Categorical(list('baabc'), categories=list('abc'))
[b, a, c]
Categories (3, object): [b, a, c]
An ordered Categorical preserves the category ordering.
>>> pd.Categorical(list('baabc'),
... categories=list('abc'),
... ordered=True)
[b, a, c]
Categories (3, object): [a < b < c]
See Also
--------
unique
CategoricalIndex.unique
Series.unique
"""
# unlike np.unique, unique1d does not sort
unique_codes = unique1d(self.codes)
cat = self.copy()
# keep nan in codes
cat._codes = unique_codes
# exclude nan from indexer for categories
take_codes = unique_codes[unique_codes != -1]
if self.ordered:
take_codes = np.sort(take_codes)
return cat.set_categories(cat.categories.take(take_codes)) | def unique(self):
"""
Return the ``Categorical`` which ``categories`` and ``codes`` are
unique. Unused categories are NOT returned.
- unordered category: values and categories are sorted by appearance
order.
- ordered category: values are sorted by appearance order, categories
keeps existing order.
Returns
-------
unique values : ``Categorical``
Examples
--------
An unordered Categorical will return categories in the
order of appearance.
>>> pd.Categorical(list('baabc'))
[b, a, c]
Categories (3, object): [b, a, c]
>>> pd.Categorical(list('baabc'), categories=list('abc'))
[b, a, c]
Categories (3, object): [b, a, c]
An ordered Categorical preserves the category ordering.
>>> pd.Categorical(list('baabc'),
... categories=list('abc'),
... ordered=True)
[b, a, c]
Categories (3, object): [a < b < c]
See Also
--------
unique
CategoricalIndex.unique
Series.unique
"""
# unlike np.unique, unique1d does not sort
unique_codes = unique1d(self.codes)
cat = self.copy()
# keep nan in codes
cat._codes = unique_codes
# exclude nan from indexer for categories
take_codes = unique_codes[unique_codes != -1]
if self.ordered:
take_codes = np.sort(take_codes)
return cat.set_categories(cat.categories.take(take_codes)) | [
"Return",
"the",
"Categorical",
"which",
"categories",
"and",
"codes",
"are",
"unique",
".",
"Unused",
"categories",
"are",
"NOT",
"returned",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2243-L2297 | [
"def",
"unique",
"(",
"self",
")",
":",
"# unlike np.unique, unique1d does not sort",
"unique_codes",
"=",
"unique1d",
"(",
"self",
".",
"codes",
")",
"cat",
"=",
"self",
".",
"copy",
"(",
")",
"# keep nan in codes",
"cat",
".",
"_codes",
"=",
"unique_codes",
"# exclude nan from indexer for categories",
"take_codes",
"=",
"unique_codes",
"[",
"unique_codes",
"!=",
"-",
"1",
"]",
"if",
"self",
".",
"ordered",
":",
"take_codes",
"=",
"np",
".",
"sort",
"(",
"take_codes",
")",
"return",
"cat",
".",
"set_categories",
"(",
"cat",
".",
"categories",
".",
"take",
"(",
"take_codes",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.equals | Returns True if categorical arrays are equal.
Parameters
----------
other : `Categorical`
Returns
-------
bool | pandas/core/arrays/categorical.py | def equals(self, other):
"""
Returns True if categorical arrays are equal.
Parameters
----------
other : `Categorical`
Returns
-------
bool
"""
if self.is_dtype_equal(other):
if self.categories.equals(other.categories):
# fastpath to avoid re-coding
other_codes = other._codes
else:
other_codes = _recode_for_categories(other.codes,
other.categories,
self.categories)
return np.array_equal(self._codes, other_codes)
return False | def equals(self, other):
"""
Returns True if categorical arrays are equal.
Parameters
----------
other : `Categorical`
Returns
-------
bool
"""
if self.is_dtype_equal(other):
if self.categories.equals(other.categories):
# fastpath to avoid re-coding
other_codes = other._codes
else:
other_codes = _recode_for_categories(other.codes,
other.categories,
self.categories)
return np.array_equal(self._codes, other_codes)
return False | [
"Returns",
"True",
"if",
"categorical",
"arrays",
"are",
"equal",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2308-L2329 | [
"def",
"equals",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"is_dtype_equal",
"(",
"other",
")",
":",
"if",
"self",
".",
"categories",
".",
"equals",
"(",
"other",
".",
"categories",
")",
":",
"# fastpath to avoid re-coding",
"other_codes",
"=",
"other",
".",
"_codes",
"else",
":",
"other_codes",
"=",
"_recode_for_categories",
"(",
"other",
".",
"codes",
",",
"other",
".",
"categories",
",",
"self",
".",
"categories",
")",
"return",
"np",
".",
"array_equal",
"(",
"self",
".",
"_codes",
",",
"other_codes",
")",
"return",
"False"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.is_dtype_equal | Returns True if categoricals are the same dtype
same categories, and same ordered
Parameters
----------
other : Categorical
Returns
-------
bool | pandas/core/arrays/categorical.py | def is_dtype_equal(self, other):
"""
Returns True if categoricals are the same dtype
same categories, and same ordered
Parameters
----------
other : Categorical
Returns
-------
bool
"""
try:
return hash(self.dtype) == hash(other.dtype)
except (AttributeError, TypeError):
return False | def is_dtype_equal(self, other):
"""
Returns True if categoricals are the same dtype
same categories, and same ordered
Parameters
----------
other : Categorical
Returns
-------
bool
"""
try:
return hash(self.dtype) == hash(other.dtype)
except (AttributeError, TypeError):
return False | [
"Returns",
"True",
"if",
"categoricals",
"are",
"the",
"same",
"dtype",
"same",
"categories",
"and",
"same",
"ordered"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2331-L2348 | [
"def",
"is_dtype_equal",
"(",
"self",
",",
"other",
")",
":",
"try",
":",
"return",
"hash",
"(",
"self",
".",
"dtype",
")",
"==",
"hash",
"(",
"other",
".",
"dtype",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"return",
"False"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.describe | Describes this Categorical
Returns
-------
description: `DataFrame`
A dataframe with frequency and counts by category. | pandas/core/arrays/categorical.py | def describe(self):
"""
Describes this Categorical
Returns
-------
description: `DataFrame`
A dataframe with frequency and counts by category.
"""
counts = self.value_counts(dropna=False)
freqs = counts / float(counts.sum())
from pandas.core.reshape.concat import concat
result = concat([counts, freqs], axis=1)
result.columns = ['counts', 'freqs']
result.index.name = 'categories'
return result | def describe(self):
"""
Describes this Categorical
Returns
-------
description: `DataFrame`
A dataframe with frequency and counts by category.
"""
counts = self.value_counts(dropna=False)
freqs = counts / float(counts.sum())
from pandas.core.reshape.concat import concat
result = concat([counts, freqs], axis=1)
result.columns = ['counts', 'freqs']
result.index.name = 'categories'
return result | [
"Describes",
"this",
"Categorical"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2350-L2367 | [
"def",
"describe",
"(",
"self",
")",
":",
"counts",
"=",
"self",
".",
"value_counts",
"(",
"dropna",
"=",
"False",
")",
"freqs",
"=",
"counts",
"/",
"float",
"(",
"counts",
".",
"sum",
"(",
")",
")",
"from",
"pandas",
".",
"core",
".",
"reshape",
".",
"concat",
"import",
"concat",
"result",
"=",
"concat",
"(",
"[",
"counts",
",",
"freqs",
"]",
",",
"axis",
"=",
"1",
")",
"result",
".",
"columns",
"=",
"[",
"'counts'",
",",
"'freqs'",
"]",
"result",
".",
"index",
".",
"name",
"=",
"'categories'",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Categorical.isin | Check whether `values` are contained in Categorical.
Return a boolean NumPy Array showing whether each element in
the Categorical matches an element in the passed sequence of
`values` exactly.
Parameters
----------
values : set or list-like
The sequence of values to test. Passing in a single string will
raise a ``TypeError``. Instead, turn a single string into a
list of one element.
Returns
-------
isin : numpy.ndarray (bool dtype)
Raises
------
TypeError
* If `values` is not a set or list-like
See Also
--------
pandas.Series.isin : Equivalent method on Series.
Examples
--------
>>> s = pd.Categorical(['lama', 'cow', 'lama', 'beetle', 'lama',
... 'hippo'])
>>> s.isin(['cow', 'lama'])
array([ True, True, True, False, True, False])
Passing a single string as ``s.isin('lama')`` will raise an error. Use
a list of one element instead:
>>> s.isin(['lama'])
array([ True, False, True, False, True, False]) | pandas/core/arrays/categorical.py | def isin(self, values):
"""
Check whether `values` are contained in Categorical.
Return a boolean NumPy Array showing whether each element in
the Categorical matches an element in the passed sequence of
`values` exactly.
Parameters
----------
values : set or list-like
The sequence of values to test. Passing in a single string will
raise a ``TypeError``. Instead, turn a single string into a
list of one element.
Returns
-------
isin : numpy.ndarray (bool dtype)
Raises
------
TypeError
* If `values` is not a set or list-like
See Also
--------
pandas.Series.isin : Equivalent method on Series.
Examples
--------
>>> s = pd.Categorical(['lama', 'cow', 'lama', 'beetle', 'lama',
... 'hippo'])
>>> s.isin(['cow', 'lama'])
array([ True, True, True, False, True, False])
Passing a single string as ``s.isin('lama')`` will raise an error. Use
a list of one element instead:
>>> s.isin(['lama'])
array([ True, False, True, False, True, False])
"""
from pandas.core.internals.construction import sanitize_array
if not is_list_like(values):
raise TypeError("only list-like objects are allowed to be passed"
" to isin(), you passed a [{values_type}]"
.format(values_type=type(values).__name__))
values = sanitize_array(values, None, None)
null_mask = np.asarray(isna(values))
code_values = self.categories.get_indexer(values)
code_values = code_values[null_mask | (code_values >= 0)]
return algorithms.isin(self.codes, code_values) | def isin(self, values):
"""
Check whether `values` are contained in Categorical.
Return a boolean NumPy Array showing whether each element in
the Categorical matches an element in the passed sequence of
`values` exactly.
Parameters
----------
values : set or list-like
The sequence of values to test. Passing in a single string will
raise a ``TypeError``. Instead, turn a single string into a
list of one element.
Returns
-------
isin : numpy.ndarray (bool dtype)
Raises
------
TypeError
* If `values` is not a set or list-like
See Also
--------
pandas.Series.isin : Equivalent method on Series.
Examples
--------
>>> s = pd.Categorical(['lama', 'cow', 'lama', 'beetle', 'lama',
... 'hippo'])
>>> s.isin(['cow', 'lama'])
array([ True, True, True, False, True, False])
Passing a single string as ``s.isin('lama')`` will raise an error. Use
a list of one element instead:
>>> s.isin(['lama'])
array([ True, False, True, False, True, False])
"""
from pandas.core.internals.construction import sanitize_array
if not is_list_like(values):
raise TypeError("only list-like objects are allowed to be passed"
" to isin(), you passed a [{values_type}]"
.format(values_type=type(values).__name__))
values = sanitize_array(values, None, None)
null_mask = np.asarray(isna(values))
code_values = self.categories.get_indexer(values)
code_values = code_values[null_mask | (code_values >= 0)]
return algorithms.isin(self.codes, code_values) | [
"Check",
"whether",
"values",
"are",
"contained",
"in",
"Categorical",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L2387-L2438 | [
"def",
"isin",
"(",
"self",
",",
"values",
")",
":",
"from",
"pandas",
".",
"core",
".",
"internals",
".",
"construction",
"import",
"sanitize_array",
"if",
"not",
"is_list_like",
"(",
"values",
")",
":",
"raise",
"TypeError",
"(",
"\"only list-like objects are allowed to be passed\"",
"\" to isin(), you passed a [{values_type}]\"",
".",
"format",
"(",
"values_type",
"=",
"type",
"(",
"values",
")",
".",
"__name__",
")",
")",
"values",
"=",
"sanitize_array",
"(",
"values",
",",
"None",
",",
"None",
")",
"null_mask",
"=",
"np",
".",
"asarray",
"(",
"isna",
"(",
"values",
")",
")",
"code_values",
"=",
"self",
".",
"categories",
".",
"get_indexer",
"(",
"values",
")",
"code_values",
"=",
"code_values",
"[",
"null_mask",
"|",
"(",
"code_values",
">=",
"0",
")",
"]",
"return",
"algorithms",
".",
"isin",
"(",
"self",
".",
"codes",
",",
"code_values",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | to_timedelta | Convert argument to timedelta.
Timedeltas are absolute differences in times, expressed in difference
units (e.g. days, hours, minutes, seconds). This method converts
an argument from a recognized timedelta format / value into
a Timedelta type.
Parameters
----------
arg : str, timedelta, list-like or Series
The data to be converted to timedelta.
unit : str, default 'ns'
Denotes the unit of the arg. Possible values:
('Y', 'M', 'W', 'D', 'days', 'day', 'hours', hour', 'hr',
'h', 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds',
'sec', 'second', 'ms', 'milliseconds', 'millisecond',
'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond',
'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos',
'nanosecond', 'N').
box : bool, default True
- If True returns a Timedelta/TimedeltaIndex of the results.
- If False returns a numpy.timedelta64 or numpy.darray of
values of dtype timedelta64[ns].
.. deprecated:: 0.25.0
Use :meth:`.to_numpy` or :meth:`Timedelta.to_timedelta64`
instead to get an ndarray of values or numpy.timedelta64,
respectively.
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- If 'raise', then invalid parsing will raise an exception.
- If 'coerce', then invalid parsing will be set as NaT.
- If 'ignore', then invalid parsing will return the input.
Returns
-------
timedelta64 or numpy.array of timedelta64
Output type returned if parsing succeeded.
See Also
--------
DataFrame.astype : Cast argument to a specified dtype.
to_datetime : Convert argument to datetime.
Examples
--------
Parsing a single string to a Timedelta:
>>> pd.to_timedelta('1 days 06:05:01.00003')
Timedelta('1 days 06:05:01.000030')
>>> pd.to_timedelta('15.5us')
Timedelta('0 days 00:00:00.000015')
Parsing a list or array of strings:
>>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015', NaT],
dtype='timedelta64[ns]', freq=None)
Converting numbers by specifying the `unit` keyword argument:
>>> pd.to_timedelta(np.arange(5), unit='s')
TimedeltaIndex(['00:00:00', '00:00:01', '00:00:02',
'00:00:03', '00:00:04'],
dtype='timedelta64[ns]', freq=None)
>>> pd.to_timedelta(np.arange(5), unit='d')
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq=None)
Returning an ndarray by using the 'box' keyword argument:
>>> pd.to_timedelta(np.arange(5), box=False)
array([0, 1, 2, 3, 4], dtype='timedelta64[ns]') | pandas/core/tools/timedeltas.py | def to_timedelta(arg, unit='ns', box=True, errors='raise'):
"""
Convert argument to timedelta.
Timedeltas are absolute differences in times, expressed in difference
units (e.g. days, hours, minutes, seconds). This method converts
an argument from a recognized timedelta format / value into
a Timedelta type.
Parameters
----------
arg : str, timedelta, list-like or Series
The data to be converted to timedelta.
unit : str, default 'ns'
Denotes the unit of the arg. Possible values:
('Y', 'M', 'W', 'D', 'days', 'day', 'hours', hour', 'hr',
'h', 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds',
'sec', 'second', 'ms', 'milliseconds', 'millisecond',
'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond',
'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos',
'nanosecond', 'N').
box : bool, default True
- If True returns a Timedelta/TimedeltaIndex of the results.
- If False returns a numpy.timedelta64 or numpy.darray of
values of dtype timedelta64[ns].
.. deprecated:: 0.25.0
Use :meth:`.to_numpy` or :meth:`Timedelta.to_timedelta64`
instead to get an ndarray of values or numpy.timedelta64,
respectively.
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- If 'raise', then invalid parsing will raise an exception.
- If 'coerce', then invalid parsing will be set as NaT.
- If 'ignore', then invalid parsing will return the input.
Returns
-------
timedelta64 or numpy.array of timedelta64
Output type returned if parsing succeeded.
See Also
--------
DataFrame.astype : Cast argument to a specified dtype.
to_datetime : Convert argument to datetime.
Examples
--------
Parsing a single string to a Timedelta:
>>> pd.to_timedelta('1 days 06:05:01.00003')
Timedelta('1 days 06:05:01.000030')
>>> pd.to_timedelta('15.5us')
Timedelta('0 days 00:00:00.000015')
Parsing a list or array of strings:
>>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015', NaT],
dtype='timedelta64[ns]', freq=None)
Converting numbers by specifying the `unit` keyword argument:
>>> pd.to_timedelta(np.arange(5), unit='s')
TimedeltaIndex(['00:00:00', '00:00:01', '00:00:02',
'00:00:03', '00:00:04'],
dtype='timedelta64[ns]', freq=None)
>>> pd.to_timedelta(np.arange(5), unit='d')
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq=None)
Returning an ndarray by using the 'box' keyword argument:
>>> pd.to_timedelta(np.arange(5), box=False)
array([0, 1, 2, 3, 4], dtype='timedelta64[ns]')
"""
unit = parse_timedelta_unit(unit)
if errors not in ('ignore', 'raise', 'coerce'):
raise ValueError("errors must be one of 'ignore', "
"'raise', or 'coerce'}")
if unit in {'Y', 'y', 'M'}:
warnings.warn("M and Y units are deprecated and "
"will be removed in a future version.",
FutureWarning, stacklevel=2)
if arg is None:
return arg
elif isinstance(arg, ABCSeries):
values = _convert_listlike(arg._values, unit=unit,
box=False, errors=errors)
return arg._constructor(values, index=arg.index, name=arg.name)
elif isinstance(arg, ABCIndexClass):
return _convert_listlike(arg, unit=unit, box=box,
errors=errors, name=arg.name)
elif isinstance(arg, np.ndarray) and arg.ndim == 0:
# extract array scalar and process below
arg = arg.item()
elif is_list_like(arg) and getattr(arg, 'ndim', 1) == 1:
return _convert_listlike(arg, unit=unit, box=box, errors=errors)
elif getattr(arg, 'ndim', 1) > 1:
raise TypeError('arg must be a string, timedelta, list, tuple, '
'1-d array, or Series')
# ...so it must be a scalar value. Return scalar.
return _coerce_scalar_to_timedelta_type(arg, unit=unit,
box=box, errors=errors) | def to_timedelta(arg, unit='ns', box=True, errors='raise'):
"""
Convert argument to timedelta.
Timedeltas are absolute differences in times, expressed in difference
units (e.g. days, hours, minutes, seconds). This method converts
an argument from a recognized timedelta format / value into
a Timedelta type.
Parameters
----------
arg : str, timedelta, list-like or Series
The data to be converted to timedelta.
unit : str, default 'ns'
Denotes the unit of the arg. Possible values:
('Y', 'M', 'W', 'D', 'days', 'day', 'hours', hour', 'hr',
'h', 'm', 'minute', 'min', 'minutes', 'T', 'S', 'seconds',
'sec', 'second', 'ms', 'milliseconds', 'millisecond',
'milli', 'millis', 'L', 'us', 'microseconds', 'microsecond',
'micro', 'micros', 'U', 'ns', 'nanoseconds', 'nano', 'nanos',
'nanosecond', 'N').
box : bool, default True
- If True returns a Timedelta/TimedeltaIndex of the results.
- If False returns a numpy.timedelta64 or numpy.darray of
values of dtype timedelta64[ns].
.. deprecated:: 0.25.0
Use :meth:`.to_numpy` or :meth:`Timedelta.to_timedelta64`
instead to get an ndarray of values or numpy.timedelta64,
respectively.
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- If 'raise', then invalid parsing will raise an exception.
- If 'coerce', then invalid parsing will be set as NaT.
- If 'ignore', then invalid parsing will return the input.
Returns
-------
timedelta64 or numpy.array of timedelta64
Output type returned if parsing succeeded.
See Also
--------
DataFrame.astype : Cast argument to a specified dtype.
to_datetime : Convert argument to datetime.
Examples
--------
Parsing a single string to a Timedelta:
>>> pd.to_timedelta('1 days 06:05:01.00003')
Timedelta('1 days 06:05:01.000030')
>>> pd.to_timedelta('15.5us')
Timedelta('0 days 00:00:00.000015')
Parsing a list or array of strings:
>>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015', NaT],
dtype='timedelta64[ns]', freq=None)
Converting numbers by specifying the `unit` keyword argument:
>>> pd.to_timedelta(np.arange(5), unit='s')
TimedeltaIndex(['00:00:00', '00:00:01', '00:00:02',
'00:00:03', '00:00:04'],
dtype='timedelta64[ns]', freq=None)
>>> pd.to_timedelta(np.arange(5), unit='d')
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq=None)
Returning an ndarray by using the 'box' keyword argument:
>>> pd.to_timedelta(np.arange(5), box=False)
array([0, 1, 2, 3, 4], dtype='timedelta64[ns]')
"""
unit = parse_timedelta_unit(unit)
if errors not in ('ignore', 'raise', 'coerce'):
raise ValueError("errors must be one of 'ignore', "
"'raise', or 'coerce'}")
if unit in {'Y', 'y', 'M'}:
warnings.warn("M and Y units are deprecated and "
"will be removed in a future version.",
FutureWarning, stacklevel=2)
if arg is None:
return arg
elif isinstance(arg, ABCSeries):
values = _convert_listlike(arg._values, unit=unit,
box=False, errors=errors)
return arg._constructor(values, index=arg.index, name=arg.name)
elif isinstance(arg, ABCIndexClass):
return _convert_listlike(arg, unit=unit, box=box,
errors=errors, name=arg.name)
elif isinstance(arg, np.ndarray) and arg.ndim == 0:
# extract array scalar and process below
arg = arg.item()
elif is_list_like(arg) and getattr(arg, 'ndim', 1) == 1:
return _convert_listlike(arg, unit=unit, box=box, errors=errors)
elif getattr(arg, 'ndim', 1) > 1:
raise TypeError('arg must be a string, timedelta, list, tuple, '
'1-d array, or Series')
# ...so it must be a scalar value. Return scalar.
return _coerce_scalar_to_timedelta_type(arg, unit=unit,
box=box, errors=errors) | [
"Convert",
"argument",
"to",
"timedelta",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/tools/timedeltas.py#L20-L128 | [
"def",
"to_timedelta",
"(",
"arg",
",",
"unit",
"=",
"'ns'",
",",
"box",
"=",
"True",
",",
"errors",
"=",
"'raise'",
")",
":",
"unit",
"=",
"parse_timedelta_unit",
"(",
"unit",
")",
"if",
"errors",
"not",
"in",
"(",
"'ignore'",
",",
"'raise'",
",",
"'coerce'",
")",
":",
"raise",
"ValueError",
"(",
"\"errors must be one of 'ignore', \"",
"\"'raise', or 'coerce'}\"",
")",
"if",
"unit",
"in",
"{",
"'Y'",
",",
"'y'",
",",
"'M'",
"}",
":",
"warnings",
".",
"warn",
"(",
"\"M and Y units are deprecated and \"",
"\"will be removed in a future version.\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"arg",
"is",
"None",
":",
"return",
"arg",
"elif",
"isinstance",
"(",
"arg",
",",
"ABCSeries",
")",
":",
"values",
"=",
"_convert_listlike",
"(",
"arg",
".",
"_values",
",",
"unit",
"=",
"unit",
",",
"box",
"=",
"False",
",",
"errors",
"=",
"errors",
")",
"return",
"arg",
".",
"_constructor",
"(",
"values",
",",
"index",
"=",
"arg",
".",
"index",
",",
"name",
"=",
"arg",
".",
"name",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"ABCIndexClass",
")",
":",
"return",
"_convert_listlike",
"(",
"arg",
",",
"unit",
"=",
"unit",
",",
"box",
"=",
"box",
",",
"errors",
"=",
"errors",
",",
"name",
"=",
"arg",
".",
"name",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"np",
".",
"ndarray",
")",
"and",
"arg",
".",
"ndim",
"==",
"0",
":",
"# extract array scalar and process below",
"arg",
"=",
"arg",
".",
"item",
"(",
")",
"elif",
"is_list_like",
"(",
"arg",
")",
"and",
"getattr",
"(",
"arg",
",",
"'ndim'",
",",
"1",
")",
"==",
"1",
":",
"return",
"_convert_listlike",
"(",
"arg",
",",
"unit",
"=",
"unit",
",",
"box",
"=",
"box",
",",
"errors",
"=",
"errors",
")",
"elif",
"getattr",
"(",
"arg",
",",
"'ndim'",
",",
"1",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"'arg must be a string, timedelta, list, tuple, '",
"'1-d array, or Series'",
")",
"# ...so it must be a scalar value. Return scalar.",
"return",
"_coerce_scalar_to_timedelta_type",
"(",
"arg",
",",
"unit",
"=",
"unit",
",",
"box",
"=",
"box",
",",
"errors",
"=",
"errors",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _coerce_scalar_to_timedelta_type | Convert string 'r' to a timedelta object. | pandas/core/tools/timedeltas.py | def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'):
"""Convert string 'r' to a timedelta object."""
try:
result = Timedelta(r, unit)
if not box:
# explicitly view as timedelta64 for case when result is pd.NaT
result = result.asm8.view('timedelta64[ns]')
except ValueError:
if errors == 'raise':
raise
elif errors == 'ignore':
return r
# coerce
result = NaT
return result | def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'):
"""Convert string 'r' to a timedelta object."""
try:
result = Timedelta(r, unit)
if not box:
# explicitly view as timedelta64 for case when result is pd.NaT
result = result.asm8.view('timedelta64[ns]')
except ValueError:
if errors == 'raise':
raise
elif errors == 'ignore':
return r
# coerce
result = NaT
return result | [
"Convert",
"string",
"r",
"to",
"a",
"timedelta",
"object",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/tools/timedeltas.py#L131-L148 | [
"def",
"_coerce_scalar_to_timedelta_type",
"(",
"r",
",",
"unit",
"=",
"'ns'",
",",
"box",
"=",
"True",
",",
"errors",
"=",
"'raise'",
")",
":",
"try",
":",
"result",
"=",
"Timedelta",
"(",
"r",
",",
"unit",
")",
"if",
"not",
"box",
":",
"# explicitly view as timedelta64 for case when result is pd.NaT",
"result",
"=",
"result",
".",
"asm8",
".",
"view",
"(",
"'timedelta64[ns]'",
")",
"except",
"ValueError",
":",
"if",
"errors",
"==",
"'raise'",
":",
"raise",
"elif",
"errors",
"==",
"'ignore'",
":",
"return",
"r",
"# coerce",
"result",
"=",
"NaT",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _convert_listlike | Convert a list of objects to a timedelta index object. | pandas/core/tools/timedeltas.py | def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None):
"""Convert a list of objects to a timedelta index object."""
if isinstance(arg, (list, tuple)) or not hasattr(arg, 'dtype'):
# This is needed only to ensure that in the case where we end up
# returning arg (errors == "ignore"), and where the input is a
# generator, we return a useful list-like instead of a
# used-up generator
arg = np.array(list(arg), dtype=object)
try:
value = sequence_to_td64ns(arg, unit=unit,
errors=errors, copy=False)[0]
except ValueError:
if errors == 'ignore':
return arg
else:
# This else-block accounts for the cases when errors='raise'
# and errors='coerce'. If errors == 'raise', these errors
# should be raised. If errors == 'coerce', we shouldn't
# expect any errors to be raised, since all parsing errors
# cause coercion to pd.NaT. However, if an error / bug is
# introduced that causes an Exception to be raised, we would
# like to surface it.
raise
if box:
from pandas import TimedeltaIndex
value = TimedeltaIndex(value, unit='ns', name=name)
return value | def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None):
"""Convert a list of objects to a timedelta index object."""
if isinstance(arg, (list, tuple)) or not hasattr(arg, 'dtype'):
# This is needed only to ensure that in the case where we end up
# returning arg (errors == "ignore"), and where the input is a
# generator, we return a useful list-like instead of a
# used-up generator
arg = np.array(list(arg), dtype=object)
try:
value = sequence_to_td64ns(arg, unit=unit,
errors=errors, copy=False)[0]
except ValueError:
if errors == 'ignore':
return arg
else:
# This else-block accounts for the cases when errors='raise'
# and errors='coerce'. If errors == 'raise', these errors
# should be raised. If errors == 'coerce', we shouldn't
# expect any errors to be raised, since all parsing errors
# cause coercion to pd.NaT. However, if an error / bug is
# introduced that causes an Exception to be raised, we would
# like to surface it.
raise
if box:
from pandas import TimedeltaIndex
value = TimedeltaIndex(value, unit='ns', name=name)
return value | [
"Convert",
"a",
"list",
"of",
"objects",
"to",
"a",
"timedelta",
"index",
"object",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/tools/timedeltas.py#L151-L180 | [
"def",
"_convert_listlike",
"(",
"arg",
",",
"unit",
"=",
"'ns'",
",",
"box",
"=",
"True",
",",
"errors",
"=",
"'raise'",
",",
"name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"(",
"list",
",",
"tuple",
")",
")",
"or",
"not",
"hasattr",
"(",
"arg",
",",
"'dtype'",
")",
":",
"# This is needed only to ensure that in the case where we end up",
"# returning arg (errors == \"ignore\"), and where the input is a",
"# generator, we return a useful list-like instead of a",
"# used-up generator",
"arg",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"arg",
")",
",",
"dtype",
"=",
"object",
")",
"try",
":",
"value",
"=",
"sequence_to_td64ns",
"(",
"arg",
",",
"unit",
"=",
"unit",
",",
"errors",
"=",
"errors",
",",
"copy",
"=",
"False",
")",
"[",
"0",
"]",
"except",
"ValueError",
":",
"if",
"errors",
"==",
"'ignore'",
":",
"return",
"arg",
"else",
":",
"# This else-block accounts for the cases when errors='raise'",
"# and errors='coerce'. If errors == 'raise', these errors",
"# should be raised. If errors == 'coerce', we shouldn't",
"# expect any errors to be raised, since all parsing errors",
"# cause coercion to pd.NaT. However, if an error / bug is",
"# introduced that causes an Exception to be raised, we would",
"# like to surface it.",
"raise",
"if",
"box",
":",
"from",
"pandas",
"import",
"TimedeltaIndex",
"value",
"=",
"TimedeltaIndex",
"(",
"value",
",",
"unit",
"=",
"'ns'",
",",
"name",
"=",
"name",
")",
"return",
"value"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | generate_range | Generates a sequence of dates corresponding to the specified time
offset. Similar to dateutil.rrule except uses pandas DateOffset
objects to represent time increments.
Parameters
----------
start : datetime (default None)
end : datetime (default None)
periods : int, (default None)
offset : DateOffset, (default BDay())
Notes
-----
* This method is faster for generating weekdays than dateutil.rrule
* At least two of (start, end, periods) must be specified.
* If both start and end are specified, the returned dates will
satisfy start <= date <= end.
Returns
-------
dates : generator object | pandas/tseries/offsets.py | def generate_range(start=None, end=None, periods=None, offset=BDay()):
"""
Generates a sequence of dates corresponding to the specified time
offset. Similar to dateutil.rrule except uses pandas DateOffset
objects to represent time increments.
Parameters
----------
start : datetime (default None)
end : datetime (default None)
periods : int, (default None)
offset : DateOffset, (default BDay())
Notes
-----
* This method is faster for generating weekdays than dateutil.rrule
* At least two of (start, end, periods) must be specified.
* If both start and end are specified, the returned dates will
satisfy start <= date <= end.
Returns
-------
dates : generator object
"""
from pandas.tseries.frequencies import to_offset
offset = to_offset(offset)
start = to_datetime(start)
end = to_datetime(end)
if start and not offset.onOffset(start):
start = offset.rollforward(start)
elif end and not offset.onOffset(end):
end = offset.rollback(end)
if periods is None and end < start and offset.n >= 0:
end = None
periods = 0
if end is None:
end = start + (periods - 1) * offset
if start is None:
start = end - (periods - 1) * offset
cur = start
if offset.n >= 0:
while cur <= end:
yield cur
# faster than cur + offset
next_date = offset.apply(cur)
if next_date <= cur:
raise ValueError('Offset {offset} did not increment date'
.format(offset=offset))
cur = next_date
else:
while cur >= end:
yield cur
# faster than cur + offset
next_date = offset.apply(cur)
if next_date >= cur:
raise ValueError('Offset {offset} did not decrement date'
.format(offset=offset))
cur = next_date | def generate_range(start=None, end=None, periods=None, offset=BDay()):
"""
Generates a sequence of dates corresponding to the specified time
offset. Similar to dateutil.rrule except uses pandas DateOffset
objects to represent time increments.
Parameters
----------
start : datetime (default None)
end : datetime (default None)
periods : int, (default None)
offset : DateOffset, (default BDay())
Notes
-----
* This method is faster for generating weekdays than dateutil.rrule
* At least two of (start, end, periods) must be specified.
* If both start and end are specified, the returned dates will
satisfy start <= date <= end.
Returns
-------
dates : generator object
"""
from pandas.tseries.frequencies import to_offset
offset = to_offset(offset)
start = to_datetime(start)
end = to_datetime(end)
if start and not offset.onOffset(start):
start = offset.rollforward(start)
elif end and not offset.onOffset(end):
end = offset.rollback(end)
if periods is None and end < start and offset.n >= 0:
end = None
periods = 0
if end is None:
end = start + (periods - 1) * offset
if start is None:
start = end - (periods - 1) * offset
cur = start
if offset.n >= 0:
while cur <= end:
yield cur
# faster than cur + offset
next_date = offset.apply(cur)
if next_date <= cur:
raise ValueError('Offset {offset} did not increment date'
.format(offset=offset))
cur = next_date
else:
while cur >= end:
yield cur
# faster than cur + offset
next_date = offset.apply(cur)
if next_date >= cur:
raise ValueError('Offset {offset} did not decrement date'
.format(offset=offset))
cur = next_date | [
"Generates",
"a",
"sequence",
"of",
"dates",
"corresponding",
"to",
"the",
"specified",
"time",
"offset",
".",
"Similar",
"to",
"dateutil",
".",
"rrule",
"except",
"uses",
"pandas",
"DateOffset",
"objects",
"to",
"represent",
"time",
"increments",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/offsets.py#L2412-L2478 | [
"def",
"generate_range",
"(",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"periods",
"=",
"None",
",",
"offset",
"=",
"BDay",
"(",
")",
")",
":",
"from",
"pandas",
".",
"tseries",
".",
"frequencies",
"import",
"to_offset",
"offset",
"=",
"to_offset",
"(",
"offset",
")",
"start",
"=",
"to_datetime",
"(",
"start",
")",
"end",
"=",
"to_datetime",
"(",
"end",
")",
"if",
"start",
"and",
"not",
"offset",
".",
"onOffset",
"(",
"start",
")",
":",
"start",
"=",
"offset",
".",
"rollforward",
"(",
"start",
")",
"elif",
"end",
"and",
"not",
"offset",
".",
"onOffset",
"(",
"end",
")",
":",
"end",
"=",
"offset",
".",
"rollback",
"(",
"end",
")",
"if",
"periods",
"is",
"None",
"and",
"end",
"<",
"start",
"and",
"offset",
".",
"n",
">=",
"0",
":",
"end",
"=",
"None",
"periods",
"=",
"0",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"start",
"+",
"(",
"periods",
"-",
"1",
")",
"*",
"offset",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"end",
"-",
"(",
"periods",
"-",
"1",
")",
"*",
"offset",
"cur",
"=",
"start",
"if",
"offset",
".",
"n",
">=",
"0",
":",
"while",
"cur",
"<=",
"end",
":",
"yield",
"cur",
"# faster than cur + offset",
"next_date",
"=",
"offset",
".",
"apply",
"(",
"cur",
")",
"if",
"next_date",
"<=",
"cur",
":",
"raise",
"ValueError",
"(",
"'Offset {offset} did not increment date'",
".",
"format",
"(",
"offset",
"=",
"offset",
")",
")",
"cur",
"=",
"next_date",
"else",
":",
"while",
"cur",
">=",
"end",
":",
"yield",
"cur",
"# faster than cur + offset",
"next_date",
"=",
"offset",
".",
"apply",
"(",
"cur",
")",
"if",
"next_date",
">=",
"cur",
":",
"raise",
"ValueError",
"(",
"'Offset {offset} did not decrement date'",
".",
"format",
"(",
"offset",
"=",
"offset",
")",
")",
"cur",
"=",
"next_date"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DateOffset.apply_index | Vectorized apply of DateOffset to DatetimeIndex,
raises NotImplentedError for offsets without a
vectorized implementation.
Parameters
----------
i : DatetimeIndex
Returns
-------
y : DatetimeIndex | pandas/tseries/offsets.py | def apply_index(self, i):
"""
Vectorized apply of DateOffset to DatetimeIndex,
raises NotImplentedError for offsets without a
vectorized implementation.
Parameters
----------
i : DatetimeIndex
Returns
-------
y : DatetimeIndex
"""
if type(self) is not DateOffset:
raise NotImplementedError("DateOffset subclass {name} "
"does not have a vectorized "
"implementation".format(
name=self.__class__.__name__))
kwds = self.kwds
relativedelta_fast = {'years', 'months', 'weeks', 'days', 'hours',
'minutes', 'seconds', 'microseconds'}
# relativedelta/_offset path only valid for base DateOffset
if (self._use_relativedelta and
set(kwds).issubset(relativedelta_fast)):
months = ((kwds.get('years', 0) * 12 +
kwds.get('months', 0)) * self.n)
if months:
shifted = liboffsets.shift_months(i.asi8, months)
i = type(i)(shifted, freq=i.freq, dtype=i.dtype)
weeks = (kwds.get('weeks', 0)) * self.n
if weeks:
# integer addition on PeriodIndex is deprecated,
# so we directly use _time_shift instead
asper = i.to_period('W')
if not isinstance(asper._data, np.ndarray):
# unwrap PeriodIndex --> PeriodArray
asper = asper._data
shifted = asper._time_shift(weeks)
i = shifted.to_timestamp() + i.to_perioddelta('W')
timedelta_kwds = {k: v for k, v in kwds.items()
if k in ['days', 'hours', 'minutes',
'seconds', 'microseconds']}
if timedelta_kwds:
delta = Timedelta(**timedelta_kwds)
i = i + (self.n * delta)
return i
elif not self._use_relativedelta and hasattr(self, '_offset'):
# timedelta
return i + (self._offset * self.n)
else:
# relativedelta with other keywords
kwd = set(kwds) - relativedelta_fast
raise NotImplementedError("DateOffset with relativedelta "
"keyword(s) {kwd} not able to be "
"applied vectorized".format(kwd=kwd)) | def apply_index(self, i):
"""
Vectorized apply of DateOffset to DatetimeIndex,
raises NotImplentedError for offsets without a
vectorized implementation.
Parameters
----------
i : DatetimeIndex
Returns
-------
y : DatetimeIndex
"""
if type(self) is not DateOffset:
raise NotImplementedError("DateOffset subclass {name} "
"does not have a vectorized "
"implementation".format(
name=self.__class__.__name__))
kwds = self.kwds
relativedelta_fast = {'years', 'months', 'weeks', 'days', 'hours',
'minutes', 'seconds', 'microseconds'}
# relativedelta/_offset path only valid for base DateOffset
if (self._use_relativedelta and
set(kwds).issubset(relativedelta_fast)):
months = ((kwds.get('years', 0) * 12 +
kwds.get('months', 0)) * self.n)
if months:
shifted = liboffsets.shift_months(i.asi8, months)
i = type(i)(shifted, freq=i.freq, dtype=i.dtype)
weeks = (kwds.get('weeks', 0)) * self.n
if weeks:
# integer addition on PeriodIndex is deprecated,
# so we directly use _time_shift instead
asper = i.to_period('W')
if not isinstance(asper._data, np.ndarray):
# unwrap PeriodIndex --> PeriodArray
asper = asper._data
shifted = asper._time_shift(weeks)
i = shifted.to_timestamp() + i.to_perioddelta('W')
timedelta_kwds = {k: v for k, v in kwds.items()
if k in ['days', 'hours', 'minutes',
'seconds', 'microseconds']}
if timedelta_kwds:
delta = Timedelta(**timedelta_kwds)
i = i + (self.n * delta)
return i
elif not self._use_relativedelta and hasattr(self, '_offset'):
# timedelta
return i + (self._offset * self.n)
else:
# relativedelta with other keywords
kwd = set(kwds) - relativedelta_fast
raise NotImplementedError("DateOffset with relativedelta "
"keyword(s) {kwd} not able to be "
"applied vectorized".format(kwd=kwd)) | [
"Vectorized",
"apply",
"of",
"DateOffset",
"to",
"DatetimeIndex",
"raises",
"NotImplentedError",
"for",
"offsets",
"without",
"a",
"vectorized",
"implementation",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/offsets.py#L245-L304 | [
"def",
"apply_index",
"(",
"self",
",",
"i",
")",
":",
"if",
"type",
"(",
"self",
")",
"is",
"not",
"DateOffset",
":",
"raise",
"NotImplementedError",
"(",
"\"DateOffset subclass {name} \"",
"\"does not have a vectorized \"",
"\"implementation\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"kwds",
"=",
"self",
".",
"kwds",
"relativedelta_fast",
"=",
"{",
"'years'",
",",
"'months'",
",",
"'weeks'",
",",
"'days'",
",",
"'hours'",
",",
"'minutes'",
",",
"'seconds'",
",",
"'microseconds'",
"}",
"# relativedelta/_offset path only valid for base DateOffset",
"if",
"(",
"self",
".",
"_use_relativedelta",
"and",
"set",
"(",
"kwds",
")",
".",
"issubset",
"(",
"relativedelta_fast",
")",
")",
":",
"months",
"=",
"(",
"(",
"kwds",
".",
"get",
"(",
"'years'",
",",
"0",
")",
"*",
"12",
"+",
"kwds",
".",
"get",
"(",
"'months'",
",",
"0",
")",
")",
"*",
"self",
".",
"n",
")",
"if",
"months",
":",
"shifted",
"=",
"liboffsets",
".",
"shift_months",
"(",
"i",
".",
"asi8",
",",
"months",
")",
"i",
"=",
"type",
"(",
"i",
")",
"(",
"shifted",
",",
"freq",
"=",
"i",
".",
"freq",
",",
"dtype",
"=",
"i",
".",
"dtype",
")",
"weeks",
"=",
"(",
"kwds",
".",
"get",
"(",
"'weeks'",
",",
"0",
")",
")",
"*",
"self",
".",
"n",
"if",
"weeks",
":",
"# integer addition on PeriodIndex is deprecated,",
"# so we directly use _time_shift instead",
"asper",
"=",
"i",
".",
"to_period",
"(",
"'W'",
")",
"if",
"not",
"isinstance",
"(",
"asper",
".",
"_data",
",",
"np",
".",
"ndarray",
")",
":",
"# unwrap PeriodIndex --> PeriodArray",
"asper",
"=",
"asper",
".",
"_data",
"shifted",
"=",
"asper",
".",
"_time_shift",
"(",
"weeks",
")",
"i",
"=",
"shifted",
".",
"to_timestamp",
"(",
")",
"+",
"i",
".",
"to_perioddelta",
"(",
"'W'",
")",
"timedelta_kwds",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwds",
".",
"items",
"(",
")",
"if",
"k",
"in",
"[",
"'days'",
",",
"'hours'",
",",
"'minutes'",
",",
"'seconds'",
",",
"'microseconds'",
"]",
"}",
"if",
"timedelta_kwds",
":",
"delta",
"=",
"Timedelta",
"(",
"*",
"*",
"timedelta_kwds",
")",
"i",
"=",
"i",
"+",
"(",
"self",
".",
"n",
"*",
"delta",
")",
"return",
"i",
"elif",
"not",
"self",
".",
"_use_relativedelta",
"and",
"hasattr",
"(",
"self",
",",
"'_offset'",
")",
":",
"# timedelta",
"return",
"i",
"+",
"(",
"self",
".",
"_offset",
"*",
"self",
".",
"n",
")",
"else",
":",
"# relativedelta with other keywords",
"kwd",
"=",
"set",
"(",
"kwds",
")",
"-",
"relativedelta_fast",
"raise",
"NotImplementedError",
"(",
"\"DateOffset with relativedelta \"",
"\"keyword(s) {kwd} not able to be \"",
"\"applied vectorized\"",
".",
"format",
"(",
"kwd",
"=",
"kwd",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DateOffset.rollback | Roll provided date backward to next offset only if not on offset. | pandas/tseries/offsets.py | def rollback(self, dt):
"""
Roll provided date backward to next offset only if not on offset.
"""
dt = as_timestamp(dt)
if not self.onOffset(dt):
dt = dt - self.__class__(1, normalize=self.normalize, **self.kwds)
return dt | def rollback(self, dt):
"""
Roll provided date backward to next offset only if not on offset.
"""
dt = as_timestamp(dt)
if not self.onOffset(dt):
dt = dt - self.__class__(1, normalize=self.normalize, **self.kwds)
return dt | [
"Roll",
"provided",
"date",
"backward",
"to",
"next",
"offset",
"only",
"if",
"not",
"on",
"offset",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/offsets.py#L333-L340 | [
"def",
"rollback",
"(",
"self",
",",
"dt",
")",
":",
"dt",
"=",
"as_timestamp",
"(",
"dt",
")",
"if",
"not",
"self",
".",
"onOffset",
"(",
"dt",
")",
":",
"dt",
"=",
"dt",
"-",
"self",
".",
"__class__",
"(",
"1",
",",
"normalize",
"=",
"self",
".",
"normalize",
",",
"*",
"*",
"self",
".",
"kwds",
")",
"return",
"dt"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DateOffset.rollforward | Roll provided date forward to next offset only if not on offset. | pandas/tseries/offsets.py | def rollforward(self, dt):
"""
Roll provided date forward to next offset only if not on offset.
"""
dt = as_timestamp(dt)
if not self.onOffset(dt):
dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds)
return dt | def rollforward(self, dt):
"""
Roll provided date forward to next offset only if not on offset.
"""
dt = as_timestamp(dt)
if not self.onOffset(dt):
dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds)
return dt | [
"Roll",
"provided",
"date",
"forward",
"to",
"next",
"offset",
"only",
"if",
"not",
"on",
"offset",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/offsets.py#L342-L349 | [
"def",
"rollforward",
"(",
"self",
",",
"dt",
")",
":",
"dt",
"=",
"as_timestamp",
"(",
"dt",
")",
"if",
"not",
"self",
".",
"onOffset",
"(",
"dt",
")",
":",
"dt",
"=",
"dt",
"+",
"self",
".",
"__class__",
"(",
"1",
",",
"normalize",
"=",
"self",
".",
"normalize",
",",
"*",
"*",
"self",
".",
"kwds",
")",
"return",
"dt"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | BusinessHourMixin.next_bday | Used for moving to next business day. | pandas/tseries/offsets.py | def next_bday(self):
"""
Used for moving to next business day.
"""
if self.n >= 0:
nb_offset = 1
else:
nb_offset = -1
if self._prefix.startswith('C'):
# CustomBusinessHour
return CustomBusinessDay(n=nb_offset,
weekmask=self.weekmask,
holidays=self.holidays,
calendar=self.calendar)
else:
return BusinessDay(n=nb_offset) | def next_bday(self):
"""
Used for moving to next business day.
"""
if self.n >= 0:
nb_offset = 1
else:
nb_offset = -1
if self._prefix.startswith('C'):
# CustomBusinessHour
return CustomBusinessDay(n=nb_offset,
weekmask=self.weekmask,
holidays=self.holidays,
calendar=self.calendar)
else:
return BusinessDay(n=nb_offset) | [
"Used",
"for",
"moving",
"to",
"next",
"business",
"day",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/offsets.py#L579-L594 | [
"def",
"next_bday",
"(",
"self",
")",
":",
"if",
"self",
".",
"n",
">=",
"0",
":",
"nb_offset",
"=",
"1",
"else",
":",
"nb_offset",
"=",
"-",
"1",
"if",
"self",
".",
"_prefix",
".",
"startswith",
"(",
"'C'",
")",
":",
"# CustomBusinessHour",
"return",
"CustomBusinessDay",
"(",
"n",
"=",
"nb_offset",
",",
"weekmask",
"=",
"self",
".",
"weekmask",
",",
"holidays",
"=",
"self",
".",
"holidays",
",",
"calendar",
"=",
"self",
".",
"calendar",
")",
"else",
":",
"return",
"BusinessDay",
"(",
"n",
"=",
"nb_offset",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | BusinessHourMixin._next_opening_time | If n is positive, return tomorrow's business day opening time.
Otherwise yesterday's business day's opening time.
Opening time always locates on BusinessDay.
Otherwise, closing time may not if business hour extends over midnight. | pandas/tseries/offsets.py | def _next_opening_time(self, other):
"""
If n is positive, return tomorrow's business day opening time.
Otherwise yesterday's business day's opening time.
Opening time always locates on BusinessDay.
Otherwise, closing time may not if business hour extends over midnight.
"""
if not self.next_bday.onOffset(other):
other = other + self.next_bday
else:
if self.n >= 0 and self.start < other.time():
other = other + self.next_bday
elif self.n < 0 and other.time() < self.start:
other = other + self.next_bday
return datetime(other.year, other.month, other.day,
self.start.hour, self.start.minute) | def _next_opening_time(self, other):
"""
If n is positive, return tomorrow's business day opening time.
Otherwise yesterday's business day's opening time.
Opening time always locates on BusinessDay.
Otherwise, closing time may not if business hour extends over midnight.
"""
if not self.next_bday.onOffset(other):
other = other + self.next_bday
else:
if self.n >= 0 and self.start < other.time():
other = other + self.next_bday
elif self.n < 0 and other.time() < self.start:
other = other + self.next_bday
return datetime(other.year, other.month, other.day,
self.start.hour, self.start.minute) | [
"If",
"n",
"is",
"positive",
"return",
"tomorrow",
"s",
"business",
"day",
"opening",
"time",
".",
"Otherwise",
"yesterday",
"s",
"business",
"day",
"s",
"opening",
"time",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/offsets.py#L605-L621 | [
"def",
"_next_opening_time",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"self",
".",
"next_bday",
".",
"onOffset",
"(",
"other",
")",
":",
"other",
"=",
"other",
"+",
"self",
".",
"next_bday",
"else",
":",
"if",
"self",
".",
"n",
">=",
"0",
"and",
"self",
".",
"start",
"<",
"other",
".",
"time",
"(",
")",
":",
"other",
"=",
"other",
"+",
"self",
".",
"next_bday",
"elif",
"self",
".",
"n",
"<",
"0",
"and",
"other",
".",
"time",
"(",
")",
"<",
"self",
".",
"start",
":",
"other",
"=",
"other",
"+",
"self",
".",
"next_bday",
"return",
"datetime",
"(",
"other",
".",
"year",
",",
"other",
".",
"month",
",",
"other",
".",
"day",
",",
"self",
".",
"start",
".",
"hour",
",",
"self",
".",
"start",
".",
"minute",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | BusinessHourMixin._get_business_hours_by_sec | Return business hours in a day by seconds. | pandas/tseries/offsets.py | def _get_business_hours_by_sec(self):
"""
Return business hours in a day by seconds.
"""
if self._get_daytime_flag:
# create dummy datetime to calculate businesshours in a day
dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)
until = datetime(2014, 4, 1, self.end.hour, self.end.minute)
return (until - dtstart).total_seconds()
else:
dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)
until = datetime(2014, 4, 2, self.end.hour, self.end.minute)
return (until - dtstart).total_seconds() | def _get_business_hours_by_sec(self):
"""
Return business hours in a day by seconds.
"""
if self._get_daytime_flag:
# create dummy datetime to calculate businesshours in a day
dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)
until = datetime(2014, 4, 1, self.end.hour, self.end.minute)
return (until - dtstart).total_seconds()
else:
dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)
until = datetime(2014, 4, 2, self.end.hour, self.end.minute)
return (until - dtstart).total_seconds() | [
"Return",
"business",
"hours",
"in",
"a",
"day",
"by",
"seconds",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/offsets.py#L639-L651 | [
"def",
"_get_business_hours_by_sec",
"(",
"self",
")",
":",
"if",
"self",
".",
"_get_daytime_flag",
":",
"# create dummy datetime to calculate businesshours in a day",
"dtstart",
"=",
"datetime",
"(",
"2014",
",",
"4",
",",
"1",
",",
"self",
".",
"start",
".",
"hour",
",",
"self",
".",
"start",
".",
"minute",
")",
"until",
"=",
"datetime",
"(",
"2014",
",",
"4",
",",
"1",
",",
"self",
".",
"end",
".",
"hour",
",",
"self",
".",
"end",
".",
"minute",
")",
"return",
"(",
"until",
"-",
"dtstart",
")",
".",
"total_seconds",
"(",
")",
"else",
":",
"dtstart",
"=",
"datetime",
"(",
"2014",
",",
"4",
",",
"1",
",",
"self",
".",
"start",
".",
"hour",
",",
"self",
".",
"start",
".",
"minute",
")",
"until",
"=",
"datetime",
"(",
"2014",
",",
"4",
",",
"2",
",",
"self",
".",
"end",
".",
"hour",
",",
"self",
".",
"end",
".",
"minute",
")",
"return",
"(",
"until",
"-",
"dtstart",
")",
".",
"total_seconds",
"(",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.