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 | Table.validate_metadata | create / validate metadata | pandas/io/pytables.py | def validate_metadata(self, existing):
""" create / validate metadata """
self.metadata = [
c.name for c in self.values_axes if c.metadata is not None] | def validate_metadata(self, existing):
""" create / validate metadata """
self.metadata = [
c.name for c in self.values_axes if c.metadata is not None] | [
"create",
"/",
"validate",
"metadata"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3130-L3133 | [
"def",
"validate_metadata",
"(",
"self",
",",
"existing",
")",
":",
"self",
".",
"metadata",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"self",
".",
"values_axes",
"if",
"c",
".",
"metadata",
"is",
"not",
"None",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.validate_multiindex | validate that we can store the multi-index; reset and return the
new object | pandas/io/pytables.py | def validate_multiindex(self, obj):
"""validate that we can store the multi-index; reset and return the
new object
"""
levels = [l if l is not None else "level_{0}".format(i)
for i, l in enumerate(obj.index.names)]
try:
return obj.reset_index(), levels
except ValueError:
raise ValueError("duplicate names/columns in the multi-index when "
"storing as a table") | def validate_multiindex(self, obj):
"""validate that we can store the multi-index; reset and return the
new object
"""
levels = [l if l is not None else "level_{0}".format(i)
for i, l in enumerate(obj.index.names)]
try:
return obj.reset_index(), levels
except ValueError:
raise ValueError("duplicate names/columns in the multi-index when "
"storing as a table") | [
"validate",
"that",
"we",
"can",
"store",
"the",
"multi",
"-",
"index",
";",
"reset",
"and",
"return",
"the",
"new",
"object"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3135-L3145 | [
"def",
"validate_multiindex",
"(",
"self",
",",
"obj",
")",
":",
"levels",
"=",
"[",
"l",
"if",
"l",
"is",
"not",
"None",
"else",
"\"level_{0}\"",
".",
"format",
"(",
"i",
")",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"obj",
".",
"index",
".",
"names",
")",
"]",
"try",
":",
"return",
"obj",
".",
"reset_index",
"(",
")",
",",
"levels",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"duplicate names/columns in the multi-index when \"",
"\"storing as a table\"",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.nrows_expected | based on our axes, compute the expected nrows | pandas/io/pytables.py | def nrows_expected(self):
""" based on our axes, compute the expected nrows """
return np.prod([i.cvalues.shape[0] for i in self.index_axes]) | def nrows_expected(self):
""" based on our axes, compute the expected nrows """
return np.prod([i.cvalues.shape[0] for i in self.index_axes]) | [
"based",
"on",
"our",
"axes",
"compute",
"the",
"expected",
"nrows"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3148-L3150 | [
"def",
"nrows_expected",
"(",
"self",
")",
":",
"return",
"np",
".",
"prod",
"(",
"[",
"i",
".",
"cvalues",
".",
"shape",
"[",
"0",
"]",
"for",
"i",
"in",
"self",
".",
"index_axes",
"]",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.data_orientation | return a tuple of my permutated axes, non_indexable at the front | pandas/io/pytables.py | def data_orientation(self):
"""return a tuple of my permutated axes, non_indexable at the front"""
return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes],
[int(a.axis) for a in self.index_axes])) | def data_orientation(self):
"""return a tuple of my permutated axes, non_indexable at the front"""
return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes],
[int(a.axis) for a in self.index_axes])) | [
"return",
"a",
"tuple",
"of",
"my",
"permutated",
"axes",
"non_indexable",
"at",
"the",
"front"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3188-L3191 | [
"def",
"data_orientation",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"itertools",
".",
"chain",
"(",
"[",
"int",
"(",
"a",
"[",
"0",
"]",
")",
"for",
"a",
"in",
"self",
".",
"non_index_axes",
"]",
",",
"[",
"int",
"(",
"a",
".",
"axis",
")",
"for",
"a",
"in",
"self",
".",
"index_axes",
"]",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.queryables | return a dict of the kinds allowable columns for this object | pandas/io/pytables.py | def queryables(self):
""" return a dict of the kinds allowable columns for this object """
# compute the values_axes queryables
return dict(
[(a.cname, a) for a in self.index_axes] +
[(self.storage_obj_type._AXIS_NAMES[axis], None)
for axis, values in self.non_index_axes] +
[(v.cname, v) for v in self.values_axes
if v.name in set(self.data_columns)]
) | def queryables(self):
""" return a dict of the kinds allowable columns for this object """
# compute the values_axes queryables
return dict(
[(a.cname, a) for a in self.index_axes] +
[(self.storage_obj_type._AXIS_NAMES[axis], None)
for axis, values in self.non_index_axes] +
[(v.cname, v) for v in self.values_axes
if v.name in set(self.data_columns)]
) | [
"return",
"a",
"dict",
"of",
"the",
"kinds",
"allowable",
"columns",
"for",
"this",
"object"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3193-L3203 | [
"def",
"queryables",
"(",
"self",
")",
":",
"# compute the values_axes queryables",
"return",
"dict",
"(",
"[",
"(",
"a",
".",
"cname",
",",
"a",
")",
"for",
"a",
"in",
"self",
".",
"index_axes",
"]",
"+",
"[",
"(",
"self",
".",
"storage_obj_type",
".",
"_AXIS_NAMES",
"[",
"axis",
"]",
",",
"None",
")",
"for",
"axis",
",",
"values",
"in",
"self",
".",
"non_index_axes",
"]",
"+",
"[",
"(",
"v",
".",
"cname",
",",
"v",
")",
"for",
"v",
"in",
"self",
".",
"values_axes",
"if",
"v",
".",
"name",
"in",
"set",
"(",
"self",
".",
"data_columns",
")",
"]",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table._get_metadata_path | return the metadata pathname for this key | pandas/io/pytables.py | def _get_metadata_path(self, key):
""" return the metadata pathname for this key """
return "{group}/meta/{key}/meta".format(group=self.group._v_pathname,
key=key) | def _get_metadata_path(self, key):
""" return the metadata pathname for this key """
return "{group}/meta/{key}/meta".format(group=self.group._v_pathname,
key=key) | [
"return",
"the",
"metadata",
"pathname",
"for",
"this",
"key"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3213-L3216 | [
"def",
"_get_metadata_path",
"(",
"self",
",",
"key",
")",
":",
"return",
"\"{group}/meta/{key}/meta\"",
".",
"format",
"(",
"group",
"=",
"self",
".",
"group",
".",
"_v_pathname",
",",
"key",
"=",
"key",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.write_metadata | write out a meta data array to the key as a fixed-format Series
Parameters
----------
key : string
values : ndarray | pandas/io/pytables.py | def write_metadata(self, key, values):
"""
write out a meta data array to the key as a fixed-format Series
Parameters
----------
key : string
values : ndarray
"""
values = Series(values)
self.parent.put(self._get_metadata_path(key), values, format='table',
encoding=self.encoding, errors=self.errors,
nan_rep=self.nan_rep) | def write_metadata(self, key, values):
"""
write out a meta data array to the key as a fixed-format Series
Parameters
----------
key : string
values : ndarray
"""
values = Series(values)
self.parent.put(self._get_metadata_path(key), values, format='table',
encoding=self.encoding, errors=self.errors,
nan_rep=self.nan_rep) | [
"write",
"out",
"a",
"meta",
"data",
"array",
"to",
"the",
"key",
"as",
"a",
"fixed",
"-",
"format",
"Series"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3218-L3231 | [
"def",
"write_metadata",
"(",
"self",
",",
"key",
",",
"values",
")",
":",
"values",
"=",
"Series",
"(",
"values",
")",
"self",
".",
"parent",
".",
"put",
"(",
"self",
".",
"_get_metadata_path",
"(",
"key",
")",
",",
"values",
",",
"format",
"=",
"'table'",
",",
"encoding",
"=",
"self",
".",
"encoding",
",",
"errors",
"=",
"self",
".",
"errors",
",",
"nan_rep",
"=",
"self",
".",
"nan_rep",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.read_metadata | return the meta data array for this key | pandas/io/pytables.py | def read_metadata(self, key):
""" return the meta data array for this key """
if getattr(getattr(self.group, 'meta', None), key, None) is not None:
return self.parent.select(self._get_metadata_path(key))
return None | def read_metadata(self, key):
""" return the meta data array for this key """
if getattr(getattr(self.group, 'meta', None), key, None) is not None:
return self.parent.select(self._get_metadata_path(key))
return None | [
"return",
"the",
"meta",
"data",
"array",
"for",
"this",
"key"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3233-L3237 | [
"def",
"read_metadata",
"(",
"self",
",",
"key",
")",
":",
"if",
"getattr",
"(",
"getattr",
"(",
"self",
".",
"group",
",",
"'meta'",
",",
"None",
")",
",",
"key",
",",
"None",
")",
"is",
"not",
"None",
":",
"return",
"self",
".",
"parent",
".",
"select",
"(",
"self",
".",
"_get_metadata_path",
"(",
"key",
")",
")",
"return",
"None"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.set_attrs | set our table type & indexables | pandas/io/pytables.py | def set_attrs(self):
""" set our table type & indexables """
self.attrs.table_type = str(self.table_type)
self.attrs.index_cols = self.index_cols()
self.attrs.values_cols = self.values_cols()
self.attrs.non_index_axes = self.non_index_axes
self.attrs.data_columns = self.data_columns
self.attrs.nan_rep = self.nan_rep
self.attrs.encoding = self.encoding
self.attrs.errors = self.errors
self.attrs.levels = self.levels
self.attrs.metadata = self.metadata
self.set_info() | def set_attrs(self):
""" set our table type & indexables """
self.attrs.table_type = str(self.table_type)
self.attrs.index_cols = self.index_cols()
self.attrs.values_cols = self.values_cols()
self.attrs.non_index_axes = self.non_index_axes
self.attrs.data_columns = self.data_columns
self.attrs.nan_rep = self.nan_rep
self.attrs.encoding = self.encoding
self.attrs.errors = self.errors
self.attrs.levels = self.levels
self.attrs.metadata = self.metadata
self.set_info() | [
"set",
"our",
"table",
"type",
"&",
"indexables"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3243-L3255 | [
"def",
"set_attrs",
"(",
"self",
")",
":",
"self",
".",
"attrs",
".",
"table_type",
"=",
"str",
"(",
"self",
".",
"table_type",
")",
"self",
".",
"attrs",
".",
"index_cols",
"=",
"self",
".",
"index_cols",
"(",
")",
"self",
".",
"attrs",
".",
"values_cols",
"=",
"self",
".",
"values_cols",
"(",
")",
"self",
".",
"attrs",
".",
"non_index_axes",
"=",
"self",
".",
"non_index_axes",
"self",
".",
"attrs",
".",
"data_columns",
"=",
"self",
".",
"data_columns",
"self",
".",
"attrs",
".",
"nan_rep",
"=",
"self",
".",
"nan_rep",
"self",
".",
"attrs",
".",
"encoding",
"=",
"self",
".",
"encoding",
"self",
".",
"attrs",
".",
"errors",
"=",
"self",
".",
"errors",
"self",
".",
"attrs",
".",
"levels",
"=",
"self",
".",
"levels",
"self",
".",
"attrs",
".",
"metadata",
"=",
"self",
".",
"metadata",
"self",
".",
"set_info",
"(",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.get_attrs | retrieve our attributes | pandas/io/pytables.py | def get_attrs(self):
""" retrieve our attributes """
self.non_index_axes = getattr(
self.attrs, 'non_index_axes', None) or []
self.data_columns = getattr(
self.attrs, 'data_columns', None) or []
self.info = getattr(
self.attrs, 'info', None) or dict()
self.nan_rep = getattr(self.attrs, 'nan_rep', None)
self.encoding = _ensure_encoding(
getattr(self.attrs, 'encoding', None))
self.errors = _ensure_decoded(getattr(self.attrs, 'errors', 'strict'))
self.levels = getattr(
self.attrs, 'levels', None) or []
self.index_axes = [
a.infer(self) for a in self.indexables if a.is_an_indexable
]
self.values_axes = [
a.infer(self) for a in self.indexables if not a.is_an_indexable
]
self.metadata = getattr(
self.attrs, 'metadata', None) or [] | def get_attrs(self):
""" retrieve our attributes """
self.non_index_axes = getattr(
self.attrs, 'non_index_axes', None) or []
self.data_columns = getattr(
self.attrs, 'data_columns', None) or []
self.info = getattr(
self.attrs, 'info', None) or dict()
self.nan_rep = getattr(self.attrs, 'nan_rep', None)
self.encoding = _ensure_encoding(
getattr(self.attrs, 'encoding', None))
self.errors = _ensure_decoded(getattr(self.attrs, 'errors', 'strict'))
self.levels = getattr(
self.attrs, 'levels', None) or []
self.index_axes = [
a.infer(self) for a in self.indexables if a.is_an_indexable
]
self.values_axes = [
a.infer(self) for a in self.indexables if not a.is_an_indexable
]
self.metadata = getattr(
self.attrs, 'metadata', None) or [] | [
"retrieve",
"our",
"attributes"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3257-L3278 | [
"def",
"get_attrs",
"(",
"self",
")",
":",
"self",
".",
"non_index_axes",
"=",
"getattr",
"(",
"self",
".",
"attrs",
",",
"'non_index_axes'",
",",
"None",
")",
"or",
"[",
"]",
"self",
".",
"data_columns",
"=",
"getattr",
"(",
"self",
".",
"attrs",
",",
"'data_columns'",
",",
"None",
")",
"or",
"[",
"]",
"self",
".",
"info",
"=",
"getattr",
"(",
"self",
".",
"attrs",
",",
"'info'",
",",
"None",
")",
"or",
"dict",
"(",
")",
"self",
".",
"nan_rep",
"=",
"getattr",
"(",
"self",
".",
"attrs",
",",
"'nan_rep'",
",",
"None",
")",
"self",
".",
"encoding",
"=",
"_ensure_encoding",
"(",
"getattr",
"(",
"self",
".",
"attrs",
",",
"'encoding'",
",",
"None",
")",
")",
"self",
".",
"errors",
"=",
"_ensure_decoded",
"(",
"getattr",
"(",
"self",
".",
"attrs",
",",
"'errors'",
",",
"'strict'",
")",
")",
"self",
".",
"levels",
"=",
"getattr",
"(",
"self",
".",
"attrs",
",",
"'levels'",
",",
"None",
")",
"or",
"[",
"]",
"self",
".",
"index_axes",
"=",
"[",
"a",
".",
"infer",
"(",
"self",
")",
"for",
"a",
"in",
"self",
".",
"indexables",
"if",
"a",
".",
"is_an_indexable",
"]",
"self",
".",
"values_axes",
"=",
"[",
"a",
".",
"infer",
"(",
"self",
")",
"for",
"a",
"in",
"self",
".",
"indexables",
"if",
"not",
"a",
".",
"is_an_indexable",
"]",
"self",
".",
"metadata",
"=",
"getattr",
"(",
"self",
".",
"attrs",
",",
"'metadata'",
",",
"None",
")",
"or",
"[",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.validate_version | are we trying to operate on an old version? | pandas/io/pytables.py | def validate_version(self, where=None):
""" are we trying to operate on an old version? """
if where is not None:
if (self.version[0] <= 0 and self.version[1] <= 10 and
self.version[2] < 1):
ws = incompatibility_doc % '.'.join(
[str(x) for x in self.version])
warnings.warn(ws, IncompatibilityWarning) | def validate_version(self, where=None):
""" are we trying to operate on an old version? """
if where is not None:
if (self.version[0] <= 0 and self.version[1] <= 10 and
self.version[2] < 1):
ws = incompatibility_doc % '.'.join(
[str(x) for x in self.version])
warnings.warn(ws, IncompatibilityWarning) | [
"are",
"we",
"trying",
"to",
"operate",
"on",
"an",
"old",
"version?"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3280-L3287 | [
"def",
"validate_version",
"(",
"self",
",",
"where",
"=",
"None",
")",
":",
"if",
"where",
"is",
"not",
"None",
":",
"if",
"(",
"self",
".",
"version",
"[",
"0",
"]",
"<=",
"0",
"and",
"self",
".",
"version",
"[",
"1",
"]",
"<=",
"10",
"and",
"self",
".",
"version",
"[",
"2",
"]",
"<",
"1",
")",
":",
"ws",
"=",
"incompatibility_doc",
"%",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"version",
"]",
")",
"warnings",
".",
"warn",
"(",
"ws",
",",
"IncompatibilityWarning",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.validate_min_itemsize | validate the min_itemisze doesn't contain items that are not in the
axes this needs data_columns to be defined | pandas/io/pytables.py | def validate_min_itemsize(self, min_itemsize):
"""validate the min_itemisze doesn't contain items that are not in the
axes this needs data_columns to be defined
"""
if min_itemsize is None:
return
if not isinstance(min_itemsize, dict):
return
q = self.queryables()
for k, v in min_itemsize.items():
# ok, apply generally
if k == 'values':
continue
if k not in q:
raise ValueError(
"min_itemsize has the key [{key}] which is not an axis or "
"data_column".format(key=k)) | def validate_min_itemsize(self, min_itemsize):
"""validate the min_itemisze doesn't contain items that are not in the
axes this needs data_columns to be defined
"""
if min_itemsize is None:
return
if not isinstance(min_itemsize, dict):
return
q = self.queryables()
for k, v in min_itemsize.items():
# ok, apply generally
if k == 'values':
continue
if k not in q:
raise ValueError(
"min_itemsize has the key [{key}] which is not an axis or "
"data_column".format(key=k)) | [
"validate",
"the",
"min_itemisze",
"doesn",
"t",
"contain",
"items",
"that",
"are",
"not",
"in",
"the",
"axes",
"this",
"needs",
"data_columns",
"to",
"be",
"defined"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3289-L3307 | [
"def",
"validate_min_itemsize",
"(",
"self",
",",
"min_itemsize",
")",
":",
"if",
"min_itemsize",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"min_itemsize",
",",
"dict",
")",
":",
"return",
"q",
"=",
"self",
".",
"queryables",
"(",
")",
"for",
"k",
",",
"v",
"in",
"min_itemsize",
".",
"items",
"(",
")",
":",
"# ok, apply generally",
"if",
"k",
"==",
"'values'",
":",
"continue",
"if",
"k",
"not",
"in",
"q",
":",
"raise",
"ValueError",
"(",
"\"min_itemsize has the key [{key}] which is not an axis or \"",
"\"data_column\"",
".",
"format",
"(",
"key",
"=",
"k",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.indexables | create/cache the indexables if they don't exist | pandas/io/pytables.py | def indexables(self):
""" create/cache the indexables if they don't exist """
if self._indexables is None:
self._indexables = []
# index columns
self._indexables.extend([
IndexCol(name=name, axis=axis, pos=i)
for i, (axis, name) in enumerate(self.attrs.index_cols)
])
# values columns
dc = set(self.data_columns)
base_pos = len(self._indexables)
def f(i, c):
klass = DataCol
if c in dc:
klass = DataIndexableCol
return klass.create_for_block(i=i, name=c, pos=base_pos + i,
version=self.version)
self._indexables.extend(
[f(i, c) for i, c in enumerate(self.attrs.values_cols)])
return self._indexables | def indexables(self):
""" create/cache the indexables if they don't exist """
if self._indexables is None:
self._indexables = []
# index columns
self._indexables.extend([
IndexCol(name=name, axis=axis, pos=i)
for i, (axis, name) in enumerate(self.attrs.index_cols)
])
# values columns
dc = set(self.data_columns)
base_pos = len(self._indexables)
def f(i, c):
klass = DataCol
if c in dc:
klass = DataIndexableCol
return klass.create_for_block(i=i, name=c, pos=base_pos + i,
version=self.version)
self._indexables.extend(
[f(i, c) for i, c in enumerate(self.attrs.values_cols)])
return self._indexables | [
"create",
"/",
"cache",
"the",
"indexables",
"if",
"they",
"don",
"t",
"exist"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3310-L3336 | [
"def",
"indexables",
"(",
"self",
")",
":",
"if",
"self",
".",
"_indexables",
"is",
"None",
":",
"self",
".",
"_indexables",
"=",
"[",
"]",
"# index columns",
"self",
".",
"_indexables",
".",
"extend",
"(",
"[",
"IndexCol",
"(",
"name",
"=",
"name",
",",
"axis",
"=",
"axis",
",",
"pos",
"=",
"i",
")",
"for",
"i",
",",
"(",
"axis",
",",
"name",
")",
"in",
"enumerate",
"(",
"self",
".",
"attrs",
".",
"index_cols",
")",
"]",
")",
"# values columns",
"dc",
"=",
"set",
"(",
"self",
".",
"data_columns",
")",
"base_pos",
"=",
"len",
"(",
"self",
".",
"_indexables",
")",
"def",
"f",
"(",
"i",
",",
"c",
")",
":",
"klass",
"=",
"DataCol",
"if",
"c",
"in",
"dc",
":",
"klass",
"=",
"DataIndexableCol",
"return",
"klass",
".",
"create_for_block",
"(",
"i",
"=",
"i",
",",
"name",
"=",
"c",
",",
"pos",
"=",
"base_pos",
"+",
"i",
",",
"version",
"=",
"self",
".",
"version",
")",
"self",
".",
"_indexables",
".",
"extend",
"(",
"[",
"f",
"(",
"i",
",",
"c",
")",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"self",
".",
"attrs",
".",
"values_cols",
")",
"]",
")",
"return",
"self",
".",
"_indexables"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.create_index | Create a pytables index on the specified columns
note: cannot index Time64Col() or ComplexCol currently;
PyTables must be >= 3.0
Parameters
----------
columns : False (don't create an index), True (create all columns
index), None or list_like (the indexers to index)
optlevel: optimization level (defaults to 6)
kind : kind of index (defaults to 'medium')
Exceptions
----------
raises if the node is not a table | pandas/io/pytables.py | def create_index(self, columns=None, optlevel=None, kind=None):
"""
Create a pytables index on the specified columns
note: cannot index Time64Col() or ComplexCol currently;
PyTables must be >= 3.0
Parameters
----------
columns : False (don't create an index), True (create all columns
index), None or list_like (the indexers to index)
optlevel: optimization level (defaults to 6)
kind : kind of index (defaults to 'medium')
Exceptions
----------
raises if the node is not a table
"""
if not self.infer_axes():
return
if columns is False:
return
# index all indexables and data_columns
if columns is None or columns is True:
columns = [a.cname for a in self.axes if a.is_data_indexable]
if not isinstance(columns, (tuple, list)):
columns = [columns]
kw = dict()
if optlevel is not None:
kw['optlevel'] = optlevel
if kind is not None:
kw['kind'] = kind
table = self.table
for c in columns:
v = getattr(table.cols, c, None)
if v is not None:
# remove the index if the kind/optlevel have changed
if v.is_indexed:
index = v.index
cur_optlevel = index.optlevel
cur_kind = index.kind
if kind is not None and cur_kind != kind:
v.remove_index()
else:
kw['kind'] = cur_kind
if optlevel is not None and cur_optlevel != optlevel:
v.remove_index()
else:
kw['optlevel'] = cur_optlevel
# create the index
if not v.is_indexed:
if v.type.startswith('complex'):
raise TypeError(
'Columns containing complex values can be stored '
'but cannot'
' be indexed when using table format. Either use '
'fixed format, set index=False, or do not include '
'the columns containing complex values to '
'data_columns when initializing the table.')
v.create_index(**kw) | def create_index(self, columns=None, optlevel=None, kind=None):
"""
Create a pytables index on the specified columns
note: cannot index Time64Col() or ComplexCol currently;
PyTables must be >= 3.0
Parameters
----------
columns : False (don't create an index), True (create all columns
index), None or list_like (the indexers to index)
optlevel: optimization level (defaults to 6)
kind : kind of index (defaults to 'medium')
Exceptions
----------
raises if the node is not a table
"""
if not self.infer_axes():
return
if columns is False:
return
# index all indexables and data_columns
if columns is None or columns is True:
columns = [a.cname for a in self.axes if a.is_data_indexable]
if not isinstance(columns, (tuple, list)):
columns = [columns]
kw = dict()
if optlevel is not None:
kw['optlevel'] = optlevel
if kind is not None:
kw['kind'] = kind
table = self.table
for c in columns:
v = getattr(table.cols, c, None)
if v is not None:
# remove the index if the kind/optlevel have changed
if v.is_indexed:
index = v.index
cur_optlevel = index.optlevel
cur_kind = index.kind
if kind is not None and cur_kind != kind:
v.remove_index()
else:
kw['kind'] = cur_kind
if optlevel is not None and cur_optlevel != optlevel:
v.remove_index()
else:
kw['optlevel'] = cur_optlevel
# create the index
if not v.is_indexed:
if v.type.startswith('complex'):
raise TypeError(
'Columns containing complex values can be stored '
'but cannot'
' be indexed when using table format. Either use '
'fixed format, set index=False, or do not include '
'the columns containing complex values to '
'data_columns when initializing the table.')
v.create_index(**kw) | [
"Create",
"a",
"pytables",
"index",
"on",
"the",
"specified",
"columns",
"note",
":",
"cannot",
"index",
"Time64Col",
"()",
"or",
"ComplexCol",
"currently",
";",
"PyTables",
"must",
"be",
">",
"=",
"3",
".",
"0"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3338-L3405 | [
"def",
"create_index",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"optlevel",
"=",
"None",
",",
"kind",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"infer_axes",
"(",
")",
":",
"return",
"if",
"columns",
"is",
"False",
":",
"return",
"# index all indexables and data_columns",
"if",
"columns",
"is",
"None",
"or",
"columns",
"is",
"True",
":",
"columns",
"=",
"[",
"a",
".",
"cname",
"for",
"a",
"in",
"self",
".",
"axes",
"if",
"a",
".",
"is_data_indexable",
"]",
"if",
"not",
"isinstance",
"(",
"columns",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"columns",
"=",
"[",
"columns",
"]",
"kw",
"=",
"dict",
"(",
")",
"if",
"optlevel",
"is",
"not",
"None",
":",
"kw",
"[",
"'optlevel'",
"]",
"=",
"optlevel",
"if",
"kind",
"is",
"not",
"None",
":",
"kw",
"[",
"'kind'",
"]",
"=",
"kind",
"table",
"=",
"self",
".",
"table",
"for",
"c",
"in",
"columns",
":",
"v",
"=",
"getattr",
"(",
"table",
".",
"cols",
",",
"c",
",",
"None",
")",
"if",
"v",
"is",
"not",
"None",
":",
"# remove the index if the kind/optlevel have changed",
"if",
"v",
".",
"is_indexed",
":",
"index",
"=",
"v",
".",
"index",
"cur_optlevel",
"=",
"index",
".",
"optlevel",
"cur_kind",
"=",
"index",
".",
"kind",
"if",
"kind",
"is",
"not",
"None",
"and",
"cur_kind",
"!=",
"kind",
":",
"v",
".",
"remove_index",
"(",
")",
"else",
":",
"kw",
"[",
"'kind'",
"]",
"=",
"cur_kind",
"if",
"optlevel",
"is",
"not",
"None",
"and",
"cur_optlevel",
"!=",
"optlevel",
":",
"v",
".",
"remove_index",
"(",
")",
"else",
":",
"kw",
"[",
"'optlevel'",
"]",
"=",
"cur_optlevel",
"# create the index",
"if",
"not",
"v",
".",
"is_indexed",
":",
"if",
"v",
".",
"type",
".",
"startswith",
"(",
"'complex'",
")",
":",
"raise",
"TypeError",
"(",
"'Columns containing complex values can be stored '",
"'but cannot'",
"' be indexed when using table format. Either use '",
"'fixed format, set index=False, or do not include '",
"'the columns containing complex values to '",
"'data_columns when initializing the table.'",
")",
"v",
".",
"create_index",
"(",
"*",
"*",
"kw",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.read_axes | create and return the axes sniffed from the table: return boolean
for success | pandas/io/pytables.py | def read_axes(self, where, **kwargs):
"""create and return the axes sniffed from the table: return boolean
for success
"""
# validate the version
self.validate_version(where)
# infer the data kind
if not self.infer_axes():
return False
# create the selection
self.selection = Selection(self, where=where, **kwargs)
values = self.selection.select()
# convert the data
for a in self.axes:
a.set_info(self.info)
a.convert(values, nan_rep=self.nan_rep, encoding=self.encoding,
errors=self.errors)
return True | def read_axes(self, where, **kwargs):
"""create and return the axes sniffed from the table: return boolean
for success
"""
# validate the version
self.validate_version(where)
# infer the data kind
if not self.infer_axes():
return False
# create the selection
self.selection = Selection(self, where=where, **kwargs)
values = self.selection.select()
# convert the data
for a in self.axes:
a.set_info(self.info)
a.convert(values, nan_rep=self.nan_rep, encoding=self.encoding,
errors=self.errors)
return True | [
"create",
"and",
"return",
"the",
"axes",
"sniffed",
"from",
"the",
"table",
":",
"return",
"boolean",
"for",
"success"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3407-L3429 | [
"def",
"read_axes",
"(",
"self",
",",
"where",
",",
"*",
"*",
"kwargs",
")",
":",
"# validate the version",
"self",
".",
"validate_version",
"(",
"where",
")",
"# infer the data kind",
"if",
"not",
"self",
".",
"infer_axes",
"(",
")",
":",
"return",
"False",
"# create the selection",
"self",
".",
"selection",
"=",
"Selection",
"(",
"self",
",",
"where",
"=",
"where",
",",
"*",
"*",
"kwargs",
")",
"values",
"=",
"self",
".",
"selection",
".",
"select",
"(",
")",
"# convert the data",
"for",
"a",
"in",
"self",
".",
"axes",
":",
"a",
".",
"set_info",
"(",
"self",
".",
"info",
")",
"a",
".",
"convert",
"(",
"values",
",",
"nan_rep",
"=",
"self",
".",
"nan_rep",
",",
"encoding",
"=",
"self",
".",
"encoding",
",",
"errors",
"=",
"self",
".",
"errors",
")",
"return",
"True"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.validate_data_columns | take the input data_columns and min_itemize and create a data
columns spec | pandas/io/pytables.py | def validate_data_columns(self, data_columns, min_itemsize):
"""take the input data_columns and min_itemize and create a data
columns spec
"""
if not len(self.non_index_axes):
return []
axis, axis_labels = self.non_index_axes[0]
info = self.info.get(axis, dict())
if info.get('type') == 'MultiIndex' and data_columns:
raise ValueError("cannot use a multi-index on axis [{0}] with "
"data_columns {1}".format(axis, data_columns))
# evaluate the passed data_columns, True == use all columns
# take only valide axis labels
if data_columns is True:
data_columns = list(axis_labels)
elif data_columns is None:
data_columns = []
# if min_itemsize is a dict, add the keys (exclude 'values')
if isinstance(min_itemsize, dict):
existing_data_columns = set(data_columns)
data_columns.extend([
k for k in min_itemsize.keys()
if k != 'values' and k not in existing_data_columns
])
# return valid columns in the order of our axis
return [c for c in data_columns if c in axis_labels] | def validate_data_columns(self, data_columns, min_itemsize):
"""take the input data_columns and min_itemize and create a data
columns spec
"""
if not len(self.non_index_axes):
return []
axis, axis_labels = self.non_index_axes[0]
info = self.info.get(axis, dict())
if info.get('type') == 'MultiIndex' and data_columns:
raise ValueError("cannot use a multi-index on axis [{0}] with "
"data_columns {1}".format(axis, data_columns))
# evaluate the passed data_columns, True == use all columns
# take only valide axis labels
if data_columns is True:
data_columns = list(axis_labels)
elif data_columns is None:
data_columns = []
# if min_itemsize is a dict, add the keys (exclude 'values')
if isinstance(min_itemsize, dict):
existing_data_columns = set(data_columns)
data_columns.extend([
k for k in min_itemsize.keys()
if k != 'values' and k not in existing_data_columns
])
# return valid columns in the order of our axis
return [c for c in data_columns if c in axis_labels] | [
"take",
"the",
"input",
"data_columns",
"and",
"min_itemize",
"and",
"create",
"a",
"data",
"columns",
"spec"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3435-L3466 | [
"def",
"validate_data_columns",
"(",
"self",
",",
"data_columns",
",",
"min_itemsize",
")",
":",
"if",
"not",
"len",
"(",
"self",
".",
"non_index_axes",
")",
":",
"return",
"[",
"]",
"axis",
",",
"axis_labels",
"=",
"self",
".",
"non_index_axes",
"[",
"0",
"]",
"info",
"=",
"self",
".",
"info",
".",
"get",
"(",
"axis",
",",
"dict",
"(",
")",
")",
"if",
"info",
".",
"get",
"(",
"'type'",
")",
"==",
"'MultiIndex'",
"and",
"data_columns",
":",
"raise",
"ValueError",
"(",
"\"cannot use a multi-index on axis [{0}] with \"",
"\"data_columns {1}\"",
".",
"format",
"(",
"axis",
",",
"data_columns",
")",
")",
"# evaluate the passed data_columns, True == use all columns",
"# take only valide axis labels",
"if",
"data_columns",
"is",
"True",
":",
"data_columns",
"=",
"list",
"(",
"axis_labels",
")",
"elif",
"data_columns",
"is",
"None",
":",
"data_columns",
"=",
"[",
"]",
"# if min_itemsize is a dict, add the keys (exclude 'values')",
"if",
"isinstance",
"(",
"min_itemsize",
",",
"dict",
")",
":",
"existing_data_columns",
"=",
"set",
"(",
"data_columns",
")",
"data_columns",
".",
"extend",
"(",
"[",
"k",
"for",
"k",
"in",
"min_itemsize",
".",
"keys",
"(",
")",
"if",
"k",
"!=",
"'values'",
"and",
"k",
"not",
"in",
"existing_data_columns",
"]",
")",
"# return valid columns in the order of our axis",
"return",
"[",
"c",
"for",
"c",
"in",
"data_columns",
"if",
"c",
"in",
"axis_labels",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.create_axes | create and return the axes
leagcy tables create an indexable column, indexable index,
non-indexable fields
Parameters:
-----------
axes: a list of the axes in order to create (names or numbers of
the axes)
obj : the object to create axes on
validate: validate the obj against an existing object already
written
min_itemsize: a dict of the min size for a column in bytes
nan_rep : a values to use for string column nan_rep
encoding : the encoding for string values
data_columns : a list of columns that we want to create separate to
allow indexing (or True will force all columns) | pandas/io/pytables.py | def create_axes(self, axes, obj, validate=True, nan_rep=None,
data_columns=None, min_itemsize=None, **kwargs):
""" create and return the axes
leagcy tables create an indexable column, indexable index,
non-indexable fields
Parameters:
-----------
axes: a list of the axes in order to create (names or numbers of
the axes)
obj : the object to create axes on
validate: validate the obj against an existing object already
written
min_itemsize: a dict of the min size for a column in bytes
nan_rep : a values to use for string column nan_rep
encoding : the encoding for string values
data_columns : a list of columns that we want to create separate to
allow indexing (or True will force all columns)
"""
# set the default axes if needed
if axes is None:
try:
axes = _AXES_MAP[type(obj)]
except KeyError:
raise TypeError(
"cannot properly create the storer for: [group->{group},"
"value->{value}]".format(
group=self.group._v_name, value=type(obj)))
# map axes to numbers
axes = [obj._get_axis_number(a) for a in axes]
# do we have an existing table (if so, use its axes & data_columns)
if self.infer_axes():
existing_table = self.copy()
existing_table.infer_axes()
axes = [a.axis for a in existing_table.index_axes]
data_columns = existing_table.data_columns
nan_rep = existing_table.nan_rep
self.encoding = existing_table.encoding
self.errors = existing_table.errors
self.info = copy.copy(existing_table.info)
else:
existing_table = None
# currently support on ndim-1 axes
if len(axes) != self.ndim - 1:
raise ValueError(
"currently only support ndim-1 indexers in an AppendableTable")
# create according to the new data
self.non_index_axes = []
self.data_columns = []
# nan_representation
if nan_rep is None:
nan_rep = 'nan'
self.nan_rep = nan_rep
# create axes to index and non_index
index_axes_map = dict()
for i, a in enumerate(obj.axes):
if i in axes:
name = obj._AXIS_NAMES[i]
index_axes_map[i] = _convert_index(
a, self.encoding, self.errors, self.format_type
).set_name(name).set_axis(i)
else:
# we might be able to change the axes on the appending data if
# necessary
append_axis = list(a)
if existing_table is not None:
indexer = len(self.non_index_axes)
exist_axis = existing_table.non_index_axes[indexer][1]
if not array_equivalent(np.array(append_axis),
np.array(exist_axis)):
# ahah! -> reindex
if array_equivalent(np.array(sorted(append_axis)),
np.array(sorted(exist_axis))):
append_axis = exist_axis
# the non_index_axes info
info = _get_info(self.info, i)
info['names'] = list(a.names)
info['type'] = a.__class__.__name__
self.non_index_axes.append((i, append_axis))
# set axis positions (based on the axes)
self.index_axes = [
index_axes_map[a].set_pos(j).update_info(self.info)
for j, a in enumerate(axes)
]
j = len(self.index_axes)
# check for column conflicts
for a in self.axes:
a.maybe_set_size(min_itemsize=min_itemsize)
# reindex by our non_index_axes & compute data_columns
for a in self.non_index_axes:
obj = _reindex_axis(obj, a[0], a[1])
def get_blk_items(mgr, blocks):
return [mgr.items.take(blk.mgr_locs) for blk in blocks]
# figure out data_columns and get out blocks
block_obj = self.get_object(obj)._consolidate()
blocks = block_obj._data.blocks
blk_items = get_blk_items(block_obj._data, blocks)
if len(self.non_index_axes):
axis, axis_labels = self.non_index_axes[0]
data_columns = self.validate_data_columns(
data_columns, min_itemsize)
if len(data_columns):
mgr = block_obj.reindex(
Index(axis_labels).difference(Index(data_columns)),
axis=axis
)._data
blocks = list(mgr.blocks)
blk_items = get_blk_items(mgr, blocks)
for c in data_columns:
mgr = block_obj.reindex([c], axis=axis)._data
blocks.extend(mgr.blocks)
blk_items.extend(get_blk_items(mgr, mgr.blocks))
# reorder the blocks in the same order as the existing_table if we can
if existing_table is not None:
by_items = {tuple(b_items.tolist()): (b, b_items)
for b, b_items in zip(blocks, blk_items)}
new_blocks = []
new_blk_items = []
for ea in existing_table.values_axes:
items = tuple(ea.values)
try:
b, b_items = by_items.pop(items)
new_blocks.append(b)
new_blk_items.append(b_items)
except (IndexError, KeyError):
raise ValueError(
"cannot match existing table structure for [{items}] "
"on appending data".format(
items=(','.join(pprint_thing(item) for
item in items))))
blocks = new_blocks
blk_items = new_blk_items
# add my values
self.values_axes = []
for i, (b, b_items) in enumerate(zip(blocks, blk_items)):
# shape of the data column are the indexable axes
klass = DataCol
name = None
# we have a data_column
if (data_columns and len(b_items) == 1 and
b_items[0] in data_columns):
klass = DataIndexableCol
name = b_items[0]
self.data_columns.append(name)
# make sure that we match up the existing columns
# if we have an existing table
if existing_table is not None and validate:
try:
existing_col = existing_table.values_axes[i]
except (IndexError, KeyError):
raise ValueError(
"Incompatible appended table [{blocks}]"
"with existing table [{table}]".format(
blocks=blocks,
table=existing_table.values_axes))
else:
existing_col = None
try:
col = klass.create_for_block(
i=i, name=name, version=self.version)
col.set_atom(block=b, block_items=b_items,
existing_col=existing_col,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
encoding=self.encoding,
errors=self.errors,
info=self.info)
col.set_pos(j)
self.values_axes.append(col)
except (NotImplementedError, ValueError, TypeError) as e:
raise e
except Exception as detail:
raise Exception(
"cannot find the correct atom type -> "
"[dtype->{name},items->{items}] {detail!s}".format(
name=b.dtype.name, items=b_items, detail=detail))
j += 1
# validate our min_itemsize
self.validate_min_itemsize(min_itemsize)
# validate our metadata
self.validate_metadata(existing_table)
# validate the axes if we have an existing table
if validate:
self.validate(existing_table) | def create_axes(self, axes, obj, validate=True, nan_rep=None,
data_columns=None, min_itemsize=None, **kwargs):
""" create and return the axes
leagcy tables create an indexable column, indexable index,
non-indexable fields
Parameters:
-----------
axes: a list of the axes in order to create (names or numbers of
the axes)
obj : the object to create axes on
validate: validate the obj against an existing object already
written
min_itemsize: a dict of the min size for a column in bytes
nan_rep : a values to use for string column nan_rep
encoding : the encoding for string values
data_columns : a list of columns that we want to create separate to
allow indexing (or True will force all columns)
"""
# set the default axes if needed
if axes is None:
try:
axes = _AXES_MAP[type(obj)]
except KeyError:
raise TypeError(
"cannot properly create the storer for: [group->{group},"
"value->{value}]".format(
group=self.group._v_name, value=type(obj)))
# map axes to numbers
axes = [obj._get_axis_number(a) for a in axes]
# do we have an existing table (if so, use its axes & data_columns)
if self.infer_axes():
existing_table = self.copy()
existing_table.infer_axes()
axes = [a.axis for a in existing_table.index_axes]
data_columns = existing_table.data_columns
nan_rep = existing_table.nan_rep
self.encoding = existing_table.encoding
self.errors = existing_table.errors
self.info = copy.copy(existing_table.info)
else:
existing_table = None
# currently support on ndim-1 axes
if len(axes) != self.ndim - 1:
raise ValueError(
"currently only support ndim-1 indexers in an AppendableTable")
# create according to the new data
self.non_index_axes = []
self.data_columns = []
# nan_representation
if nan_rep is None:
nan_rep = 'nan'
self.nan_rep = nan_rep
# create axes to index and non_index
index_axes_map = dict()
for i, a in enumerate(obj.axes):
if i in axes:
name = obj._AXIS_NAMES[i]
index_axes_map[i] = _convert_index(
a, self.encoding, self.errors, self.format_type
).set_name(name).set_axis(i)
else:
# we might be able to change the axes on the appending data if
# necessary
append_axis = list(a)
if existing_table is not None:
indexer = len(self.non_index_axes)
exist_axis = existing_table.non_index_axes[indexer][1]
if not array_equivalent(np.array(append_axis),
np.array(exist_axis)):
# ahah! -> reindex
if array_equivalent(np.array(sorted(append_axis)),
np.array(sorted(exist_axis))):
append_axis = exist_axis
# the non_index_axes info
info = _get_info(self.info, i)
info['names'] = list(a.names)
info['type'] = a.__class__.__name__
self.non_index_axes.append((i, append_axis))
# set axis positions (based on the axes)
self.index_axes = [
index_axes_map[a].set_pos(j).update_info(self.info)
for j, a in enumerate(axes)
]
j = len(self.index_axes)
# check for column conflicts
for a in self.axes:
a.maybe_set_size(min_itemsize=min_itemsize)
# reindex by our non_index_axes & compute data_columns
for a in self.non_index_axes:
obj = _reindex_axis(obj, a[0], a[1])
def get_blk_items(mgr, blocks):
return [mgr.items.take(blk.mgr_locs) for blk in blocks]
# figure out data_columns and get out blocks
block_obj = self.get_object(obj)._consolidate()
blocks = block_obj._data.blocks
blk_items = get_blk_items(block_obj._data, blocks)
if len(self.non_index_axes):
axis, axis_labels = self.non_index_axes[0]
data_columns = self.validate_data_columns(
data_columns, min_itemsize)
if len(data_columns):
mgr = block_obj.reindex(
Index(axis_labels).difference(Index(data_columns)),
axis=axis
)._data
blocks = list(mgr.blocks)
blk_items = get_blk_items(mgr, blocks)
for c in data_columns:
mgr = block_obj.reindex([c], axis=axis)._data
blocks.extend(mgr.blocks)
blk_items.extend(get_blk_items(mgr, mgr.blocks))
# reorder the blocks in the same order as the existing_table if we can
if existing_table is not None:
by_items = {tuple(b_items.tolist()): (b, b_items)
for b, b_items in zip(blocks, blk_items)}
new_blocks = []
new_blk_items = []
for ea in existing_table.values_axes:
items = tuple(ea.values)
try:
b, b_items = by_items.pop(items)
new_blocks.append(b)
new_blk_items.append(b_items)
except (IndexError, KeyError):
raise ValueError(
"cannot match existing table structure for [{items}] "
"on appending data".format(
items=(','.join(pprint_thing(item) for
item in items))))
blocks = new_blocks
blk_items = new_blk_items
# add my values
self.values_axes = []
for i, (b, b_items) in enumerate(zip(blocks, blk_items)):
# shape of the data column are the indexable axes
klass = DataCol
name = None
# we have a data_column
if (data_columns and len(b_items) == 1 and
b_items[0] in data_columns):
klass = DataIndexableCol
name = b_items[0]
self.data_columns.append(name)
# make sure that we match up the existing columns
# if we have an existing table
if existing_table is not None and validate:
try:
existing_col = existing_table.values_axes[i]
except (IndexError, KeyError):
raise ValueError(
"Incompatible appended table [{blocks}]"
"with existing table [{table}]".format(
blocks=blocks,
table=existing_table.values_axes))
else:
existing_col = None
try:
col = klass.create_for_block(
i=i, name=name, version=self.version)
col.set_atom(block=b, block_items=b_items,
existing_col=existing_col,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
encoding=self.encoding,
errors=self.errors,
info=self.info)
col.set_pos(j)
self.values_axes.append(col)
except (NotImplementedError, ValueError, TypeError) as e:
raise e
except Exception as detail:
raise Exception(
"cannot find the correct atom type -> "
"[dtype->{name},items->{items}] {detail!s}".format(
name=b.dtype.name, items=b_items, detail=detail))
j += 1
# validate our min_itemsize
self.validate_min_itemsize(min_itemsize)
# validate our metadata
self.validate_metadata(existing_table)
# validate the axes if we have an existing table
if validate:
self.validate(existing_table) | [
"create",
"and",
"return",
"the",
"axes",
"leagcy",
"tables",
"create",
"an",
"indexable",
"column",
"indexable",
"index",
"non",
"-",
"indexable",
"fields"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3468-L3681 | [
"def",
"create_axes",
"(",
"self",
",",
"axes",
",",
"obj",
",",
"validate",
"=",
"True",
",",
"nan_rep",
"=",
"None",
",",
"data_columns",
"=",
"None",
",",
"min_itemsize",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# set the default axes if needed",
"if",
"axes",
"is",
"None",
":",
"try",
":",
"axes",
"=",
"_AXES_MAP",
"[",
"type",
"(",
"obj",
")",
"]",
"except",
"KeyError",
":",
"raise",
"TypeError",
"(",
"\"cannot properly create the storer for: [group->{group},\"",
"\"value->{value}]\"",
".",
"format",
"(",
"group",
"=",
"self",
".",
"group",
".",
"_v_name",
",",
"value",
"=",
"type",
"(",
"obj",
")",
")",
")",
"# map axes to numbers",
"axes",
"=",
"[",
"obj",
".",
"_get_axis_number",
"(",
"a",
")",
"for",
"a",
"in",
"axes",
"]",
"# do we have an existing table (if so, use its axes & data_columns)",
"if",
"self",
".",
"infer_axes",
"(",
")",
":",
"existing_table",
"=",
"self",
".",
"copy",
"(",
")",
"existing_table",
".",
"infer_axes",
"(",
")",
"axes",
"=",
"[",
"a",
".",
"axis",
"for",
"a",
"in",
"existing_table",
".",
"index_axes",
"]",
"data_columns",
"=",
"existing_table",
".",
"data_columns",
"nan_rep",
"=",
"existing_table",
".",
"nan_rep",
"self",
".",
"encoding",
"=",
"existing_table",
".",
"encoding",
"self",
".",
"errors",
"=",
"existing_table",
".",
"errors",
"self",
".",
"info",
"=",
"copy",
".",
"copy",
"(",
"existing_table",
".",
"info",
")",
"else",
":",
"existing_table",
"=",
"None",
"# currently support on ndim-1 axes",
"if",
"len",
"(",
"axes",
")",
"!=",
"self",
".",
"ndim",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"currently only support ndim-1 indexers in an AppendableTable\"",
")",
"# create according to the new data",
"self",
".",
"non_index_axes",
"=",
"[",
"]",
"self",
".",
"data_columns",
"=",
"[",
"]",
"# nan_representation",
"if",
"nan_rep",
"is",
"None",
":",
"nan_rep",
"=",
"'nan'",
"self",
".",
"nan_rep",
"=",
"nan_rep",
"# create axes to index and non_index",
"index_axes_map",
"=",
"dict",
"(",
")",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"obj",
".",
"axes",
")",
":",
"if",
"i",
"in",
"axes",
":",
"name",
"=",
"obj",
".",
"_AXIS_NAMES",
"[",
"i",
"]",
"index_axes_map",
"[",
"i",
"]",
"=",
"_convert_index",
"(",
"a",
",",
"self",
".",
"encoding",
",",
"self",
".",
"errors",
",",
"self",
".",
"format_type",
")",
".",
"set_name",
"(",
"name",
")",
".",
"set_axis",
"(",
"i",
")",
"else",
":",
"# we might be able to change the axes on the appending data if",
"# necessary",
"append_axis",
"=",
"list",
"(",
"a",
")",
"if",
"existing_table",
"is",
"not",
"None",
":",
"indexer",
"=",
"len",
"(",
"self",
".",
"non_index_axes",
")",
"exist_axis",
"=",
"existing_table",
".",
"non_index_axes",
"[",
"indexer",
"]",
"[",
"1",
"]",
"if",
"not",
"array_equivalent",
"(",
"np",
".",
"array",
"(",
"append_axis",
")",
",",
"np",
".",
"array",
"(",
"exist_axis",
")",
")",
":",
"# ahah! -> reindex",
"if",
"array_equivalent",
"(",
"np",
".",
"array",
"(",
"sorted",
"(",
"append_axis",
")",
")",
",",
"np",
".",
"array",
"(",
"sorted",
"(",
"exist_axis",
")",
")",
")",
":",
"append_axis",
"=",
"exist_axis",
"# the non_index_axes info",
"info",
"=",
"_get_info",
"(",
"self",
".",
"info",
",",
"i",
")",
"info",
"[",
"'names'",
"]",
"=",
"list",
"(",
"a",
".",
"names",
")",
"info",
"[",
"'type'",
"]",
"=",
"a",
".",
"__class__",
".",
"__name__",
"self",
".",
"non_index_axes",
".",
"append",
"(",
"(",
"i",
",",
"append_axis",
")",
")",
"# set axis positions (based on the axes)",
"self",
".",
"index_axes",
"=",
"[",
"index_axes_map",
"[",
"a",
"]",
".",
"set_pos",
"(",
"j",
")",
".",
"update_info",
"(",
"self",
".",
"info",
")",
"for",
"j",
",",
"a",
"in",
"enumerate",
"(",
"axes",
")",
"]",
"j",
"=",
"len",
"(",
"self",
".",
"index_axes",
")",
"# check for column conflicts",
"for",
"a",
"in",
"self",
".",
"axes",
":",
"a",
".",
"maybe_set_size",
"(",
"min_itemsize",
"=",
"min_itemsize",
")",
"# reindex by our non_index_axes & compute data_columns",
"for",
"a",
"in",
"self",
".",
"non_index_axes",
":",
"obj",
"=",
"_reindex_axis",
"(",
"obj",
",",
"a",
"[",
"0",
"]",
",",
"a",
"[",
"1",
"]",
")",
"def",
"get_blk_items",
"(",
"mgr",
",",
"blocks",
")",
":",
"return",
"[",
"mgr",
".",
"items",
".",
"take",
"(",
"blk",
".",
"mgr_locs",
")",
"for",
"blk",
"in",
"blocks",
"]",
"# figure out data_columns and get out blocks",
"block_obj",
"=",
"self",
".",
"get_object",
"(",
"obj",
")",
".",
"_consolidate",
"(",
")",
"blocks",
"=",
"block_obj",
".",
"_data",
".",
"blocks",
"blk_items",
"=",
"get_blk_items",
"(",
"block_obj",
".",
"_data",
",",
"blocks",
")",
"if",
"len",
"(",
"self",
".",
"non_index_axes",
")",
":",
"axis",
",",
"axis_labels",
"=",
"self",
".",
"non_index_axes",
"[",
"0",
"]",
"data_columns",
"=",
"self",
".",
"validate_data_columns",
"(",
"data_columns",
",",
"min_itemsize",
")",
"if",
"len",
"(",
"data_columns",
")",
":",
"mgr",
"=",
"block_obj",
".",
"reindex",
"(",
"Index",
"(",
"axis_labels",
")",
".",
"difference",
"(",
"Index",
"(",
"data_columns",
")",
")",
",",
"axis",
"=",
"axis",
")",
".",
"_data",
"blocks",
"=",
"list",
"(",
"mgr",
".",
"blocks",
")",
"blk_items",
"=",
"get_blk_items",
"(",
"mgr",
",",
"blocks",
")",
"for",
"c",
"in",
"data_columns",
":",
"mgr",
"=",
"block_obj",
".",
"reindex",
"(",
"[",
"c",
"]",
",",
"axis",
"=",
"axis",
")",
".",
"_data",
"blocks",
".",
"extend",
"(",
"mgr",
".",
"blocks",
")",
"blk_items",
".",
"extend",
"(",
"get_blk_items",
"(",
"mgr",
",",
"mgr",
".",
"blocks",
")",
")",
"# reorder the blocks in the same order as the existing_table if we can",
"if",
"existing_table",
"is",
"not",
"None",
":",
"by_items",
"=",
"{",
"tuple",
"(",
"b_items",
".",
"tolist",
"(",
")",
")",
":",
"(",
"b",
",",
"b_items",
")",
"for",
"b",
",",
"b_items",
"in",
"zip",
"(",
"blocks",
",",
"blk_items",
")",
"}",
"new_blocks",
"=",
"[",
"]",
"new_blk_items",
"=",
"[",
"]",
"for",
"ea",
"in",
"existing_table",
".",
"values_axes",
":",
"items",
"=",
"tuple",
"(",
"ea",
".",
"values",
")",
"try",
":",
"b",
",",
"b_items",
"=",
"by_items",
".",
"pop",
"(",
"items",
")",
"new_blocks",
".",
"append",
"(",
"b",
")",
"new_blk_items",
".",
"append",
"(",
"b_items",
")",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"raise",
"ValueError",
"(",
"\"cannot match existing table structure for [{items}] \"",
"\"on appending data\"",
".",
"format",
"(",
"items",
"=",
"(",
"','",
".",
"join",
"(",
"pprint_thing",
"(",
"item",
")",
"for",
"item",
"in",
"items",
")",
")",
")",
")",
"blocks",
"=",
"new_blocks",
"blk_items",
"=",
"new_blk_items",
"# add my values",
"self",
".",
"values_axes",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"b",
",",
"b_items",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"blocks",
",",
"blk_items",
")",
")",
":",
"# shape of the data column are the indexable axes",
"klass",
"=",
"DataCol",
"name",
"=",
"None",
"# we have a data_column",
"if",
"(",
"data_columns",
"and",
"len",
"(",
"b_items",
")",
"==",
"1",
"and",
"b_items",
"[",
"0",
"]",
"in",
"data_columns",
")",
":",
"klass",
"=",
"DataIndexableCol",
"name",
"=",
"b_items",
"[",
"0",
"]",
"self",
".",
"data_columns",
".",
"append",
"(",
"name",
")",
"# make sure that we match up the existing columns",
"# if we have an existing table",
"if",
"existing_table",
"is",
"not",
"None",
"and",
"validate",
":",
"try",
":",
"existing_col",
"=",
"existing_table",
".",
"values_axes",
"[",
"i",
"]",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"raise",
"ValueError",
"(",
"\"Incompatible appended table [{blocks}]\"",
"\"with existing table [{table}]\"",
".",
"format",
"(",
"blocks",
"=",
"blocks",
",",
"table",
"=",
"existing_table",
".",
"values_axes",
")",
")",
"else",
":",
"existing_col",
"=",
"None",
"try",
":",
"col",
"=",
"klass",
".",
"create_for_block",
"(",
"i",
"=",
"i",
",",
"name",
"=",
"name",
",",
"version",
"=",
"self",
".",
"version",
")",
"col",
".",
"set_atom",
"(",
"block",
"=",
"b",
",",
"block_items",
"=",
"b_items",
",",
"existing_col",
"=",
"existing_col",
",",
"min_itemsize",
"=",
"min_itemsize",
",",
"nan_rep",
"=",
"nan_rep",
",",
"encoding",
"=",
"self",
".",
"encoding",
",",
"errors",
"=",
"self",
".",
"errors",
",",
"info",
"=",
"self",
".",
"info",
")",
"col",
".",
"set_pos",
"(",
"j",
")",
"self",
".",
"values_axes",
".",
"append",
"(",
"col",
")",
"except",
"(",
"NotImplementedError",
",",
"ValueError",
",",
"TypeError",
")",
"as",
"e",
":",
"raise",
"e",
"except",
"Exception",
"as",
"detail",
":",
"raise",
"Exception",
"(",
"\"cannot find the correct atom type -> \"",
"\"[dtype->{name},items->{items}] {detail!s}\"",
".",
"format",
"(",
"name",
"=",
"b",
".",
"dtype",
".",
"name",
",",
"items",
"=",
"b_items",
",",
"detail",
"=",
"detail",
")",
")",
"j",
"+=",
"1",
"# validate our min_itemsize",
"self",
".",
"validate_min_itemsize",
"(",
"min_itemsize",
")",
"# validate our metadata",
"self",
".",
"validate_metadata",
"(",
"existing_table",
")",
"# validate the axes if we have an existing table",
"if",
"validate",
":",
"self",
".",
"validate",
"(",
"existing_table",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.process_axes | process axes filters | pandas/io/pytables.py | def process_axes(self, obj, columns=None):
""" process axes filters """
# make a copy to avoid side effects
if columns is not None:
columns = list(columns)
# make sure to include levels if we have them
if columns is not None and self.is_multi_index:
for n in self.levels:
if n not in columns:
columns.insert(0, n)
# reorder by any non_index_axes & limit to the select columns
for axis, labels in self.non_index_axes:
obj = _reindex_axis(obj, axis, labels, columns)
# apply the selection filters (but keep in the same order)
if self.selection.filter is not None:
for field, op, filt in self.selection.filter.format():
def process_filter(field, filt):
for axis_name in obj._AXIS_NAMES.values():
axis_number = obj._get_axis_number(axis_name)
axis_values = obj._get_axis(axis_name)
# see if the field is the name of an axis
if field == axis_name:
# if we have a multi-index, then need to include
# the levels
if self.is_multi_index:
filt = filt.union(Index(self.levels))
takers = op(axis_values, filt)
return obj.loc._getitem_axis(takers,
axis=axis_number)
# this might be the name of a file IN an axis
elif field in axis_values:
# we need to filter on this dimension
values = ensure_index(getattr(obj, field).values)
filt = ensure_index(filt)
# hack until we support reversed dim flags
if isinstance(obj, DataFrame):
axis_number = 1 - axis_number
takers = op(values, filt)
return obj.loc._getitem_axis(takers,
axis=axis_number)
raise ValueError("cannot find the field [{field}] for "
"filtering!".format(field=field))
obj = process_filter(field, filt)
return obj | def process_axes(self, obj, columns=None):
""" process axes filters """
# make a copy to avoid side effects
if columns is not None:
columns = list(columns)
# make sure to include levels if we have them
if columns is not None and self.is_multi_index:
for n in self.levels:
if n not in columns:
columns.insert(0, n)
# reorder by any non_index_axes & limit to the select columns
for axis, labels in self.non_index_axes:
obj = _reindex_axis(obj, axis, labels, columns)
# apply the selection filters (but keep in the same order)
if self.selection.filter is not None:
for field, op, filt in self.selection.filter.format():
def process_filter(field, filt):
for axis_name in obj._AXIS_NAMES.values():
axis_number = obj._get_axis_number(axis_name)
axis_values = obj._get_axis(axis_name)
# see if the field is the name of an axis
if field == axis_name:
# if we have a multi-index, then need to include
# the levels
if self.is_multi_index:
filt = filt.union(Index(self.levels))
takers = op(axis_values, filt)
return obj.loc._getitem_axis(takers,
axis=axis_number)
# this might be the name of a file IN an axis
elif field in axis_values:
# we need to filter on this dimension
values = ensure_index(getattr(obj, field).values)
filt = ensure_index(filt)
# hack until we support reversed dim flags
if isinstance(obj, DataFrame):
axis_number = 1 - axis_number
takers = op(values, filt)
return obj.loc._getitem_axis(takers,
axis=axis_number)
raise ValueError("cannot find the field [{field}] for "
"filtering!".format(field=field))
obj = process_filter(field, filt)
return obj | [
"process",
"axes",
"filters"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3683-L3741 | [
"def",
"process_axes",
"(",
"self",
",",
"obj",
",",
"columns",
"=",
"None",
")",
":",
"# make a copy to avoid side effects",
"if",
"columns",
"is",
"not",
"None",
":",
"columns",
"=",
"list",
"(",
"columns",
")",
"# make sure to include levels if we have them",
"if",
"columns",
"is",
"not",
"None",
"and",
"self",
".",
"is_multi_index",
":",
"for",
"n",
"in",
"self",
".",
"levels",
":",
"if",
"n",
"not",
"in",
"columns",
":",
"columns",
".",
"insert",
"(",
"0",
",",
"n",
")",
"# reorder by any non_index_axes & limit to the select columns",
"for",
"axis",
",",
"labels",
"in",
"self",
".",
"non_index_axes",
":",
"obj",
"=",
"_reindex_axis",
"(",
"obj",
",",
"axis",
",",
"labels",
",",
"columns",
")",
"# apply the selection filters (but keep in the same order)",
"if",
"self",
".",
"selection",
".",
"filter",
"is",
"not",
"None",
":",
"for",
"field",
",",
"op",
",",
"filt",
"in",
"self",
".",
"selection",
".",
"filter",
".",
"format",
"(",
")",
":",
"def",
"process_filter",
"(",
"field",
",",
"filt",
")",
":",
"for",
"axis_name",
"in",
"obj",
".",
"_AXIS_NAMES",
".",
"values",
"(",
")",
":",
"axis_number",
"=",
"obj",
".",
"_get_axis_number",
"(",
"axis_name",
")",
"axis_values",
"=",
"obj",
".",
"_get_axis",
"(",
"axis_name",
")",
"# see if the field is the name of an axis",
"if",
"field",
"==",
"axis_name",
":",
"# if we have a multi-index, then need to include",
"# the levels",
"if",
"self",
".",
"is_multi_index",
":",
"filt",
"=",
"filt",
".",
"union",
"(",
"Index",
"(",
"self",
".",
"levels",
")",
")",
"takers",
"=",
"op",
"(",
"axis_values",
",",
"filt",
")",
"return",
"obj",
".",
"loc",
".",
"_getitem_axis",
"(",
"takers",
",",
"axis",
"=",
"axis_number",
")",
"# this might be the name of a file IN an axis",
"elif",
"field",
"in",
"axis_values",
":",
"# we need to filter on this dimension",
"values",
"=",
"ensure_index",
"(",
"getattr",
"(",
"obj",
",",
"field",
")",
".",
"values",
")",
"filt",
"=",
"ensure_index",
"(",
"filt",
")",
"# hack until we support reversed dim flags",
"if",
"isinstance",
"(",
"obj",
",",
"DataFrame",
")",
":",
"axis_number",
"=",
"1",
"-",
"axis_number",
"takers",
"=",
"op",
"(",
"values",
",",
"filt",
")",
"return",
"obj",
".",
"loc",
".",
"_getitem_axis",
"(",
"takers",
",",
"axis",
"=",
"axis_number",
")",
"raise",
"ValueError",
"(",
"\"cannot find the field [{field}] for \"",
"\"filtering!\"",
".",
"format",
"(",
"field",
"=",
"field",
")",
")",
"obj",
"=",
"process_filter",
"(",
"field",
",",
"filt",
")",
"return",
"obj"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.create_description | create the description of the table from the axes & values | pandas/io/pytables.py | def create_description(self, complib=None, complevel=None,
fletcher32=False, expectedrows=None):
""" create the description of the table from the axes & values """
# provided expected rows if its passed
if expectedrows is None:
expectedrows = max(self.nrows_expected, 10000)
d = dict(name='table', expectedrows=expectedrows)
# description from the axes & values
d['description'] = {a.cname: a.typ for a in self.axes}
if complib:
if complevel is None:
complevel = self._complevel or 9
filters = _tables().Filters(
complevel=complevel, complib=complib,
fletcher32=fletcher32 or self._fletcher32)
d['filters'] = filters
elif self._filters is not None:
d['filters'] = self._filters
return d | def create_description(self, complib=None, complevel=None,
fletcher32=False, expectedrows=None):
""" create the description of the table from the axes & values """
# provided expected rows if its passed
if expectedrows is None:
expectedrows = max(self.nrows_expected, 10000)
d = dict(name='table', expectedrows=expectedrows)
# description from the axes & values
d['description'] = {a.cname: a.typ for a in self.axes}
if complib:
if complevel is None:
complevel = self._complevel or 9
filters = _tables().Filters(
complevel=complevel, complib=complib,
fletcher32=fletcher32 or self._fletcher32)
d['filters'] = filters
elif self._filters is not None:
d['filters'] = self._filters
return d | [
"create",
"the",
"description",
"of",
"the",
"table",
"from",
"the",
"axes",
"&",
"values"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3743-L3766 | [
"def",
"create_description",
"(",
"self",
",",
"complib",
"=",
"None",
",",
"complevel",
"=",
"None",
",",
"fletcher32",
"=",
"False",
",",
"expectedrows",
"=",
"None",
")",
":",
"# provided expected rows if its passed",
"if",
"expectedrows",
"is",
"None",
":",
"expectedrows",
"=",
"max",
"(",
"self",
".",
"nrows_expected",
",",
"10000",
")",
"d",
"=",
"dict",
"(",
"name",
"=",
"'table'",
",",
"expectedrows",
"=",
"expectedrows",
")",
"# description from the axes & values",
"d",
"[",
"'description'",
"]",
"=",
"{",
"a",
".",
"cname",
":",
"a",
".",
"typ",
"for",
"a",
"in",
"self",
".",
"axes",
"}",
"if",
"complib",
":",
"if",
"complevel",
"is",
"None",
":",
"complevel",
"=",
"self",
".",
"_complevel",
"or",
"9",
"filters",
"=",
"_tables",
"(",
")",
".",
"Filters",
"(",
"complevel",
"=",
"complevel",
",",
"complib",
"=",
"complib",
",",
"fletcher32",
"=",
"fletcher32",
"or",
"self",
".",
"_fletcher32",
")",
"d",
"[",
"'filters'",
"]",
"=",
"filters",
"elif",
"self",
".",
"_filters",
"is",
"not",
"None",
":",
"d",
"[",
"'filters'",
"]",
"=",
"self",
".",
"_filters",
"return",
"d"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.read_coordinates | select coordinates (row numbers) from a table; return the
coordinates object | pandas/io/pytables.py | def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
"""select coordinates (row numbers) from a table; return the
coordinates object
"""
# validate the version
self.validate_version(where)
# infer the data kind
if not self.infer_axes():
return False
# create the selection
self.selection = Selection(
self, where=where, start=start, stop=stop, **kwargs)
coords = self.selection.select_coords()
if self.selection.filter is not None:
for field, op, filt in self.selection.filter.format():
data = self.read_column(
field, start=coords.min(), stop=coords.max() + 1)
coords = coords[
op(data.iloc[coords - coords.min()], filt).values]
return Index(coords) | def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
"""select coordinates (row numbers) from a table; return the
coordinates object
"""
# validate the version
self.validate_version(where)
# infer the data kind
if not self.infer_axes():
return False
# create the selection
self.selection = Selection(
self, where=where, start=start, stop=stop, **kwargs)
coords = self.selection.select_coords()
if self.selection.filter is not None:
for field, op, filt in self.selection.filter.format():
data = self.read_column(
field, start=coords.min(), stop=coords.max() + 1)
coords = coords[
op(data.iloc[coords - coords.min()], filt).values]
return Index(coords) | [
"select",
"coordinates",
"(",
"row",
"numbers",
")",
"from",
"a",
"table",
";",
"return",
"the",
"coordinates",
"object"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3768-L3791 | [
"def",
"read_coordinates",
"(",
"self",
",",
"where",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# validate the version",
"self",
".",
"validate_version",
"(",
"where",
")",
"# infer the data kind",
"if",
"not",
"self",
".",
"infer_axes",
"(",
")",
":",
"return",
"False",
"# create the selection",
"self",
".",
"selection",
"=",
"Selection",
"(",
"self",
",",
"where",
"=",
"where",
",",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"*",
"*",
"kwargs",
")",
"coords",
"=",
"self",
".",
"selection",
".",
"select_coords",
"(",
")",
"if",
"self",
".",
"selection",
".",
"filter",
"is",
"not",
"None",
":",
"for",
"field",
",",
"op",
",",
"filt",
"in",
"self",
".",
"selection",
".",
"filter",
".",
"format",
"(",
")",
":",
"data",
"=",
"self",
".",
"read_column",
"(",
"field",
",",
"start",
"=",
"coords",
".",
"min",
"(",
")",
",",
"stop",
"=",
"coords",
".",
"max",
"(",
")",
"+",
"1",
")",
"coords",
"=",
"coords",
"[",
"op",
"(",
"data",
".",
"iloc",
"[",
"coords",
"-",
"coords",
".",
"min",
"(",
")",
"]",
",",
"filt",
")",
".",
"values",
"]",
"return",
"Index",
"(",
"coords",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Table.read_column | return a single column from the table, generally only indexables
are interesting | pandas/io/pytables.py | def read_column(self, column, where=None, start=None, stop=None):
"""return a single column from the table, generally only indexables
are interesting
"""
# validate the version
self.validate_version()
# infer the data kind
if not self.infer_axes():
return False
if where is not None:
raise TypeError("read_column does not currently accept a where "
"clause")
# find the axes
for a in self.axes:
if column == a.name:
if not a.is_data_indexable:
raise ValueError(
"column [{column}] can not be extracted individually; "
"it is not data indexable".format(column=column))
# column must be an indexable or a data column
c = getattr(self.table.cols, column)
a.set_info(self.info)
return Series(_set_tz(a.convert(c[start:stop],
nan_rep=self.nan_rep,
encoding=self.encoding,
errors=self.errors
).take_data(),
a.tz, True), name=column)
raise KeyError(
"column [{column}] not found in the table".format(column=column)) | def read_column(self, column, where=None, start=None, stop=None):
"""return a single column from the table, generally only indexables
are interesting
"""
# validate the version
self.validate_version()
# infer the data kind
if not self.infer_axes():
return False
if where is not None:
raise TypeError("read_column does not currently accept a where "
"clause")
# find the axes
for a in self.axes:
if column == a.name:
if not a.is_data_indexable:
raise ValueError(
"column [{column}] can not be extracted individually; "
"it is not data indexable".format(column=column))
# column must be an indexable or a data column
c = getattr(self.table.cols, column)
a.set_info(self.info)
return Series(_set_tz(a.convert(c[start:stop],
nan_rep=self.nan_rep,
encoding=self.encoding,
errors=self.errors
).take_data(),
a.tz, True), name=column)
raise KeyError(
"column [{column}] not found in the table".format(column=column)) | [
"return",
"a",
"single",
"column",
"from",
"the",
"table",
"generally",
"only",
"indexables",
"are",
"interesting"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3793-L3829 | [
"def",
"read_column",
"(",
"self",
",",
"column",
",",
"where",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"# validate the version",
"self",
".",
"validate_version",
"(",
")",
"# infer the data kind",
"if",
"not",
"self",
".",
"infer_axes",
"(",
")",
":",
"return",
"False",
"if",
"where",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"read_column does not currently accept a where \"",
"\"clause\"",
")",
"# find the axes",
"for",
"a",
"in",
"self",
".",
"axes",
":",
"if",
"column",
"==",
"a",
".",
"name",
":",
"if",
"not",
"a",
".",
"is_data_indexable",
":",
"raise",
"ValueError",
"(",
"\"column [{column}] can not be extracted individually; \"",
"\"it is not data indexable\"",
".",
"format",
"(",
"column",
"=",
"column",
")",
")",
"# column must be an indexable or a data column",
"c",
"=",
"getattr",
"(",
"self",
".",
"table",
".",
"cols",
",",
"column",
")",
"a",
".",
"set_info",
"(",
"self",
".",
"info",
")",
"return",
"Series",
"(",
"_set_tz",
"(",
"a",
".",
"convert",
"(",
"c",
"[",
"start",
":",
"stop",
"]",
",",
"nan_rep",
"=",
"self",
".",
"nan_rep",
",",
"encoding",
"=",
"self",
".",
"encoding",
",",
"errors",
"=",
"self",
".",
"errors",
")",
".",
"take_data",
"(",
")",
",",
"a",
".",
"tz",
",",
"True",
")",
",",
"name",
"=",
"column",
")",
"raise",
"KeyError",
"(",
"\"column [{column}] not found in the table\"",
".",
"format",
"(",
"column",
"=",
"column",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | LegacyTable.read | we have n indexable columns, with an arbitrary number of data
axes | pandas/io/pytables.py | def read(self, where=None, columns=None, **kwargs):
"""we have n indexable columns, with an arbitrary number of data
axes
"""
if not self.read_axes(where=where, **kwargs):
return None
raise NotImplementedError("Panel is removed in pandas 0.25.0") | def read(self, where=None, columns=None, **kwargs):
"""we have n indexable columns, with an arbitrary number of data
axes
"""
if not self.read_axes(where=where, **kwargs):
return None
raise NotImplementedError("Panel is removed in pandas 0.25.0") | [
"we",
"have",
"n",
"indexable",
"columns",
"with",
"an",
"arbitrary",
"number",
"of",
"data",
"axes"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3872-L3880 | [
"def",
"read",
"(",
"self",
",",
"where",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"read_axes",
"(",
"where",
"=",
"where",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"None",
"raise",
"NotImplementedError",
"(",
"\"Panel is removed in pandas 0.25.0\"",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | AppendableTable.write_data | we form the data into a 2-d including indexes,values,mask
write chunk-by-chunk | pandas/io/pytables.py | def write_data(self, chunksize, dropna=False):
""" we form the data into a 2-d including indexes,values,mask
write chunk-by-chunk """
names = self.dtype.names
nrows = self.nrows_expected
# if dropna==True, then drop ALL nan rows
masks = []
if dropna:
for a in self.values_axes:
# figure the mask: only do if we can successfully process this
# column, otherwise ignore the mask
mask = isna(a.data).all(axis=0)
if isinstance(mask, np.ndarray):
masks.append(mask.astype('u1', copy=False))
# consolidate masks
if len(masks):
mask = masks[0]
for m in masks[1:]:
mask = mask & m
mask = mask.ravel()
else:
mask = None
# broadcast the indexes if needed
indexes = [a.cvalues for a in self.index_axes]
nindexes = len(indexes)
bindexes = []
for i, idx in enumerate(indexes):
# broadcast to all other indexes except myself
if i > 0 and i < nindexes:
repeater = np.prod(
[indexes[bi].shape[0] for bi in range(0, i)])
idx = np.tile(idx, repeater)
if i < nindexes - 1:
repeater = np.prod([indexes[bi].shape[0]
for bi in range(i + 1, nindexes)])
idx = np.repeat(idx, repeater)
bindexes.append(idx)
# transpose the values so first dimension is last
# reshape the values if needed
values = [a.take_data() for a in self.values_axes]
values = [v.transpose(np.roll(np.arange(v.ndim), v.ndim - 1))
for v in values]
bvalues = []
for i, v in enumerate(values):
new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape
bvalues.append(values[i].reshape(new_shape))
# write the chunks
if chunksize is None:
chunksize = 100000
rows = np.empty(min(chunksize, nrows), dtype=self.dtype)
chunks = int(nrows / chunksize) + 1
for i in range(chunks):
start_i = i * chunksize
end_i = min((i + 1) * chunksize, nrows)
if start_i >= end_i:
break
self.write_data_chunk(
rows,
indexes=[a[start_i:end_i] for a in bindexes],
mask=mask[start_i:end_i] if mask is not None else None,
values=[v[start_i:end_i] for v in bvalues]) | def write_data(self, chunksize, dropna=False):
""" we form the data into a 2-d including indexes,values,mask
write chunk-by-chunk """
names = self.dtype.names
nrows = self.nrows_expected
# if dropna==True, then drop ALL nan rows
masks = []
if dropna:
for a in self.values_axes:
# figure the mask: only do if we can successfully process this
# column, otherwise ignore the mask
mask = isna(a.data).all(axis=0)
if isinstance(mask, np.ndarray):
masks.append(mask.astype('u1', copy=False))
# consolidate masks
if len(masks):
mask = masks[0]
for m in masks[1:]:
mask = mask & m
mask = mask.ravel()
else:
mask = None
# broadcast the indexes if needed
indexes = [a.cvalues for a in self.index_axes]
nindexes = len(indexes)
bindexes = []
for i, idx in enumerate(indexes):
# broadcast to all other indexes except myself
if i > 0 and i < nindexes:
repeater = np.prod(
[indexes[bi].shape[0] for bi in range(0, i)])
idx = np.tile(idx, repeater)
if i < nindexes - 1:
repeater = np.prod([indexes[bi].shape[0]
for bi in range(i + 1, nindexes)])
idx = np.repeat(idx, repeater)
bindexes.append(idx)
# transpose the values so first dimension is last
# reshape the values if needed
values = [a.take_data() for a in self.values_axes]
values = [v.transpose(np.roll(np.arange(v.ndim), v.ndim - 1))
for v in values]
bvalues = []
for i, v in enumerate(values):
new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape
bvalues.append(values[i].reshape(new_shape))
# write the chunks
if chunksize is None:
chunksize = 100000
rows = np.empty(min(chunksize, nrows), dtype=self.dtype)
chunks = int(nrows / chunksize) + 1
for i in range(chunks):
start_i = i * chunksize
end_i = min((i + 1) * chunksize, nrows)
if start_i >= end_i:
break
self.write_data_chunk(
rows,
indexes=[a[start_i:end_i] for a in bindexes],
mask=mask[start_i:end_i] if mask is not None else None,
values=[v[start_i:end_i] for v in bvalues]) | [
"we",
"form",
"the",
"data",
"into",
"a",
"2",
"-",
"d",
"including",
"indexes",
"values",
"mask",
"write",
"chunk",
"-",
"by",
"-",
"chunk"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3930-L4003 | [
"def",
"write_data",
"(",
"self",
",",
"chunksize",
",",
"dropna",
"=",
"False",
")",
":",
"names",
"=",
"self",
".",
"dtype",
".",
"names",
"nrows",
"=",
"self",
".",
"nrows_expected",
"# if dropna==True, then drop ALL nan rows",
"masks",
"=",
"[",
"]",
"if",
"dropna",
":",
"for",
"a",
"in",
"self",
".",
"values_axes",
":",
"# figure the mask: only do if we can successfully process this",
"# column, otherwise ignore the mask",
"mask",
"=",
"isna",
"(",
"a",
".",
"data",
")",
".",
"all",
"(",
"axis",
"=",
"0",
")",
"if",
"isinstance",
"(",
"mask",
",",
"np",
".",
"ndarray",
")",
":",
"masks",
".",
"append",
"(",
"mask",
".",
"astype",
"(",
"'u1'",
",",
"copy",
"=",
"False",
")",
")",
"# consolidate masks",
"if",
"len",
"(",
"masks",
")",
":",
"mask",
"=",
"masks",
"[",
"0",
"]",
"for",
"m",
"in",
"masks",
"[",
"1",
":",
"]",
":",
"mask",
"=",
"mask",
"&",
"m",
"mask",
"=",
"mask",
".",
"ravel",
"(",
")",
"else",
":",
"mask",
"=",
"None",
"# broadcast the indexes if needed",
"indexes",
"=",
"[",
"a",
".",
"cvalues",
"for",
"a",
"in",
"self",
".",
"index_axes",
"]",
"nindexes",
"=",
"len",
"(",
"indexes",
")",
"bindexes",
"=",
"[",
"]",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"indexes",
")",
":",
"# broadcast to all other indexes except myself",
"if",
"i",
">",
"0",
"and",
"i",
"<",
"nindexes",
":",
"repeater",
"=",
"np",
".",
"prod",
"(",
"[",
"indexes",
"[",
"bi",
"]",
".",
"shape",
"[",
"0",
"]",
"for",
"bi",
"in",
"range",
"(",
"0",
",",
"i",
")",
"]",
")",
"idx",
"=",
"np",
".",
"tile",
"(",
"idx",
",",
"repeater",
")",
"if",
"i",
"<",
"nindexes",
"-",
"1",
":",
"repeater",
"=",
"np",
".",
"prod",
"(",
"[",
"indexes",
"[",
"bi",
"]",
".",
"shape",
"[",
"0",
"]",
"for",
"bi",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"nindexes",
")",
"]",
")",
"idx",
"=",
"np",
".",
"repeat",
"(",
"idx",
",",
"repeater",
")",
"bindexes",
".",
"append",
"(",
"idx",
")",
"# transpose the values so first dimension is last",
"# reshape the values if needed",
"values",
"=",
"[",
"a",
".",
"take_data",
"(",
")",
"for",
"a",
"in",
"self",
".",
"values_axes",
"]",
"values",
"=",
"[",
"v",
".",
"transpose",
"(",
"np",
".",
"roll",
"(",
"np",
".",
"arange",
"(",
"v",
".",
"ndim",
")",
",",
"v",
".",
"ndim",
"-",
"1",
")",
")",
"for",
"v",
"in",
"values",
"]",
"bvalues",
"=",
"[",
"]",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"values",
")",
":",
"new_shape",
"=",
"(",
"nrows",
",",
")",
"+",
"self",
".",
"dtype",
"[",
"names",
"[",
"nindexes",
"+",
"i",
"]",
"]",
".",
"shape",
"bvalues",
".",
"append",
"(",
"values",
"[",
"i",
"]",
".",
"reshape",
"(",
"new_shape",
")",
")",
"# write the chunks",
"if",
"chunksize",
"is",
"None",
":",
"chunksize",
"=",
"100000",
"rows",
"=",
"np",
".",
"empty",
"(",
"min",
"(",
"chunksize",
",",
"nrows",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"chunks",
"=",
"int",
"(",
"nrows",
"/",
"chunksize",
")",
"+",
"1",
"for",
"i",
"in",
"range",
"(",
"chunks",
")",
":",
"start_i",
"=",
"i",
"*",
"chunksize",
"end_i",
"=",
"min",
"(",
"(",
"i",
"+",
"1",
")",
"*",
"chunksize",
",",
"nrows",
")",
"if",
"start_i",
">=",
"end_i",
":",
"break",
"self",
".",
"write_data_chunk",
"(",
"rows",
",",
"indexes",
"=",
"[",
"a",
"[",
"start_i",
":",
"end_i",
"]",
"for",
"a",
"in",
"bindexes",
"]",
",",
"mask",
"=",
"mask",
"[",
"start_i",
":",
"end_i",
"]",
"if",
"mask",
"is",
"not",
"None",
"else",
"None",
",",
"values",
"=",
"[",
"v",
"[",
"start_i",
":",
"end_i",
"]",
"for",
"v",
"in",
"bvalues",
"]",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | AppendableTable.write_data_chunk | Parameters
----------
rows : an empty memory space where we are putting the chunk
indexes : an array of the indexes
mask : an array of the masks
values : an array of the values | pandas/io/pytables.py | def write_data_chunk(self, rows, indexes, mask, values):
"""
Parameters
----------
rows : an empty memory space where we are putting the chunk
indexes : an array of the indexes
mask : an array of the masks
values : an array of the values
"""
# 0 len
for v in values:
if not np.prod(v.shape):
return
try:
nrows = indexes[0].shape[0]
if nrows != len(rows):
rows = np.empty(nrows, dtype=self.dtype)
names = self.dtype.names
nindexes = len(indexes)
# indexes
for i, idx in enumerate(indexes):
rows[names[i]] = idx
# values
for i, v in enumerate(values):
rows[names[i + nindexes]] = v
# mask
if mask is not None:
m = ~mask.ravel().astype(bool, copy=False)
if not m.all():
rows = rows[m]
except Exception as detail:
raise Exception(
"cannot create row-data -> {detail}".format(detail=detail))
try:
if len(rows):
self.table.append(rows)
self.table.flush()
except Exception as detail:
raise TypeError(
"tables cannot write this data -> {detail}".format(
detail=detail)) | def write_data_chunk(self, rows, indexes, mask, values):
"""
Parameters
----------
rows : an empty memory space where we are putting the chunk
indexes : an array of the indexes
mask : an array of the masks
values : an array of the values
"""
# 0 len
for v in values:
if not np.prod(v.shape):
return
try:
nrows = indexes[0].shape[0]
if nrows != len(rows):
rows = np.empty(nrows, dtype=self.dtype)
names = self.dtype.names
nindexes = len(indexes)
# indexes
for i, idx in enumerate(indexes):
rows[names[i]] = idx
# values
for i, v in enumerate(values):
rows[names[i + nindexes]] = v
# mask
if mask is not None:
m = ~mask.ravel().astype(bool, copy=False)
if not m.all():
rows = rows[m]
except Exception as detail:
raise Exception(
"cannot create row-data -> {detail}".format(detail=detail))
try:
if len(rows):
self.table.append(rows)
self.table.flush()
except Exception as detail:
raise TypeError(
"tables cannot write this data -> {detail}".format(
detail=detail)) | [
"Parameters",
"----------",
"rows",
":",
"an",
"empty",
"memory",
"space",
"where",
"we",
"are",
"putting",
"the",
"chunk",
"indexes",
":",
"an",
"array",
"of",
"the",
"indexes",
"mask",
":",
"an",
"array",
"of",
"the",
"masks",
"values",
":",
"an",
"array",
"of",
"the",
"values"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L4005-L4052 | [
"def",
"write_data_chunk",
"(",
"self",
",",
"rows",
",",
"indexes",
",",
"mask",
",",
"values",
")",
":",
"# 0 len",
"for",
"v",
"in",
"values",
":",
"if",
"not",
"np",
".",
"prod",
"(",
"v",
".",
"shape",
")",
":",
"return",
"try",
":",
"nrows",
"=",
"indexes",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"if",
"nrows",
"!=",
"len",
"(",
"rows",
")",
":",
"rows",
"=",
"np",
".",
"empty",
"(",
"nrows",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"names",
"=",
"self",
".",
"dtype",
".",
"names",
"nindexes",
"=",
"len",
"(",
"indexes",
")",
"# indexes",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"indexes",
")",
":",
"rows",
"[",
"names",
"[",
"i",
"]",
"]",
"=",
"idx",
"# values",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"values",
")",
":",
"rows",
"[",
"names",
"[",
"i",
"+",
"nindexes",
"]",
"]",
"=",
"v",
"# mask",
"if",
"mask",
"is",
"not",
"None",
":",
"m",
"=",
"~",
"mask",
".",
"ravel",
"(",
")",
".",
"astype",
"(",
"bool",
",",
"copy",
"=",
"False",
")",
"if",
"not",
"m",
".",
"all",
"(",
")",
":",
"rows",
"=",
"rows",
"[",
"m",
"]",
"except",
"Exception",
"as",
"detail",
":",
"raise",
"Exception",
"(",
"\"cannot create row-data -> {detail}\"",
".",
"format",
"(",
"detail",
"=",
"detail",
")",
")",
"try",
":",
"if",
"len",
"(",
"rows",
")",
":",
"self",
".",
"table",
".",
"append",
"(",
"rows",
")",
"self",
".",
"table",
".",
"flush",
"(",
")",
"except",
"Exception",
"as",
"detail",
":",
"raise",
"TypeError",
"(",
"\"tables cannot write this data -> {detail}\"",
".",
"format",
"(",
"detail",
"=",
"detail",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | AppendableSeriesTable.write | we are going to write this as a frame table | pandas/io/pytables.py | def write(self, obj, data_columns=None, **kwargs):
""" we are going to write this as a frame table """
if not isinstance(obj, DataFrame):
name = obj.name or 'values'
obj = DataFrame({name: obj}, index=obj.index)
obj.columns = [name]
return super().write(obj=obj, data_columns=obj.columns.tolist(),
**kwargs) | def write(self, obj, data_columns=None, **kwargs):
""" we are going to write this as a frame table """
if not isinstance(obj, DataFrame):
name = obj.name or 'values'
obj = DataFrame({name: obj}, index=obj.index)
obj.columns = [name]
return super().write(obj=obj, data_columns=obj.columns.tolist(),
**kwargs) | [
"we",
"are",
"going",
"to",
"write",
"this",
"as",
"a",
"frame",
"table"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L4196-L4203 | [
"def",
"write",
"(",
"self",
",",
"obj",
",",
"data_columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"DataFrame",
")",
":",
"name",
"=",
"obj",
".",
"name",
"or",
"'values'",
"obj",
"=",
"DataFrame",
"(",
"{",
"name",
":",
"obj",
"}",
",",
"index",
"=",
"obj",
".",
"index",
")",
"obj",
".",
"columns",
"=",
"[",
"name",
"]",
"return",
"super",
"(",
")",
".",
"write",
"(",
"obj",
"=",
"obj",
",",
"data_columns",
"=",
"obj",
".",
"columns",
".",
"tolist",
"(",
")",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | AppendableMultiSeriesTable.write | we are going to write this as a frame table | pandas/io/pytables.py | def write(self, obj, **kwargs):
""" we are going to write this as a frame table """
name = obj.name or 'values'
obj, self.levels = self.validate_multiindex(obj)
cols = list(self.levels)
cols.append(name)
obj.columns = cols
return super().write(obj=obj, **kwargs) | def write(self, obj, **kwargs):
""" we are going to write this as a frame table """
name = obj.name or 'values'
obj, self.levels = self.validate_multiindex(obj)
cols = list(self.levels)
cols.append(name)
obj.columns = cols
return super().write(obj=obj, **kwargs) | [
"we",
"are",
"going",
"to",
"write",
"this",
"as",
"a",
"frame",
"table"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L4229-L4236 | [
"def",
"write",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"obj",
".",
"name",
"or",
"'values'",
"obj",
",",
"self",
".",
"levels",
"=",
"self",
".",
"validate_multiindex",
"(",
"obj",
")",
"cols",
"=",
"list",
"(",
"self",
".",
"levels",
")",
"cols",
".",
"append",
"(",
"name",
")",
"obj",
".",
"columns",
"=",
"cols",
"return",
"super",
"(",
")",
".",
"write",
"(",
"obj",
"=",
"obj",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | GenericTable.get_attrs | retrieve our attributes | pandas/io/pytables.py | def get_attrs(self):
""" retrieve our attributes """
self.non_index_axes = []
self.nan_rep = None
self.levels = []
self.index_axes = [a.infer(self)
for a in self.indexables if a.is_an_indexable]
self.values_axes = [a.infer(self)
for a in self.indexables if not a.is_an_indexable]
self.data_columns = [a.name for a in self.values_axes] | def get_attrs(self):
""" retrieve our attributes """
self.non_index_axes = []
self.nan_rep = None
self.levels = []
self.index_axes = [a.infer(self)
for a in self.indexables if a.is_an_indexable]
self.values_axes = [a.infer(self)
for a in self.indexables if not a.is_an_indexable]
self.data_columns = [a.name for a in self.values_axes] | [
"retrieve",
"our",
"attributes"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L4254-L4264 | [
"def",
"get_attrs",
"(",
"self",
")",
":",
"self",
".",
"non_index_axes",
"=",
"[",
"]",
"self",
".",
"nan_rep",
"=",
"None",
"self",
".",
"levels",
"=",
"[",
"]",
"self",
".",
"index_axes",
"=",
"[",
"a",
".",
"infer",
"(",
"self",
")",
"for",
"a",
"in",
"self",
".",
"indexables",
"if",
"a",
".",
"is_an_indexable",
"]",
"self",
".",
"values_axes",
"=",
"[",
"a",
".",
"infer",
"(",
"self",
")",
"for",
"a",
"in",
"self",
".",
"indexables",
"if",
"not",
"a",
".",
"is_an_indexable",
"]",
"self",
".",
"data_columns",
"=",
"[",
"a",
".",
"name",
"for",
"a",
"in",
"self",
".",
"values_axes",
"]"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | GenericTable.indexables | create the indexables from the table description | pandas/io/pytables.py | def indexables(self):
""" create the indexables from the table description """
if self._indexables is None:
d = self.description
# the index columns is just a simple index
self._indexables = [GenericIndexCol(name='index', axis=0)]
for i, n in enumerate(d._v_names):
dc = GenericDataIndexableCol(
name=n, pos=i, values=[n], version=self.version)
self._indexables.append(dc)
return self._indexables | def indexables(self):
""" create the indexables from the table description """
if self._indexables is None:
d = self.description
# the index columns is just a simple index
self._indexables = [GenericIndexCol(name='index', axis=0)]
for i, n in enumerate(d._v_names):
dc = GenericDataIndexableCol(
name=n, pos=i, values=[n], version=self.version)
self._indexables.append(dc)
return self._indexables | [
"create",
"the",
"indexables",
"from",
"the",
"table",
"description"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L4267-L4282 | [
"def",
"indexables",
"(",
"self",
")",
":",
"if",
"self",
".",
"_indexables",
"is",
"None",
":",
"d",
"=",
"self",
".",
"description",
"# the index columns is just a simple index",
"self",
".",
"_indexables",
"=",
"[",
"GenericIndexCol",
"(",
"name",
"=",
"'index'",
",",
"axis",
"=",
"0",
")",
"]",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"d",
".",
"_v_names",
")",
":",
"dc",
"=",
"GenericDataIndexableCol",
"(",
"name",
"=",
"n",
",",
"pos",
"=",
"i",
",",
"values",
"=",
"[",
"n",
"]",
",",
"version",
"=",
"self",
".",
"version",
")",
"self",
".",
"_indexables",
".",
"append",
"(",
"dc",
")",
"return",
"self",
".",
"_indexables"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Selection.generate | where can be a : dict,list,tuple,string | pandas/io/pytables.py | def generate(self, where):
""" where can be a : dict,list,tuple,string """
if where is None:
return None
q = self.table.queryables()
try:
return Expr(where, queryables=q, encoding=self.table.encoding)
except NameError:
# raise a nice message, suggesting that the user should use
# data_columns
raise ValueError(
"The passed where expression: {0}\n"
" contains an invalid variable reference\n"
" all of the variable references must be a "
"reference to\n"
" an axis (e.g. 'index' or 'columns'), or a "
"data_column\n"
" The currently defined references are: {1}\n"
.format(where, ','.join(q.keys()))
) | def generate(self, where):
""" where can be a : dict,list,tuple,string """
if where is None:
return None
q = self.table.queryables()
try:
return Expr(where, queryables=q, encoding=self.table.encoding)
except NameError:
# raise a nice message, suggesting that the user should use
# data_columns
raise ValueError(
"The passed where expression: {0}\n"
" contains an invalid variable reference\n"
" all of the variable references must be a "
"reference to\n"
" an axis (e.g. 'index' or 'columns'), or a "
"data_column\n"
" The currently defined references are: {1}\n"
.format(where, ','.join(q.keys()))
) | [
"where",
"can",
"be",
"a",
":",
"dict",
"list",
"tuple",
"string"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L4679-L4699 | [
"def",
"generate",
"(",
"self",
",",
"where",
")",
":",
"if",
"where",
"is",
"None",
":",
"return",
"None",
"q",
"=",
"self",
".",
"table",
".",
"queryables",
"(",
")",
"try",
":",
"return",
"Expr",
"(",
"where",
",",
"queryables",
"=",
"q",
",",
"encoding",
"=",
"self",
".",
"table",
".",
"encoding",
")",
"except",
"NameError",
":",
"# raise a nice message, suggesting that the user should use",
"# data_columns",
"raise",
"ValueError",
"(",
"\"The passed where expression: {0}\\n\"",
"\" contains an invalid variable reference\\n\"",
"\" all of the variable references must be a \"",
"\"reference to\\n\"",
"\" an axis (e.g. 'index' or 'columns'), or a \"",
"\"data_column\\n\"",
"\" The currently defined references are: {1}\\n\"",
".",
"format",
"(",
"where",
",",
"','",
".",
"join",
"(",
"q",
".",
"keys",
"(",
")",
")",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Selection.select | generate the selection | pandas/io/pytables.py | def select(self):
"""
generate the selection
"""
if self.condition is not None:
return self.table.table.read_where(self.condition.format(),
start=self.start,
stop=self.stop)
elif self.coordinates is not None:
return self.table.table.read_coordinates(self.coordinates)
return self.table.table.read(start=self.start, stop=self.stop) | def select(self):
"""
generate the selection
"""
if self.condition is not None:
return self.table.table.read_where(self.condition.format(),
start=self.start,
stop=self.stop)
elif self.coordinates is not None:
return self.table.table.read_coordinates(self.coordinates)
return self.table.table.read(start=self.start, stop=self.stop) | [
"generate",
"the",
"selection"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L4701-L4711 | [
"def",
"select",
"(",
"self",
")",
":",
"if",
"self",
".",
"condition",
"is",
"not",
"None",
":",
"return",
"self",
".",
"table",
".",
"table",
".",
"read_where",
"(",
"self",
".",
"condition",
".",
"format",
"(",
")",
",",
"start",
"=",
"self",
".",
"start",
",",
"stop",
"=",
"self",
".",
"stop",
")",
"elif",
"self",
".",
"coordinates",
"is",
"not",
"None",
":",
"return",
"self",
".",
"table",
".",
"table",
".",
"read_coordinates",
"(",
"self",
".",
"coordinates",
")",
"return",
"self",
".",
"table",
".",
"table",
".",
"read",
"(",
"start",
"=",
"self",
".",
"start",
",",
"stop",
"=",
"self",
".",
"stop",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | Selection.select_coords | generate the selection | pandas/io/pytables.py | def select_coords(self):
"""
generate the selection
"""
start, stop = self.start, self.stop
nrows = self.table.nrows
if start is None:
start = 0
elif start < 0:
start += nrows
if self.stop is None:
stop = nrows
elif stop < 0:
stop += nrows
if self.condition is not None:
return self.table.table.get_where_list(self.condition.format(),
start=start, stop=stop,
sort=True)
elif self.coordinates is not None:
return self.coordinates
return np.arange(start, stop) | def select_coords(self):
"""
generate the selection
"""
start, stop = self.start, self.stop
nrows = self.table.nrows
if start is None:
start = 0
elif start < 0:
start += nrows
if self.stop is None:
stop = nrows
elif stop < 0:
stop += nrows
if self.condition is not None:
return self.table.table.get_where_list(self.condition.format(),
start=start, stop=stop,
sort=True)
elif self.coordinates is not None:
return self.coordinates
return np.arange(start, stop) | [
"generate",
"the",
"selection"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L4713-L4735 | [
"def",
"select_coords",
"(",
"self",
")",
":",
"start",
",",
"stop",
"=",
"self",
".",
"start",
",",
"self",
".",
"stop",
"nrows",
"=",
"self",
".",
"table",
".",
"nrows",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"0",
"elif",
"start",
"<",
"0",
":",
"start",
"+=",
"nrows",
"if",
"self",
".",
"stop",
"is",
"None",
":",
"stop",
"=",
"nrows",
"elif",
"stop",
"<",
"0",
":",
"stop",
"+=",
"nrows",
"if",
"self",
".",
"condition",
"is",
"not",
"None",
":",
"return",
"self",
".",
"table",
".",
"table",
".",
"get_where_list",
"(",
"self",
".",
"condition",
".",
"format",
"(",
")",
",",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"sort",
"=",
"True",
")",
"elif",
"self",
".",
"coordinates",
"is",
"not",
"None",
":",
"return",
"self",
".",
"coordinates",
"return",
"np",
".",
"arange",
"(",
"start",
",",
"stop",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray.astype | Cast to a NumPy array with 'dtype'.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
copy : bool, default True
Whether to copy the data, even if not necessary. If False,
a copy is made only if the old dtype does not match the
new dtype.
Returns
-------
array : ndarray
NumPy ndarray with 'dtype' for its dtype. | pandas/core/arrays/base.py | def astype(self, dtype, copy=True):
"""
Cast to a NumPy array with 'dtype'.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
copy : bool, default True
Whether to copy the data, even if not necessary. If False,
a copy is made only if the old dtype does not match the
new dtype.
Returns
-------
array : ndarray
NumPy ndarray with 'dtype' for its dtype.
"""
return np.array(self, dtype=dtype, copy=copy) | def astype(self, dtype, copy=True):
"""
Cast to a NumPy array with 'dtype'.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
copy : bool, default True
Whether to copy the data, even if not necessary. If False,
a copy is made only if the old dtype does not match the
new dtype.
Returns
-------
array : ndarray
NumPy ndarray with 'dtype' for its dtype.
"""
return np.array(self, dtype=dtype, copy=copy) | [
"Cast",
"to",
"a",
"NumPy",
"array",
"with",
"dtype",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L322-L340 | [
"def",
"astype",
"(",
"self",
",",
"dtype",
",",
"copy",
"=",
"True",
")",
":",
"return",
"np",
".",
"array",
"(",
"self",
",",
"dtype",
"=",
"dtype",
",",
"copy",
"=",
"copy",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray.argsort | Return the indices that would sort this array.
Parameters
----------
ascending : bool, default True
Whether the indices should result in an ascending
or descending sort.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
*args, **kwargs:
passed through to :func:`numpy.argsort`.
Returns
-------
index_array : ndarray
Array of indices that sort ``self``.
See Also
--------
numpy.argsort : Sorting implementation used internally. | pandas/core/arrays/base.py | def argsort(self, ascending=True, kind='quicksort', *args, **kwargs):
"""
Return the indices that would sort this array.
Parameters
----------
ascending : bool, default True
Whether the indices should result in an ascending
or descending sort.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
*args, **kwargs:
passed through to :func:`numpy.argsort`.
Returns
-------
index_array : ndarray
Array of indices that sort ``self``.
See Also
--------
numpy.argsort : Sorting implementation used internally.
"""
# Implementor note: You have two places to override the behavior of
# argsort.
# 1. _values_for_argsort : construct the values passed to np.argsort
# 2. argsort : total control over sorting.
ascending = nv.validate_argsort_with_ascending(ascending, args, kwargs)
values = self._values_for_argsort()
result = np.argsort(values, kind=kind, **kwargs)
if not ascending:
result = result[::-1]
return result | def argsort(self, ascending=True, kind='quicksort', *args, **kwargs):
"""
Return the indices that would sort this array.
Parameters
----------
ascending : bool, default True
Whether the indices should result in an ascending
or descending sort.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
*args, **kwargs:
passed through to :func:`numpy.argsort`.
Returns
-------
index_array : ndarray
Array of indices that sort ``self``.
See Also
--------
numpy.argsort : Sorting implementation used internally.
"""
# Implementor note: You have two places to override the behavior of
# argsort.
# 1. _values_for_argsort : construct the values passed to np.argsort
# 2. argsort : total control over sorting.
ascending = nv.validate_argsort_with_ascending(ascending, args, kwargs)
values = self._values_for_argsort()
result = np.argsort(values, kind=kind, **kwargs)
if not ascending:
result = result[::-1]
return result | [
"Return",
"the",
"indices",
"that",
"would",
"sort",
"this",
"array",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L381-L413 | [
"def",
"argsort",
"(",
"self",
",",
"ascending",
"=",
"True",
",",
"kind",
"=",
"'quicksort'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implementor note: You have two places to override the behavior of",
"# argsort.",
"# 1. _values_for_argsort : construct the values passed to np.argsort",
"# 2. argsort : total control over sorting.",
"ascending",
"=",
"nv",
".",
"validate_argsort_with_ascending",
"(",
"ascending",
",",
"args",
",",
"kwargs",
")",
"values",
"=",
"self",
".",
"_values_for_argsort",
"(",
")",
"result",
"=",
"np",
".",
"argsort",
"(",
"values",
",",
"kind",
"=",
"kind",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"ascending",
":",
"result",
"=",
"result",
"[",
":",
":",
"-",
"1",
"]",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray.fillna | Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, array-like
If a scalar value is passed it is used to fill all missing values.
Alternatively, an array-like 'value' can be given. It's expected
that the array-like have the same length as 'self'.
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
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 : ExtensionArray with NA/NaN filled | pandas/core/arrays/base.py | def fillna(self, value=None, method=None, limit=None):
"""
Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, array-like
If a scalar value is passed it is used to fill all missing values.
Alternatively, an array-like 'value' can be given. It's expected
that the array-like have the same length as 'self'.
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
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 : ExtensionArray with NA/NaN filled
"""
from pandas.api.types import is_array_like
from pandas.util._validators import validate_fillna_kwargs
from pandas.core.missing import pad_1d, backfill_1d
value, method = validate_fillna_kwargs(value, method)
mask = self.isna()
if is_array_like(value):
if len(value) != len(self):
raise ValueError("Length of 'value' does not match. Got ({}) "
" expected {}".format(len(value), len(self)))
value = value[mask]
if mask.any():
if method is not None:
func = pad_1d if method == 'pad' else backfill_1d
new_values = func(self.astype(object), limit=limit,
mask=mask)
new_values = self._from_sequence(new_values, dtype=self.dtype)
else:
# fill with value
new_values = self.copy()
new_values[mask] = value
else:
new_values = self.copy()
return new_values | def fillna(self, value=None, method=None, limit=None):
"""
Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, array-like
If a scalar value is passed it is used to fill all missing values.
Alternatively, an array-like 'value' can be given. It's expected
that the array-like have the same length as 'self'.
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
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 : ExtensionArray with NA/NaN filled
"""
from pandas.api.types import is_array_like
from pandas.util._validators import validate_fillna_kwargs
from pandas.core.missing import pad_1d, backfill_1d
value, method = validate_fillna_kwargs(value, method)
mask = self.isna()
if is_array_like(value):
if len(value) != len(self):
raise ValueError("Length of 'value' does not match. Got ({}) "
" expected {}".format(len(value), len(self)))
value = value[mask]
if mask.any():
if method is not None:
func = pad_1d if method == 'pad' else backfill_1d
new_values = func(self.astype(object), limit=limit,
mask=mask)
new_values = self._from_sequence(new_values, dtype=self.dtype)
else:
# fill with value
new_values = self.copy()
new_values[mask] = value
else:
new_values = self.copy()
return new_values | [
"Fill",
"NA",
"/",
"NaN",
"values",
"using",
"the",
"specified",
"method",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L415-L467 | [
"def",
"fillna",
"(",
"self",
",",
"value",
"=",
"None",
",",
"method",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"from",
"pandas",
".",
"api",
".",
"types",
"import",
"is_array_like",
"from",
"pandas",
".",
"util",
".",
"_validators",
"import",
"validate_fillna_kwargs",
"from",
"pandas",
".",
"core",
".",
"missing",
"import",
"pad_1d",
",",
"backfill_1d",
"value",
",",
"method",
"=",
"validate_fillna_kwargs",
"(",
"value",
",",
"method",
")",
"mask",
"=",
"self",
".",
"isna",
"(",
")",
"if",
"is_array_like",
"(",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"len",
"(",
"self",
")",
":",
"raise",
"ValueError",
"(",
"\"Length of 'value' does not match. Got ({}) \"",
"\" expected {}\"",
".",
"format",
"(",
"len",
"(",
"value",
")",
",",
"len",
"(",
"self",
")",
")",
")",
"value",
"=",
"value",
"[",
"mask",
"]",
"if",
"mask",
".",
"any",
"(",
")",
":",
"if",
"method",
"is",
"not",
"None",
":",
"func",
"=",
"pad_1d",
"if",
"method",
"==",
"'pad'",
"else",
"backfill_1d",
"new_values",
"=",
"func",
"(",
"self",
".",
"astype",
"(",
"object",
")",
",",
"limit",
"=",
"limit",
",",
"mask",
"=",
"mask",
")",
"new_values",
"=",
"self",
".",
"_from_sequence",
"(",
"new_values",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"else",
":",
"# fill with value",
"new_values",
"=",
"self",
".",
"copy",
"(",
")",
"new_values",
"[",
"mask",
"]",
"=",
"value",
"else",
":",
"new_values",
"=",
"self",
".",
"copy",
"(",
")",
"return",
"new_values"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray.shift | Shift values by desired number.
Newly introduced missing values are filled with
``self.dtype.na_value``.
.. versionadded:: 0.24.0
Parameters
----------
periods : int, default 1
The number of periods to shift. Negative values are allowed
for shifting backwards.
fill_value : object, optional
The scalar value to use for newly introduced missing values.
The default is ``self.dtype.na_value``
.. versionadded:: 0.24.0
Returns
-------
shifted : ExtensionArray
Notes
-----
If ``self`` is empty or ``periods`` is 0, a copy of ``self`` is
returned.
If ``periods > len(self)``, then an array of size
len(self) is returned, with all values filled with
``self.dtype.na_value``. | pandas/core/arrays/base.py | def shift(
self,
periods: int = 1,
fill_value: object = None,
) -> ABCExtensionArray:
"""
Shift values by desired number.
Newly introduced missing values are filled with
``self.dtype.na_value``.
.. versionadded:: 0.24.0
Parameters
----------
periods : int, default 1
The number of periods to shift. Negative values are allowed
for shifting backwards.
fill_value : object, optional
The scalar value to use for newly introduced missing values.
The default is ``self.dtype.na_value``
.. versionadded:: 0.24.0
Returns
-------
shifted : ExtensionArray
Notes
-----
If ``self`` is empty or ``periods`` is 0, a copy of ``self`` is
returned.
If ``periods > len(self)``, then an array of size
len(self) is returned, with all values filled with
``self.dtype.na_value``.
"""
# Note: this implementation assumes that `self.dtype.na_value` can be
# stored in an instance of your ExtensionArray with `self.dtype`.
if not len(self) or periods == 0:
return self.copy()
if isna(fill_value):
fill_value = self.dtype.na_value
empty = self._from_sequence(
[fill_value] * min(abs(periods), len(self)),
dtype=self.dtype
)
if periods > 0:
a = empty
b = self[:-periods]
else:
a = self[abs(periods):]
b = empty
return self._concat_same_type([a, b]) | def shift(
self,
periods: int = 1,
fill_value: object = None,
) -> ABCExtensionArray:
"""
Shift values by desired number.
Newly introduced missing values are filled with
``self.dtype.na_value``.
.. versionadded:: 0.24.0
Parameters
----------
periods : int, default 1
The number of periods to shift. Negative values are allowed
for shifting backwards.
fill_value : object, optional
The scalar value to use for newly introduced missing values.
The default is ``self.dtype.na_value``
.. versionadded:: 0.24.0
Returns
-------
shifted : ExtensionArray
Notes
-----
If ``self`` is empty or ``periods`` is 0, a copy of ``self`` is
returned.
If ``periods > len(self)``, then an array of size
len(self) is returned, with all values filled with
``self.dtype.na_value``.
"""
# Note: this implementation assumes that `self.dtype.na_value` can be
# stored in an instance of your ExtensionArray with `self.dtype`.
if not len(self) or periods == 0:
return self.copy()
if isna(fill_value):
fill_value = self.dtype.na_value
empty = self._from_sequence(
[fill_value] * min(abs(periods), len(self)),
dtype=self.dtype
)
if periods > 0:
a = empty
b = self[:-periods]
else:
a = self[abs(periods):]
b = empty
return self._concat_same_type([a, b]) | [
"Shift",
"values",
"by",
"desired",
"number",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L479-L535 | [
"def",
"shift",
"(",
"self",
",",
"periods",
":",
"int",
"=",
"1",
",",
"fill_value",
":",
"object",
"=",
"None",
",",
")",
"->",
"ABCExtensionArray",
":",
"# Note: this implementation assumes that `self.dtype.na_value` can be",
"# stored in an instance of your ExtensionArray with `self.dtype`.",
"if",
"not",
"len",
"(",
"self",
")",
"or",
"periods",
"==",
"0",
":",
"return",
"self",
".",
"copy",
"(",
")",
"if",
"isna",
"(",
"fill_value",
")",
":",
"fill_value",
"=",
"self",
".",
"dtype",
".",
"na_value",
"empty",
"=",
"self",
".",
"_from_sequence",
"(",
"[",
"fill_value",
"]",
"*",
"min",
"(",
"abs",
"(",
"periods",
")",
",",
"len",
"(",
"self",
")",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"if",
"periods",
">",
"0",
":",
"a",
"=",
"empty",
"b",
"=",
"self",
"[",
":",
"-",
"periods",
"]",
"else",
":",
"a",
"=",
"self",
"[",
"abs",
"(",
"periods",
")",
":",
"]",
"b",
"=",
"empty",
"return",
"self",
".",
"_concat_same_type",
"(",
"[",
"a",
",",
"b",
"]",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray.unique | Compute the ExtensionArray of unique values.
Returns
-------
uniques : ExtensionArray | pandas/core/arrays/base.py | def unique(self):
"""
Compute the ExtensionArray of unique values.
Returns
-------
uniques : ExtensionArray
"""
from pandas import unique
uniques = unique(self.astype(object))
return self._from_sequence(uniques, dtype=self.dtype) | def unique(self):
"""
Compute the ExtensionArray of unique values.
Returns
-------
uniques : ExtensionArray
"""
from pandas import unique
uniques = unique(self.astype(object))
return self._from_sequence(uniques, dtype=self.dtype) | [
"Compute",
"the",
"ExtensionArray",
"of",
"unique",
"values",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L537-L548 | [
"def",
"unique",
"(",
"self",
")",
":",
"from",
"pandas",
"import",
"unique",
"uniques",
"=",
"unique",
"(",
"self",
".",
"astype",
"(",
"object",
")",
")",
"return",
"self",
".",
"_from_sequence",
"(",
"uniques",
",",
"dtype",
"=",
"self",
".",
"dtype",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray.searchsorted | Find indices where elements should be inserted to maintain order.
.. versionadded:: 0.24.0
Find the indices into a sorted array `self` (a) such that, if the
corresponding elements in `value` were inserted before the indices,
the order of `self` would be preserved.
Assuming that `self` is sorted:
====== ================================
`side` returned index `i` satisfies
====== ================================
left ``self[i-1] < value <= self[i]``
right ``self[i-1] <= value < self[i]``
====== ================================
Parameters
----------
value : array_like
Values to insert into `self`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `self`).
sorter : 1-D array_like, optional
Optional array of integer indices that sort array a into ascending
order. They are typically the result of argsort.
Returns
-------
array of ints
Array of insertion points with the same shape as `value`.
See Also
--------
numpy.searchsorted : Similar method from NumPy. | pandas/core/arrays/base.py | def searchsorted(self, value, side="left", sorter=None):
"""
Find indices where elements should be inserted to maintain order.
.. versionadded:: 0.24.0
Find the indices into a sorted array `self` (a) such that, if the
corresponding elements in `value` were inserted before the indices,
the order of `self` would be preserved.
Assuming that `self` is sorted:
====== ================================
`side` returned index `i` satisfies
====== ================================
left ``self[i-1] < value <= self[i]``
right ``self[i-1] <= value < self[i]``
====== ================================
Parameters
----------
value : array_like
Values to insert into `self`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `self`).
sorter : 1-D array_like, optional
Optional array of integer indices that sort array a into ascending
order. They are typically the result of argsort.
Returns
-------
array of ints
Array of insertion points with the same shape as `value`.
See Also
--------
numpy.searchsorted : Similar method from NumPy.
"""
# Note: the base tests provided by pandas only test the basics.
# We do not test
# 1. Values outside the range of the `data_for_sorting` fixture
# 2. Values between the values in the `data_for_sorting` fixture
# 3. Missing values.
arr = self.astype(object)
return arr.searchsorted(value, side=side, sorter=sorter) | def searchsorted(self, value, side="left", sorter=None):
"""
Find indices where elements should be inserted to maintain order.
.. versionadded:: 0.24.0
Find the indices into a sorted array `self` (a) such that, if the
corresponding elements in `value` were inserted before the indices,
the order of `self` would be preserved.
Assuming that `self` is sorted:
====== ================================
`side` returned index `i` satisfies
====== ================================
left ``self[i-1] < value <= self[i]``
right ``self[i-1] <= value < self[i]``
====== ================================
Parameters
----------
value : array_like
Values to insert into `self`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `self`).
sorter : 1-D array_like, optional
Optional array of integer indices that sort array a into ascending
order. They are typically the result of argsort.
Returns
-------
array of ints
Array of insertion points with the same shape as `value`.
See Also
--------
numpy.searchsorted : Similar method from NumPy.
"""
# Note: the base tests provided by pandas only test the basics.
# We do not test
# 1. Values outside the range of the `data_for_sorting` fixture
# 2. Values between the values in the `data_for_sorting` fixture
# 3. Missing values.
arr = self.astype(object)
return arr.searchsorted(value, side=side, sorter=sorter) | [
"Find",
"indices",
"where",
"elements",
"should",
"be",
"inserted",
"to",
"maintain",
"order",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L550-L596 | [
"def",
"searchsorted",
"(",
"self",
",",
"value",
",",
"side",
"=",
"\"left\"",
",",
"sorter",
"=",
"None",
")",
":",
"# Note: the base tests provided by pandas only test the basics.",
"# We do not test",
"# 1. Values outside the range of the `data_for_sorting` fixture",
"# 2. Values between the values in the `data_for_sorting` fixture",
"# 3. Missing values.",
"arr",
"=",
"self",
".",
"astype",
"(",
"object",
")",
"return",
"arr",
".",
"searchsorted",
"(",
"value",
",",
"side",
"=",
"side",
",",
"sorter",
"=",
"sorter",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray._values_for_factorize | Return an array and missing value suitable for factorization.
Returns
-------
values : ndarray
An array suitable for factorization. This should maintain order
and be a supported dtype (Float64, Int64, UInt64, String, Object).
By default, the extension array is cast to object dtype.
na_value : object
The value in `values` to consider missing. This will be treated
as NA in the factorization routines, so it will be coded as
`na_sentinal` and not included in `uniques`. By default,
``np.nan`` is used.
Notes
-----
The values returned by this method are also used in
:func:`pandas.util.hash_pandas_object`. | pandas/core/arrays/base.py | def _values_for_factorize(self) -> Tuple[np.ndarray, Any]:
"""
Return an array and missing value suitable for factorization.
Returns
-------
values : ndarray
An array suitable for factorization. This should maintain order
and be a supported dtype (Float64, Int64, UInt64, String, Object).
By default, the extension array is cast to object dtype.
na_value : object
The value in `values` to consider missing. This will be treated
as NA in the factorization routines, so it will be coded as
`na_sentinal` and not included in `uniques`. By default,
``np.nan`` is used.
Notes
-----
The values returned by this method are also used in
:func:`pandas.util.hash_pandas_object`.
"""
return self.astype(object), np.nan | def _values_for_factorize(self) -> Tuple[np.ndarray, Any]:
"""
Return an array and missing value suitable for factorization.
Returns
-------
values : ndarray
An array suitable for factorization. This should maintain order
and be a supported dtype (Float64, Int64, UInt64, String, Object).
By default, the extension array is cast to object dtype.
na_value : object
The value in `values` to consider missing. This will be treated
as NA in the factorization routines, so it will be coded as
`na_sentinal` and not included in `uniques`. By default,
``np.nan`` is used.
Notes
-----
The values returned by this method are also used in
:func:`pandas.util.hash_pandas_object`.
"""
return self.astype(object), np.nan | [
"Return",
"an",
"array",
"and",
"missing",
"value",
"suitable",
"for",
"factorization",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L598-L620 | [
"def",
"_values_for_factorize",
"(",
"self",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"Any",
"]",
":",
"return",
"self",
".",
"astype",
"(",
"object",
")",
",",
"np",
".",
"nan"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray.factorize | Encode the extension array as an enumerated type.
Parameters
----------
na_sentinel : int, default -1
Value to use in the `labels` array to indicate missing values.
Returns
-------
labels : ndarray
An integer NumPy array that's an indexer into the original
ExtensionArray.
uniques : ExtensionArray
An ExtensionArray containing the unique values of `self`.
.. note::
uniques will *not* contain an entry for the NA value of
the ExtensionArray if there are any missing values present
in `self`.
See Also
--------
pandas.factorize : Top-level factorize method that dispatches here.
Notes
-----
:meth:`pandas.factorize` offers a `sort` keyword as well. | pandas/core/arrays/base.py | def factorize(
self,
na_sentinel: int = -1,
) -> Tuple[np.ndarray, ABCExtensionArray]:
"""
Encode the extension array as an enumerated type.
Parameters
----------
na_sentinel : int, default -1
Value to use in the `labels` array to indicate missing values.
Returns
-------
labels : ndarray
An integer NumPy array that's an indexer into the original
ExtensionArray.
uniques : ExtensionArray
An ExtensionArray containing the unique values of `self`.
.. note::
uniques will *not* contain an entry for the NA value of
the ExtensionArray if there are any missing values present
in `self`.
See Also
--------
pandas.factorize : Top-level factorize method that dispatches here.
Notes
-----
:meth:`pandas.factorize` offers a `sort` keyword as well.
"""
# Impelmentor note: There are two ways to override the behavior of
# pandas.factorize
# 1. _values_for_factorize and _from_factorize.
# Specify the values passed to pandas' internal factorization
# routines, and how to convert from those values back to the
# original ExtensionArray.
# 2. ExtensionArray.factorize.
# Complete control over factorization.
from pandas.core.algorithms import _factorize_array
arr, na_value = self._values_for_factorize()
labels, uniques = _factorize_array(arr, na_sentinel=na_sentinel,
na_value=na_value)
uniques = self._from_factorized(uniques, self)
return labels, uniques | def factorize(
self,
na_sentinel: int = -1,
) -> Tuple[np.ndarray, ABCExtensionArray]:
"""
Encode the extension array as an enumerated type.
Parameters
----------
na_sentinel : int, default -1
Value to use in the `labels` array to indicate missing values.
Returns
-------
labels : ndarray
An integer NumPy array that's an indexer into the original
ExtensionArray.
uniques : ExtensionArray
An ExtensionArray containing the unique values of `self`.
.. note::
uniques will *not* contain an entry for the NA value of
the ExtensionArray if there are any missing values present
in `self`.
See Also
--------
pandas.factorize : Top-level factorize method that dispatches here.
Notes
-----
:meth:`pandas.factorize` offers a `sort` keyword as well.
"""
# Impelmentor note: There are two ways to override the behavior of
# pandas.factorize
# 1. _values_for_factorize and _from_factorize.
# Specify the values passed to pandas' internal factorization
# routines, and how to convert from those values back to the
# original ExtensionArray.
# 2. ExtensionArray.factorize.
# Complete control over factorization.
from pandas.core.algorithms import _factorize_array
arr, na_value = self._values_for_factorize()
labels, uniques = _factorize_array(arr, na_sentinel=na_sentinel,
na_value=na_value)
uniques = self._from_factorized(uniques, self)
return labels, uniques | [
"Encode",
"the",
"extension",
"array",
"as",
"an",
"enumerated",
"type",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L622-L672 | [
"def",
"factorize",
"(",
"self",
",",
"na_sentinel",
":",
"int",
"=",
"-",
"1",
",",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"ABCExtensionArray",
"]",
":",
"# Impelmentor note: There are two ways to override the behavior of",
"# pandas.factorize",
"# 1. _values_for_factorize and _from_factorize.",
"# Specify the values passed to pandas' internal factorization",
"# routines, and how to convert from those values back to the",
"# original ExtensionArray.",
"# 2. ExtensionArray.factorize.",
"# Complete control over factorization.",
"from",
"pandas",
".",
"core",
".",
"algorithms",
"import",
"_factorize_array",
"arr",
",",
"na_value",
"=",
"self",
".",
"_values_for_factorize",
"(",
")",
"labels",
",",
"uniques",
"=",
"_factorize_array",
"(",
"arr",
",",
"na_sentinel",
"=",
"na_sentinel",
",",
"na_value",
"=",
"na_value",
")",
"uniques",
"=",
"self",
".",
"_from_factorized",
"(",
"uniques",
",",
"self",
")",
"return",
"labels",
",",
"uniques"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray.take | Take elements from an array.
Parameters
----------
indices : sequence of integers
Indices to be taken.
allow_fill : bool, default False
How to handle negative values in `indices`.
* False: negative values in `indices` indicate positional indices
from the right (the default). This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate
missing values. These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
fill_value : any, optional
Fill value to use for NA-indices when `allow_fill` is True.
This may be ``None``, in which case the default NA value for
the type, ``self.dtype.na_value``, is used.
For many ExtensionArrays, there will be two representations of
`fill_value`: a user-facing "boxed" scalar, and a low-level
physical NA value. `fill_value` should be the user-facing version,
and the implementation should handle translating that to the
physical version for processing the take if necessary.
Returns
-------
ExtensionArray
Raises
------
IndexError
When the indices are out of bounds for the array.
ValueError
When `indices` contains negative values other than ``-1``
and `allow_fill` is True.
Notes
-----
ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``,
``iloc``, when `indices` is a sequence of values. Additionally,
it's called by :meth:`Series.reindex`, or any other method
that causes realignment, with a `fill_value`.
See Also
--------
numpy.take
pandas.api.extensions.take
Examples
--------
Here's an example implementation, which relies on casting the
extension array to object dtype. This uses the helper method
:func:`pandas.api.extensions.take`.
.. code-block:: python
def take(self, indices, allow_fill=False, fill_value=None):
from pandas.core.algorithms import take
# If the ExtensionArray is backed by an ndarray, then
# just pass that here instead of coercing to object.
data = self.astype(object)
if allow_fill and fill_value is None:
fill_value = self.dtype.na_value
# fill value should always be translated from the scalar
# type for the array, to the physical storage type for
# the data, before passing to take.
result = take(data, indices, fill_value=fill_value,
allow_fill=allow_fill)
return self._from_sequence(result, dtype=self.dtype) | pandas/core/arrays/base.py | def take(
self,
indices: Sequence[int],
allow_fill: bool = False,
fill_value: Any = None
) -> ABCExtensionArray:
"""
Take elements from an array.
Parameters
----------
indices : sequence of integers
Indices to be taken.
allow_fill : bool, default False
How to handle negative values in `indices`.
* False: negative values in `indices` indicate positional indices
from the right (the default). This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate
missing values. These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
fill_value : any, optional
Fill value to use for NA-indices when `allow_fill` is True.
This may be ``None``, in which case the default NA value for
the type, ``self.dtype.na_value``, is used.
For many ExtensionArrays, there will be two representations of
`fill_value`: a user-facing "boxed" scalar, and a low-level
physical NA value. `fill_value` should be the user-facing version,
and the implementation should handle translating that to the
physical version for processing the take if necessary.
Returns
-------
ExtensionArray
Raises
------
IndexError
When the indices are out of bounds for the array.
ValueError
When `indices` contains negative values other than ``-1``
and `allow_fill` is True.
Notes
-----
ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``,
``iloc``, when `indices` is a sequence of values. Additionally,
it's called by :meth:`Series.reindex`, or any other method
that causes realignment, with a `fill_value`.
See Also
--------
numpy.take
pandas.api.extensions.take
Examples
--------
Here's an example implementation, which relies on casting the
extension array to object dtype. This uses the helper method
:func:`pandas.api.extensions.take`.
.. code-block:: python
def take(self, indices, allow_fill=False, fill_value=None):
from pandas.core.algorithms import take
# If the ExtensionArray is backed by an ndarray, then
# just pass that here instead of coercing to object.
data = self.astype(object)
if allow_fill and fill_value is None:
fill_value = self.dtype.na_value
# fill value should always be translated from the scalar
# type for the array, to the physical storage type for
# the data, before passing to take.
result = take(data, indices, fill_value=fill_value,
allow_fill=allow_fill)
return self._from_sequence(result, dtype=self.dtype)
"""
# Implementer note: The `fill_value` parameter should be a user-facing
# value, an instance of self.dtype.type. When passed `fill_value=None`,
# the default of `self.dtype.na_value` should be used.
# This may differ from the physical storage type your ExtensionArray
# uses. In this case, your implementation is responsible for casting
# the user-facing type to the storage type, before using
# pandas.api.extensions.take
raise AbstractMethodError(self) | def take(
self,
indices: Sequence[int],
allow_fill: bool = False,
fill_value: Any = None
) -> ABCExtensionArray:
"""
Take elements from an array.
Parameters
----------
indices : sequence of integers
Indices to be taken.
allow_fill : bool, default False
How to handle negative values in `indices`.
* False: negative values in `indices` indicate positional indices
from the right (the default). This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate
missing values. These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
fill_value : any, optional
Fill value to use for NA-indices when `allow_fill` is True.
This may be ``None``, in which case the default NA value for
the type, ``self.dtype.na_value``, is used.
For many ExtensionArrays, there will be two representations of
`fill_value`: a user-facing "boxed" scalar, and a low-level
physical NA value. `fill_value` should be the user-facing version,
and the implementation should handle translating that to the
physical version for processing the take if necessary.
Returns
-------
ExtensionArray
Raises
------
IndexError
When the indices are out of bounds for the array.
ValueError
When `indices` contains negative values other than ``-1``
and `allow_fill` is True.
Notes
-----
ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``,
``iloc``, when `indices` is a sequence of values. Additionally,
it's called by :meth:`Series.reindex`, or any other method
that causes realignment, with a `fill_value`.
See Also
--------
numpy.take
pandas.api.extensions.take
Examples
--------
Here's an example implementation, which relies on casting the
extension array to object dtype. This uses the helper method
:func:`pandas.api.extensions.take`.
.. code-block:: python
def take(self, indices, allow_fill=False, fill_value=None):
from pandas.core.algorithms import take
# If the ExtensionArray is backed by an ndarray, then
# just pass that here instead of coercing to object.
data = self.astype(object)
if allow_fill and fill_value is None:
fill_value = self.dtype.na_value
# fill value should always be translated from the scalar
# type for the array, to the physical storage type for
# the data, before passing to take.
result = take(data, indices, fill_value=fill_value,
allow_fill=allow_fill)
return self._from_sequence(result, dtype=self.dtype)
"""
# Implementer note: The `fill_value` parameter should be a user-facing
# value, an instance of self.dtype.type. When passed `fill_value=None`,
# the default of `self.dtype.na_value` should be used.
# This may differ from the physical storage type your ExtensionArray
# uses. In this case, your implementation is responsible for casting
# the user-facing type to the storage type, before using
# pandas.api.extensions.take
raise AbstractMethodError(self) | [
"Take",
"elements",
"from",
"an",
"array",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L727-L819 | [
"def",
"take",
"(",
"self",
",",
"indices",
":",
"Sequence",
"[",
"int",
"]",
",",
"allow_fill",
":",
"bool",
"=",
"False",
",",
"fill_value",
":",
"Any",
"=",
"None",
")",
"->",
"ABCExtensionArray",
":",
"# Implementer note: The `fill_value` parameter should be a user-facing",
"# value, an instance of self.dtype.type. When passed `fill_value=None`,",
"# the default of `self.dtype.na_value` should be used.",
"# This may differ from the physical storage type your ExtensionArray",
"# uses. In this case, your implementation is responsible for casting",
"# the user-facing type to the storage type, before using",
"# pandas.api.extensions.take",
"raise",
"AbstractMethodError",
"(",
"self",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray._formatter | Formatting function for scalar values.
This is used in the default '__repr__'. The returned formatting
function receives instances of your scalar type.
Parameters
----------
boxed: bool, default False
An indicated for whether or not your array is being printed
within a Series, DataFrame, or Index (True), or just by
itself (False). This may be useful if you want scalar values
to appear differently within a Series versus on its own (e.g.
quoted or not).
Returns
-------
Callable[[Any], str]
A callable that gets instances of the scalar type and
returns a string. By default, :func:`repr` is used
when ``boxed=False`` and :func:`str` is used when
``boxed=True``. | pandas/core/arrays/base.py | def _formatter(
self,
boxed: bool = False,
) -> Callable[[Any], Optional[str]]:
"""Formatting function for scalar values.
This is used in the default '__repr__'. The returned formatting
function receives instances of your scalar type.
Parameters
----------
boxed: bool, default False
An indicated for whether or not your array is being printed
within a Series, DataFrame, or Index (True), or just by
itself (False). This may be useful if you want scalar values
to appear differently within a Series versus on its own (e.g.
quoted or not).
Returns
-------
Callable[[Any], str]
A callable that gets instances of the scalar type and
returns a string. By default, :func:`repr` is used
when ``boxed=False`` and :func:`str` is used when
``boxed=True``.
"""
if boxed:
return str
return repr | def _formatter(
self,
boxed: bool = False,
) -> Callable[[Any], Optional[str]]:
"""Formatting function for scalar values.
This is used in the default '__repr__'. The returned formatting
function receives instances of your scalar type.
Parameters
----------
boxed: bool, default False
An indicated for whether or not your array is being printed
within a Series, DataFrame, or Index (True), or just by
itself (False). This may be useful if you want scalar values
to appear differently within a Series versus on its own (e.g.
quoted or not).
Returns
-------
Callable[[Any], str]
A callable that gets instances of the scalar type and
returns a string. By default, :func:`repr` is used
when ``boxed=False`` and :func:`str` is used when
``boxed=True``.
"""
if boxed:
return str
return repr | [
"Formatting",
"function",
"for",
"scalar",
"values",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L857-L885 | [
"def",
"_formatter",
"(",
"self",
",",
"boxed",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Optional",
"[",
"str",
"]",
"]",
":",
"if",
"boxed",
":",
"return",
"str",
"return",
"repr"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionArray._reduce | Return a scalar result of performing the reduction operation.
Parameters
----------
name : str
Name of the function, supported values are:
{ any, all, min, max, sum, mean, median, prod,
std, var, sem, kurt, skew }.
skipna : bool, default True
If True, skip NaN values.
**kwargs
Additional keyword arguments passed to the reduction function.
Currently, `ddof` is the only supported kwarg.
Returns
-------
scalar
Raises
------
TypeError : subclass does not define reductions | pandas/core/arrays/base.py | def _reduce(self, name, skipna=True, **kwargs):
"""
Return a scalar result of performing the reduction operation.
Parameters
----------
name : str
Name of the function, supported values are:
{ any, all, min, max, sum, mean, median, prod,
std, var, sem, kurt, skew }.
skipna : bool, default True
If True, skip NaN values.
**kwargs
Additional keyword arguments passed to the reduction function.
Currently, `ddof` is the only supported kwarg.
Returns
-------
scalar
Raises
------
TypeError : subclass does not define reductions
"""
raise TypeError("cannot perform {name} with type {dtype}".format(
name=name, dtype=self.dtype)) | def _reduce(self, name, skipna=True, **kwargs):
"""
Return a scalar result of performing the reduction operation.
Parameters
----------
name : str
Name of the function, supported values are:
{ any, all, min, max, sum, mean, median, prod,
std, var, sem, kurt, skew }.
skipna : bool, default True
If True, skip NaN values.
**kwargs
Additional keyword arguments passed to the reduction function.
Currently, `ddof` is the only supported kwarg.
Returns
-------
scalar
Raises
------
TypeError : subclass does not define reductions
"""
raise TypeError("cannot perform {name} with type {dtype}".format(
name=name, dtype=self.dtype)) | [
"Return",
"a",
"scalar",
"result",
"of",
"performing",
"the",
"reduction",
"operation",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L939-L964 | [
"def",
"_reduce",
"(",
"self",
",",
"name",
",",
"skipna",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"TypeError",
"(",
"\"cannot perform {name} with type {dtype}\"",
".",
"format",
"(",
"name",
"=",
"name",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ExtensionScalarOpsMixin._create_method | A class method that returns a method that will correspond to an
operator for an ExtensionArray subclass, by dispatching to the
relevant operator defined on the individual elements of the
ExtensionArray.
Parameters
----------
op : function
An operator that takes arguments op(a, b)
coerce_to_dtype : bool, default True
boolean indicating whether to attempt to convert
the result to the underlying ExtensionArray dtype.
If it's not possible to create a new ExtensionArray with the
values, an ndarray is returned instead.
Returns
-------
Callable[[Any, Any], Union[ndarray, ExtensionArray]]
A method that can be bound to a class. When used, the method
receives the two arguments, one of which is the instance of
this class, and should return an ExtensionArray or an ndarray.
Returning an ndarray may be necessary when the result of the
`op` cannot be stored in the ExtensionArray. The dtype of the
ndarray uses NumPy's normal inference rules.
Example
-------
Given an ExtensionArray subclass called MyExtensionArray, use
>>> __add__ = cls._create_method(operator.add)
in the class definition of MyExtensionArray to create the operator
for addition, that will be based on the operator implementation
of the underlying elements of the ExtensionArray | pandas/core/arrays/base.py | def _create_method(cls, op, coerce_to_dtype=True):
"""
A class method that returns a method that will correspond to an
operator for an ExtensionArray subclass, by dispatching to the
relevant operator defined on the individual elements of the
ExtensionArray.
Parameters
----------
op : function
An operator that takes arguments op(a, b)
coerce_to_dtype : bool, default True
boolean indicating whether to attempt to convert
the result to the underlying ExtensionArray dtype.
If it's not possible to create a new ExtensionArray with the
values, an ndarray is returned instead.
Returns
-------
Callable[[Any, Any], Union[ndarray, ExtensionArray]]
A method that can be bound to a class. When used, the method
receives the two arguments, one of which is the instance of
this class, and should return an ExtensionArray or an ndarray.
Returning an ndarray may be necessary when the result of the
`op` cannot be stored in the ExtensionArray. The dtype of the
ndarray uses NumPy's normal inference rules.
Example
-------
Given an ExtensionArray subclass called MyExtensionArray, use
>>> __add__ = cls._create_method(operator.add)
in the class definition of MyExtensionArray to create the operator
for addition, that will be based on the operator implementation
of the underlying elements of the ExtensionArray
"""
def _binop(self, other):
def convert_values(param):
if isinstance(param, ExtensionArray) or is_list_like(param):
ovalues = param
else: # Assume its an object
ovalues = [param] * len(self)
return ovalues
if isinstance(other, (ABCSeries, ABCIndexClass)):
# rely on pandas to unbox and dispatch to us
return NotImplemented
lvalues = self
rvalues = convert_values(other)
# If the operator is not defined for the underlying objects,
# a TypeError should be raised
res = [op(a, b) for (a, b) in zip(lvalues, rvalues)]
def _maybe_convert(arr):
if coerce_to_dtype:
# https://github.com/pandas-dev/pandas/issues/22850
# We catch all regular exceptions here, and fall back
# to an ndarray.
try:
res = self._from_sequence(arr)
except Exception:
res = np.asarray(arr)
else:
res = np.asarray(arr)
return res
if op.__name__ in {'divmod', 'rdivmod'}:
a, b = zip(*res)
res = _maybe_convert(a), _maybe_convert(b)
else:
res = _maybe_convert(res)
return res
op_name = ops._get_op_name(op, True)
return set_function_name(_binop, op_name, cls) | def _create_method(cls, op, coerce_to_dtype=True):
"""
A class method that returns a method that will correspond to an
operator for an ExtensionArray subclass, by dispatching to the
relevant operator defined on the individual elements of the
ExtensionArray.
Parameters
----------
op : function
An operator that takes arguments op(a, b)
coerce_to_dtype : bool, default True
boolean indicating whether to attempt to convert
the result to the underlying ExtensionArray dtype.
If it's not possible to create a new ExtensionArray with the
values, an ndarray is returned instead.
Returns
-------
Callable[[Any, Any], Union[ndarray, ExtensionArray]]
A method that can be bound to a class. When used, the method
receives the two arguments, one of which is the instance of
this class, and should return an ExtensionArray or an ndarray.
Returning an ndarray may be necessary when the result of the
`op` cannot be stored in the ExtensionArray. The dtype of the
ndarray uses NumPy's normal inference rules.
Example
-------
Given an ExtensionArray subclass called MyExtensionArray, use
>>> __add__ = cls._create_method(operator.add)
in the class definition of MyExtensionArray to create the operator
for addition, that will be based on the operator implementation
of the underlying elements of the ExtensionArray
"""
def _binop(self, other):
def convert_values(param):
if isinstance(param, ExtensionArray) or is_list_like(param):
ovalues = param
else: # Assume its an object
ovalues = [param] * len(self)
return ovalues
if isinstance(other, (ABCSeries, ABCIndexClass)):
# rely on pandas to unbox and dispatch to us
return NotImplemented
lvalues = self
rvalues = convert_values(other)
# If the operator is not defined for the underlying objects,
# a TypeError should be raised
res = [op(a, b) for (a, b) in zip(lvalues, rvalues)]
def _maybe_convert(arr):
if coerce_to_dtype:
# https://github.com/pandas-dev/pandas/issues/22850
# We catch all regular exceptions here, and fall back
# to an ndarray.
try:
res = self._from_sequence(arr)
except Exception:
res = np.asarray(arr)
else:
res = np.asarray(arr)
return res
if op.__name__ in {'divmod', 'rdivmod'}:
a, b = zip(*res)
res = _maybe_convert(a), _maybe_convert(b)
else:
res = _maybe_convert(res)
return res
op_name = ops._get_op_name(op, True)
return set_function_name(_binop, op_name, cls) | [
"A",
"class",
"method",
"that",
"returns",
"a",
"method",
"that",
"will",
"correspond",
"to",
"an",
"operator",
"for",
"an",
"ExtensionArray",
"subclass",
"by",
"dispatching",
"to",
"the",
"relevant",
"operator",
"defined",
"on",
"the",
"individual",
"elements",
"of",
"the",
"ExtensionArray",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L1034-L1113 | [
"def",
"_create_method",
"(",
"cls",
",",
"op",
",",
"coerce_to_dtype",
"=",
"True",
")",
":",
"def",
"_binop",
"(",
"self",
",",
"other",
")",
":",
"def",
"convert_values",
"(",
"param",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"ExtensionArray",
")",
"or",
"is_list_like",
"(",
"param",
")",
":",
"ovalues",
"=",
"param",
"else",
":",
"# Assume its an object",
"ovalues",
"=",
"[",
"param",
"]",
"*",
"len",
"(",
"self",
")",
"return",
"ovalues",
"if",
"isinstance",
"(",
"other",
",",
"(",
"ABCSeries",
",",
"ABCIndexClass",
")",
")",
":",
"# rely on pandas to unbox and dispatch to us",
"return",
"NotImplemented",
"lvalues",
"=",
"self",
"rvalues",
"=",
"convert_values",
"(",
"other",
")",
"# If the operator is not defined for the underlying objects,",
"# a TypeError should be raised",
"res",
"=",
"[",
"op",
"(",
"a",
",",
"b",
")",
"for",
"(",
"a",
",",
"b",
")",
"in",
"zip",
"(",
"lvalues",
",",
"rvalues",
")",
"]",
"def",
"_maybe_convert",
"(",
"arr",
")",
":",
"if",
"coerce_to_dtype",
":",
"# https://github.com/pandas-dev/pandas/issues/22850",
"# We catch all regular exceptions here, and fall back",
"# to an ndarray.",
"try",
":",
"res",
"=",
"self",
".",
"_from_sequence",
"(",
"arr",
")",
"except",
"Exception",
":",
"res",
"=",
"np",
".",
"asarray",
"(",
"arr",
")",
"else",
":",
"res",
"=",
"np",
".",
"asarray",
"(",
"arr",
")",
"return",
"res",
"if",
"op",
".",
"__name__",
"in",
"{",
"'divmod'",
",",
"'rdivmod'",
"}",
":",
"a",
",",
"b",
"=",
"zip",
"(",
"*",
"res",
")",
"res",
"=",
"_maybe_convert",
"(",
"a",
")",
",",
"_maybe_convert",
"(",
"b",
")",
"else",
":",
"res",
"=",
"_maybe_convert",
"(",
"res",
")",
"return",
"res",
"op_name",
"=",
"ops",
".",
"_get_op_name",
"(",
"op",
",",
"True",
")",
"return",
"set_function_name",
"(",
"_binop",
",",
"op_name",
",",
"cls",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | ea_passthrough | Make an alias for a method of the underlying ExtensionArray.
Parameters
----------
array_method : method on an Array class
Returns
-------
method | pandas/core/indexes/datetimelike.py | def ea_passthrough(array_method):
"""
Make an alias for a method of the underlying ExtensionArray.
Parameters
----------
array_method : method on an Array class
Returns
-------
method
"""
def method(self, *args, **kwargs):
return array_method(self._data, *args, **kwargs)
method.__name__ = array_method.__name__
method.__doc__ = array_method.__doc__
return method | def ea_passthrough(array_method):
"""
Make an alias for a method of the underlying ExtensionArray.
Parameters
----------
array_method : method on an Array class
Returns
-------
method
"""
def method(self, *args, **kwargs):
return array_method(self._data, *args, **kwargs)
method.__name__ = array_method.__name__
method.__doc__ = array_method.__doc__
return method | [
"Make",
"an",
"alias",
"for",
"a",
"method",
"of",
"the",
"underlying",
"ExtensionArray",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L34-L52 | [
"def",
"ea_passthrough",
"(",
"array_method",
")",
":",
"def",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"array_method",
"(",
"self",
".",
"_data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"method",
".",
"__name__",
"=",
"array_method",
".",
"__name__",
"method",
".",
"__doc__",
"=",
"array_method",
".",
"__doc__",
"return",
"method"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin._create_comparison_method | Create a comparison method that dispatches to ``cls.values``. | pandas/core/indexes/datetimelike.py | def _create_comparison_method(cls, op):
"""
Create a comparison method that dispatches to ``cls.values``.
"""
def wrapper(self, other):
if isinstance(other, ABCSeries):
# the arrays defer to Series for comparison ops but the indexes
# don't, so we have to unwrap here.
other = other._values
result = op(self._data, maybe_unwrap_index(other))
return result
wrapper.__doc__ = op.__doc__
wrapper.__name__ = '__{}__'.format(op.__name__)
return wrapper | def _create_comparison_method(cls, op):
"""
Create a comparison method that dispatches to ``cls.values``.
"""
def wrapper(self, other):
if isinstance(other, ABCSeries):
# the arrays defer to Series for comparison ops but the indexes
# don't, so we have to unwrap here.
other = other._values
result = op(self._data, maybe_unwrap_index(other))
return result
wrapper.__doc__ = op.__doc__
wrapper.__name__ = '__{}__'.format(op.__name__)
return wrapper | [
"Create",
"a",
"comparison",
"method",
"that",
"dispatches",
"to",
"cls",
".",
"values",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L107-L122 | [
"def",
"_create_comparison_method",
"(",
"cls",
",",
"op",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"ABCSeries",
")",
":",
"# the arrays defer to Series for comparison ops but the indexes",
"# don't, so we have to unwrap here.",
"other",
"=",
"other",
".",
"_values",
"result",
"=",
"op",
"(",
"self",
".",
"_data",
",",
"maybe_unwrap_index",
"(",
"other",
")",
")",
"return",
"result",
"wrapper",
".",
"__doc__",
"=",
"op",
".",
"__doc__",
"wrapper",
".",
"__name__",
"=",
"'__{}__'",
".",
"format",
"(",
"op",
".",
"__name__",
")",
"return",
"wrapper"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin.equals | Determines if two Index objects contain the same elements. | pandas/core/indexes/datetimelike.py | def equals(self, other):
"""
Determines if two Index objects contain the same elements.
"""
if self.is_(other):
return True
if not isinstance(other, ABCIndexClass):
return False
elif not isinstance(other, type(self)):
try:
other = type(self)(other)
except Exception:
return False
if not is_dtype_equal(self.dtype, other.dtype):
# have different timezone
return False
elif is_period_dtype(self):
if not is_period_dtype(other):
return False
if self.freq != other.freq:
return False
return np.array_equal(self.asi8, other.asi8) | def equals(self, other):
"""
Determines if two Index objects contain the same elements.
"""
if self.is_(other):
return True
if not isinstance(other, ABCIndexClass):
return False
elif not isinstance(other, type(self)):
try:
other = type(self)(other)
except Exception:
return False
if not is_dtype_equal(self.dtype, other.dtype):
# have different timezone
return False
elif is_period_dtype(self):
if not is_period_dtype(other):
return False
if self.freq != other.freq:
return False
return np.array_equal(self.asi8, other.asi8) | [
"Determines",
"if",
"two",
"Index",
"objects",
"contain",
"the",
"same",
"elements",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L143-L168 | [
"def",
"equals",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"is_",
"(",
"other",
")",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ABCIndexClass",
")",
":",
"return",
"False",
"elif",
"not",
"isinstance",
"(",
"other",
",",
"type",
"(",
"self",
")",
")",
":",
"try",
":",
"other",
"=",
"type",
"(",
"self",
")",
"(",
"other",
")",
"except",
"Exception",
":",
"return",
"False",
"if",
"not",
"is_dtype_equal",
"(",
"self",
".",
"dtype",
",",
"other",
".",
"dtype",
")",
":",
"# have different timezone",
"return",
"False",
"elif",
"is_period_dtype",
"(",
"self",
")",
":",
"if",
"not",
"is_period_dtype",
"(",
"other",
")",
":",
"return",
"False",
"if",
"self",
".",
"freq",
"!=",
"other",
".",
"freq",
":",
"return",
"False",
"return",
"np",
".",
"array_equal",
"(",
"self",
".",
"asi8",
",",
"other",
".",
"asi8",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin._join_i8_wrapper | Create the join wrapper methods. | pandas/core/indexes/datetimelike.py | def _join_i8_wrapper(joinf, dtype, with_indexers=True):
"""
Create the join wrapper methods.
"""
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
@staticmethod
def wrapper(left, right):
if isinstance(left, (np.ndarray, ABCIndex, ABCSeries,
DatetimeLikeArrayMixin)):
left = left.view('i8')
if isinstance(right, (np.ndarray, ABCIndex, ABCSeries,
DatetimeLikeArrayMixin)):
right = right.view('i8')
results = joinf(left, right)
if with_indexers:
join_index, left_indexer, right_indexer = results
join_index = join_index.view(dtype)
return join_index, left_indexer, right_indexer
return results
return wrapper | def _join_i8_wrapper(joinf, dtype, with_indexers=True):
"""
Create the join wrapper methods.
"""
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
@staticmethod
def wrapper(left, right):
if isinstance(left, (np.ndarray, ABCIndex, ABCSeries,
DatetimeLikeArrayMixin)):
left = left.view('i8')
if isinstance(right, (np.ndarray, ABCIndex, ABCSeries,
DatetimeLikeArrayMixin)):
right = right.view('i8')
results = joinf(left, right)
if with_indexers:
join_index, left_indexer, right_indexer = results
join_index = join_index.view(dtype)
return join_index, left_indexer, right_indexer
return results
return wrapper | [
"Create",
"the",
"join",
"wrapper",
"methods",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L171-L192 | [
"def",
"_join_i8_wrapper",
"(",
"joinf",
",",
"dtype",
",",
"with_indexers",
"=",
"True",
")",
":",
"from",
"pandas",
".",
"core",
".",
"arrays",
".",
"datetimelike",
"import",
"DatetimeLikeArrayMixin",
"@",
"staticmethod",
"def",
"wrapper",
"(",
"left",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"(",
"np",
".",
"ndarray",
",",
"ABCIndex",
",",
"ABCSeries",
",",
"DatetimeLikeArrayMixin",
")",
")",
":",
"left",
"=",
"left",
".",
"view",
"(",
"'i8'",
")",
"if",
"isinstance",
"(",
"right",
",",
"(",
"np",
".",
"ndarray",
",",
"ABCIndex",
",",
"ABCSeries",
",",
"DatetimeLikeArrayMixin",
")",
")",
":",
"right",
"=",
"right",
".",
"view",
"(",
"'i8'",
")",
"results",
"=",
"joinf",
"(",
"left",
",",
"right",
")",
"if",
"with_indexers",
":",
"join_index",
",",
"left_indexer",
",",
"right_indexer",
"=",
"results",
"join_index",
"=",
"join_index",
".",
"view",
"(",
"dtype",
")",
"return",
"join_index",
",",
"left_indexer",
",",
"right_indexer",
"return",
"results",
"return",
"wrapper"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin.sort_values | Return sorted copy of Index. | pandas/core/indexes/datetimelike.py | def sort_values(self, return_indexer=False, ascending=True):
"""
Return sorted copy of Index.
"""
if return_indexer:
_as = self.argsort()
if not ascending:
_as = _as[::-1]
sorted_index = self.take(_as)
return sorted_index, _as
else:
sorted_values = np.sort(self._ndarray_values)
attribs = self._get_attributes_dict()
freq = attribs['freq']
if freq is not None and not is_period_dtype(self):
if freq.n > 0 and not ascending:
freq = freq * -1
elif freq.n < 0 and ascending:
freq = freq * -1
attribs['freq'] = freq
if not ascending:
sorted_values = sorted_values[::-1]
return self._simple_new(sorted_values, **attribs) | def sort_values(self, return_indexer=False, ascending=True):
"""
Return sorted copy of Index.
"""
if return_indexer:
_as = self.argsort()
if not ascending:
_as = _as[::-1]
sorted_index = self.take(_as)
return sorted_index, _as
else:
sorted_values = np.sort(self._ndarray_values)
attribs = self._get_attributes_dict()
freq = attribs['freq']
if freq is not None and not is_period_dtype(self):
if freq.n > 0 and not ascending:
freq = freq * -1
elif freq.n < 0 and ascending:
freq = freq * -1
attribs['freq'] = freq
if not ascending:
sorted_values = sorted_values[::-1]
return self._simple_new(sorted_values, **attribs) | [
"Return",
"sorted",
"copy",
"of",
"Index",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L236-L261 | [
"def",
"sort_values",
"(",
"self",
",",
"return_indexer",
"=",
"False",
",",
"ascending",
"=",
"True",
")",
":",
"if",
"return_indexer",
":",
"_as",
"=",
"self",
".",
"argsort",
"(",
")",
"if",
"not",
"ascending",
":",
"_as",
"=",
"_as",
"[",
":",
":",
"-",
"1",
"]",
"sorted_index",
"=",
"self",
".",
"take",
"(",
"_as",
")",
"return",
"sorted_index",
",",
"_as",
"else",
":",
"sorted_values",
"=",
"np",
".",
"sort",
"(",
"self",
".",
"_ndarray_values",
")",
"attribs",
"=",
"self",
".",
"_get_attributes_dict",
"(",
")",
"freq",
"=",
"attribs",
"[",
"'freq'",
"]",
"if",
"freq",
"is",
"not",
"None",
"and",
"not",
"is_period_dtype",
"(",
"self",
")",
":",
"if",
"freq",
".",
"n",
">",
"0",
"and",
"not",
"ascending",
":",
"freq",
"=",
"freq",
"*",
"-",
"1",
"elif",
"freq",
".",
"n",
"<",
"0",
"and",
"ascending",
":",
"freq",
"=",
"freq",
"*",
"-",
"1",
"attribs",
"[",
"'freq'",
"]",
"=",
"freq",
"if",
"not",
"ascending",
":",
"sorted_values",
"=",
"sorted_values",
"[",
":",
":",
"-",
"1",
"]",
"return",
"self",
".",
"_simple_new",
"(",
"sorted_values",
",",
"*",
"*",
"attribs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin.min | Return the minimum value of the Index or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Series.min : Return the minimum value in a Series. | pandas/core/indexes/datetimelike.py | def min(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the minimum value of the Index or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Series.min : Return the minimum value in a Series.
"""
nv.validate_min(args, kwargs)
nv.validate_minmax_axis(axis)
if not len(self):
return self._na_value
i8 = self.asi8
try:
# quick check
if len(i8) and self.is_monotonic:
if i8[0] != iNaT:
return self._box_func(i8[0])
if self.hasnans:
if skipna:
min_stamp = self[~self._isnan].asi8.min()
else:
return self._na_value
else:
min_stamp = i8.min()
return self._box_func(min_stamp)
except ValueError:
return self._na_value | def min(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the minimum value of the Index or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Series.min : Return the minimum value in a Series.
"""
nv.validate_min(args, kwargs)
nv.validate_minmax_axis(axis)
if not len(self):
return self._na_value
i8 = self.asi8
try:
# quick check
if len(i8) and self.is_monotonic:
if i8[0] != iNaT:
return self._box_func(i8[0])
if self.hasnans:
if skipna:
min_stamp = self[~self._isnan].asi8.min()
else:
return self._na_value
else:
min_stamp = i8.min()
return self._box_func(min_stamp)
except ValueError:
return self._na_value | [
"Return",
"the",
"minimum",
"value",
"of",
"the",
"Index",
"or",
"minimum",
"along",
"an",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L315-L347 | [
"def",
"min",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_min",
"(",
"args",
",",
"kwargs",
")",
"nv",
".",
"validate_minmax_axis",
"(",
"axis",
")",
"if",
"not",
"len",
"(",
"self",
")",
":",
"return",
"self",
".",
"_na_value",
"i8",
"=",
"self",
".",
"asi8",
"try",
":",
"# quick check",
"if",
"len",
"(",
"i8",
")",
"and",
"self",
".",
"is_monotonic",
":",
"if",
"i8",
"[",
"0",
"]",
"!=",
"iNaT",
":",
"return",
"self",
".",
"_box_func",
"(",
"i8",
"[",
"0",
"]",
")",
"if",
"self",
".",
"hasnans",
":",
"if",
"skipna",
":",
"min_stamp",
"=",
"self",
"[",
"~",
"self",
".",
"_isnan",
"]",
".",
"asi8",
".",
"min",
"(",
")",
"else",
":",
"return",
"self",
".",
"_na_value",
"else",
":",
"min_stamp",
"=",
"i8",
".",
"min",
"(",
")",
"return",
"self",
".",
"_box_func",
"(",
"min_stamp",
")",
"except",
"ValueError",
":",
"return",
"self",
".",
"_na_value"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin.argmin | Returns the indices of the minimum values along an axis.
See `numpy.ndarray.argmin` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmin | pandas/core/indexes/datetimelike.py | def argmin(self, axis=None, skipna=True, *args, **kwargs):
"""
Returns the indices of the minimum values along an axis.
See `numpy.ndarray.argmin` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmin
"""
nv.validate_argmin(args, kwargs)
nv.validate_minmax_axis(axis)
i8 = self.asi8
if self.hasnans:
mask = self._isnan
if mask.all() or not skipna:
return -1
i8 = i8.copy()
i8[mask] = np.iinfo('int64').max
return i8.argmin() | def argmin(self, axis=None, skipna=True, *args, **kwargs):
"""
Returns the indices of the minimum values along an axis.
See `numpy.ndarray.argmin` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmin
"""
nv.validate_argmin(args, kwargs)
nv.validate_minmax_axis(axis)
i8 = self.asi8
if self.hasnans:
mask = self._isnan
if mask.all() or not skipna:
return -1
i8 = i8.copy()
i8[mask] = np.iinfo('int64').max
return i8.argmin() | [
"Returns",
"the",
"indices",
"of",
"the",
"minimum",
"values",
"along",
"an",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L349-L370 | [
"def",
"argmin",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_argmin",
"(",
"args",
",",
"kwargs",
")",
"nv",
".",
"validate_minmax_axis",
"(",
"axis",
")",
"i8",
"=",
"self",
".",
"asi8",
"if",
"self",
".",
"hasnans",
":",
"mask",
"=",
"self",
".",
"_isnan",
"if",
"mask",
".",
"all",
"(",
")",
"or",
"not",
"skipna",
":",
"return",
"-",
"1",
"i8",
"=",
"i8",
".",
"copy",
"(",
")",
"i8",
"[",
"mask",
"]",
"=",
"np",
".",
"iinfo",
"(",
"'int64'",
")",
".",
"max",
"return",
"i8",
".",
"argmin",
"(",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin.max | Return the maximum value of the Index or maximum along
an axis.
See Also
--------
numpy.ndarray.max
Series.max : Return the maximum value in a Series. | pandas/core/indexes/datetimelike.py | def max(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the maximum value of the Index or maximum along
an axis.
See Also
--------
numpy.ndarray.max
Series.max : Return the maximum value in a Series.
"""
nv.validate_max(args, kwargs)
nv.validate_minmax_axis(axis)
if not len(self):
return self._na_value
i8 = self.asi8
try:
# quick check
if len(i8) and self.is_monotonic:
if i8[-1] != iNaT:
return self._box_func(i8[-1])
if self.hasnans:
if skipna:
max_stamp = self[~self._isnan].asi8.max()
else:
return self._na_value
else:
max_stamp = i8.max()
return self._box_func(max_stamp)
except ValueError:
return self._na_value | def max(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the maximum value of the Index or maximum along
an axis.
See Also
--------
numpy.ndarray.max
Series.max : Return the maximum value in a Series.
"""
nv.validate_max(args, kwargs)
nv.validate_minmax_axis(axis)
if not len(self):
return self._na_value
i8 = self.asi8
try:
# quick check
if len(i8) and self.is_monotonic:
if i8[-1] != iNaT:
return self._box_func(i8[-1])
if self.hasnans:
if skipna:
max_stamp = self[~self._isnan].asi8.max()
else:
return self._na_value
else:
max_stamp = i8.max()
return self._box_func(max_stamp)
except ValueError:
return self._na_value | [
"Return",
"the",
"maximum",
"value",
"of",
"the",
"Index",
"or",
"maximum",
"along",
"an",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L372-L404 | [
"def",
"max",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_max",
"(",
"args",
",",
"kwargs",
")",
"nv",
".",
"validate_minmax_axis",
"(",
"axis",
")",
"if",
"not",
"len",
"(",
"self",
")",
":",
"return",
"self",
".",
"_na_value",
"i8",
"=",
"self",
".",
"asi8",
"try",
":",
"# quick check",
"if",
"len",
"(",
"i8",
")",
"and",
"self",
".",
"is_monotonic",
":",
"if",
"i8",
"[",
"-",
"1",
"]",
"!=",
"iNaT",
":",
"return",
"self",
".",
"_box_func",
"(",
"i8",
"[",
"-",
"1",
"]",
")",
"if",
"self",
".",
"hasnans",
":",
"if",
"skipna",
":",
"max_stamp",
"=",
"self",
"[",
"~",
"self",
".",
"_isnan",
"]",
".",
"asi8",
".",
"max",
"(",
")",
"else",
":",
"return",
"self",
".",
"_na_value",
"else",
":",
"max_stamp",
"=",
"i8",
".",
"max",
"(",
")",
"return",
"self",
".",
"_box_func",
"(",
"max_stamp",
")",
"except",
"ValueError",
":",
"return",
"self",
".",
"_na_value"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin.argmax | Returns the indices of the maximum values along an axis.
See `numpy.ndarray.argmax` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmax | pandas/core/indexes/datetimelike.py | def argmax(self, axis=None, skipna=True, *args, **kwargs):
"""
Returns the indices of the maximum values along an axis.
See `numpy.ndarray.argmax` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmax
"""
nv.validate_argmax(args, kwargs)
nv.validate_minmax_axis(axis)
i8 = self.asi8
if self.hasnans:
mask = self._isnan
if mask.all() or not skipna:
return -1
i8 = i8.copy()
i8[mask] = 0
return i8.argmax() | def argmax(self, axis=None, skipna=True, *args, **kwargs):
"""
Returns the indices of the maximum values along an axis.
See `numpy.ndarray.argmax` for more information on the
`axis` parameter.
See Also
--------
numpy.ndarray.argmax
"""
nv.validate_argmax(args, kwargs)
nv.validate_minmax_axis(axis)
i8 = self.asi8
if self.hasnans:
mask = self._isnan
if mask.all() or not skipna:
return -1
i8 = i8.copy()
i8[mask] = 0
return i8.argmax() | [
"Returns",
"the",
"indices",
"of",
"the",
"maximum",
"values",
"along",
"an",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L406-L427 | [
"def",
"argmax",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_argmax",
"(",
"args",
",",
"kwargs",
")",
"nv",
".",
"validate_minmax_axis",
"(",
"axis",
")",
"i8",
"=",
"self",
".",
"asi8",
"if",
"self",
".",
"hasnans",
":",
"mask",
"=",
"self",
".",
"_isnan",
"if",
"mask",
".",
"all",
"(",
")",
"or",
"not",
"skipna",
":",
"return",
"-",
"1",
"i8",
"=",
"i8",
".",
"copy",
"(",
")",
"i8",
"[",
"mask",
"]",
"=",
"0",
"return",
"i8",
".",
"argmax",
"(",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin._format_attrs | Return a list of tuples of the (attr,formatted_value). | pandas/core/indexes/datetimelike.py | def _format_attrs(self):
"""
Return a list of tuples of the (attr,formatted_value).
"""
attrs = super()._format_attrs()
for attrib in self._attributes:
if attrib == 'freq':
freq = self.freqstr
if freq is not None:
freq = "'%s'" % freq
attrs.append(('freq', freq))
return attrs | def _format_attrs(self):
"""
Return a list of tuples of the (attr,formatted_value).
"""
attrs = super()._format_attrs()
for attrib in self._attributes:
if attrib == 'freq':
freq = self.freqstr
if freq is not None:
freq = "'%s'" % freq
attrs.append(('freq', freq))
return attrs | [
"Return",
"a",
"list",
"of",
"tuples",
"of",
"the",
"(",
"attr",
"formatted_value",
")",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L439-L450 | [
"def",
"_format_attrs",
"(",
"self",
")",
":",
"attrs",
"=",
"super",
"(",
")",
".",
"_format_attrs",
"(",
")",
"for",
"attrib",
"in",
"self",
".",
"_attributes",
":",
"if",
"attrib",
"==",
"'freq'",
":",
"freq",
"=",
"self",
".",
"freqstr",
"if",
"freq",
"is",
"not",
"None",
":",
"freq",
"=",
"\"'%s'\"",
"%",
"freq",
"attrs",
".",
"append",
"(",
"(",
"'freq'",
",",
"freq",
")",
")",
"return",
"attrs"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin._convert_scalar_indexer | We don't allow integer or float indexing on datetime-like when using
loc.
Parameters
----------
key : label of the slice bound
kind : {'ix', 'loc', 'getitem', 'iloc'} or None | pandas/core/indexes/datetimelike.py | def _convert_scalar_indexer(self, key, kind=None):
"""
We don't allow integer or float indexing on datetime-like when using
loc.
Parameters
----------
key : label of the slice bound
kind : {'ix', 'loc', 'getitem', 'iloc'} or None
"""
assert kind in ['ix', 'loc', 'getitem', 'iloc', None]
# we don't allow integer/float indexing for loc
# we don't allow float indexing for ix/getitem
if is_scalar(key):
is_int = is_integer(key)
is_flt = is_float(key)
if kind in ['loc'] and (is_int or is_flt):
self._invalid_indexer('index', key)
elif kind in ['ix', 'getitem'] and is_flt:
self._invalid_indexer('index', key)
return super()._convert_scalar_indexer(key, kind=kind) | def _convert_scalar_indexer(self, key, kind=None):
"""
We don't allow integer or float indexing on datetime-like when using
loc.
Parameters
----------
key : label of the slice bound
kind : {'ix', 'loc', 'getitem', 'iloc'} or None
"""
assert kind in ['ix', 'loc', 'getitem', 'iloc', None]
# we don't allow integer/float indexing for loc
# we don't allow float indexing for ix/getitem
if is_scalar(key):
is_int = is_integer(key)
is_flt = is_float(key)
if kind in ['loc'] and (is_int or is_flt):
self._invalid_indexer('index', key)
elif kind in ['ix', 'getitem'] and is_flt:
self._invalid_indexer('index', key)
return super()._convert_scalar_indexer(key, kind=kind) | [
"We",
"don",
"t",
"allow",
"integer",
"or",
"float",
"indexing",
"on",
"datetime",
"-",
"like",
"when",
"using",
"loc",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L454-L477 | [
"def",
"_convert_scalar_indexer",
"(",
"self",
",",
"key",
",",
"kind",
"=",
"None",
")",
":",
"assert",
"kind",
"in",
"[",
"'ix'",
",",
"'loc'",
",",
"'getitem'",
",",
"'iloc'",
",",
"None",
"]",
"# we don't allow integer/float indexing for loc",
"# we don't allow float indexing for ix/getitem",
"if",
"is_scalar",
"(",
"key",
")",
":",
"is_int",
"=",
"is_integer",
"(",
"key",
")",
"is_flt",
"=",
"is_float",
"(",
"key",
")",
"if",
"kind",
"in",
"[",
"'loc'",
"]",
"and",
"(",
"is_int",
"or",
"is_flt",
")",
":",
"self",
".",
"_invalid_indexer",
"(",
"'index'",
",",
"key",
")",
"elif",
"kind",
"in",
"[",
"'ix'",
",",
"'getitem'",
"]",
"and",
"is_flt",
":",
"self",
".",
"_invalid_indexer",
"(",
"'index'",
",",
"key",
")",
"return",
"super",
"(",
")",
".",
"_convert_scalar_indexer",
"(",
"key",
",",
"kind",
"=",
"kind",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin._add_datetimelike_methods | Add in the datetimelike methods (as we may have to override the
superclass). | pandas/core/indexes/datetimelike.py | def _add_datetimelike_methods(cls):
"""
Add in the datetimelike methods (as we may have to override the
superclass).
"""
def __add__(self, other):
# dispatch to ExtensionArray implementation
result = self._data.__add__(maybe_unwrap_index(other))
return wrap_arithmetic_op(self, other, result)
cls.__add__ = __add__
def __radd__(self, other):
# alias for __add__
return self.__add__(other)
cls.__radd__ = __radd__
def __sub__(self, other):
# dispatch to ExtensionArray implementation
result = self._data.__sub__(maybe_unwrap_index(other))
return wrap_arithmetic_op(self, other, result)
cls.__sub__ = __sub__
def __rsub__(self, other):
result = self._data.__rsub__(maybe_unwrap_index(other))
return wrap_arithmetic_op(self, other, result)
cls.__rsub__ = __rsub__ | def _add_datetimelike_methods(cls):
"""
Add in the datetimelike methods (as we may have to override the
superclass).
"""
def __add__(self, other):
# dispatch to ExtensionArray implementation
result = self._data.__add__(maybe_unwrap_index(other))
return wrap_arithmetic_op(self, other, result)
cls.__add__ = __add__
def __radd__(self, other):
# alias for __add__
return self.__add__(other)
cls.__radd__ = __radd__
def __sub__(self, other):
# dispatch to ExtensionArray implementation
result = self._data.__sub__(maybe_unwrap_index(other))
return wrap_arithmetic_op(self, other, result)
cls.__sub__ = __sub__
def __rsub__(self, other):
result = self._data.__rsub__(maybe_unwrap_index(other))
return wrap_arithmetic_op(self, other, result)
cls.__rsub__ = __rsub__ | [
"Add",
"in",
"the",
"datetimelike",
"methods",
"(",
"as",
"we",
"may",
"have",
"to",
"override",
"the",
"superclass",
")",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L480-L509 | [
"def",
"_add_datetimelike_methods",
"(",
"cls",
")",
":",
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"# dispatch to ExtensionArray implementation",
"result",
"=",
"self",
".",
"_data",
".",
"__add__",
"(",
"maybe_unwrap_index",
"(",
"other",
")",
")",
"return",
"wrap_arithmetic_op",
"(",
"self",
",",
"other",
",",
"result",
")",
"cls",
".",
"__add__",
"=",
"__add__",
"def",
"__radd__",
"(",
"self",
",",
"other",
")",
":",
"# alias for __add__",
"return",
"self",
".",
"__add__",
"(",
"other",
")",
"cls",
".",
"__radd__",
"=",
"__radd__",
"def",
"__sub__",
"(",
"self",
",",
"other",
")",
":",
"# dispatch to ExtensionArray implementation",
"result",
"=",
"self",
".",
"_data",
".",
"__sub__",
"(",
"maybe_unwrap_index",
"(",
"other",
")",
")",
"return",
"wrap_arithmetic_op",
"(",
"self",
",",
"other",
",",
"result",
")",
"cls",
".",
"__sub__",
"=",
"__sub__",
"def",
"__rsub__",
"(",
"self",
",",
"other",
")",
":",
"result",
"=",
"self",
".",
"_data",
".",
"__rsub__",
"(",
"maybe_unwrap_index",
"(",
"other",
")",
")",
"return",
"wrap_arithmetic_op",
"(",
"self",
",",
"other",
",",
"result",
")",
"cls",
".",
"__rsub__",
"=",
"__rsub__"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin.isin | Compute boolean array of whether each index value is found in the
passed set of values.
Parameters
----------
values : set or sequence of values
Returns
-------
is_contained : ndarray (boolean dtype) | pandas/core/indexes/datetimelike.py | def isin(self, values):
"""
Compute boolean array of whether each index value is found in the
passed set of values.
Parameters
----------
values : set or sequence of values
Returns
-------
is_contained : ndarray (boolean dtype)
"""
if not isinstance(values, type(self)):
try:
values = type(self)(values)
except ValueError:
return self.astype(object).isin(values)
return algorithms.isin(self.asi8, values.asi8) | def isin(self, values):
"""
Compute boolean array of whether each index value is found in the
passed set of values.
Parameters
----------
values : set or sequence of values
Returns
-------
is_contained : ndarray (boolean dtype)
"""
if not isinstance(values, type(self)):
try:
values = type(self)(values)
except ValueError:
return self.astype(object).isin(values)
return algorithms.isin(self.asi8, values.asi8) | [
"Compute",
"boolean",
"array",
"of",
"whether",
"each",
"index",
"value",
"is",
"found",
"in",
"the",
"passed",
"set",
"of",
"values",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L511-L530 | [
"def",
"isin",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"type",
"(",
"self",
")",
")",
":",
"try",
":",
"values",
"=",
"type",
"(",
"self",
")",
"(",
"values",
")",
"except",
"ValueError",
":",
"return",
"self",
".",
"astype",
"(",
"object",
")",
".",
"isin",
"(",
"values",
")",
"return",
"algorithms",
".",
"isin",
"(",
"self",
".",
"asi8",
",",
"values",
".",
"asi8",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin._summary | Return a summarized representation.
Parameters
----------
name : str
name to use in the summary representation
Returns
-------
String with a summarized representation of the index | pandas/core/indexes/datetimelike.py | def _summary(self, name=None):
"""
Return a summarized representation.
Parameters
----------
name : str
name to use in the summary representation
Returns
-------
String with a summarized representation of the index
"""
formatter = self._formatter_func
if len(self) > 0:
index_summary = ', %s to %s' % (formatter(self[0]),
formatter(self[-1]))
else:
index_summary = ''
if name is None:
name = type(self).__name__
result = '%s: %s entries%s' % (printing.pprint_thing(name),
len(self), index_summary)
if self.freq:
result += '\nFreq: %s' % self.freqstr
# display as values, not quoted
result = result.replace("'", "")
return result | def _summary(self, name=None):
"""
Return a summarized representation.
Parameters
----------
name : str
name to use in the summary representation
Returns
-------
String with a summarized representation of the index
"""
formatter = self._formatter_func
if len(self) > 0:
index_summary = ', %s to %s' % (formatter(self[0]),
formatter(self[-1]))
else:
index_summary = ''
if name is None:
name = type(self).__name__
result = '%s: %s entries%s' % (printing.pprint_thing(name),
len(self), index_summary)
if self.freq:
result += '\nFreq: %s' % self.freqstr
# display as values, not quoted
result = result.replace("'", "")
return result | [
"Return",
"a",
"summarized",
"representation",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L547-L576 | [
"def",
"_summary",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"formatter",
"=",
"self",
".",
"_formatter_func",
"if",
"len",
"(",
"self",
")",
">",
"0",
":",
"index_summary",
"=",
"', %s to %s'",
"%",
"(",
"formatter",
"(",
"self",
"[",
"0",
"]",
")",
",",
"formatter",
"(",
"self",
"[",
"-",
"1",
"]",
")",
")",
"else",
":",
"index_summary",
"=",
"''",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
"result",
"=",
"'%s: %s entries%s'",
"%",
"(",
"printing",
".",
"pprint_thing",
"(",
"name",
")",
",",
"len",
"(",
"self",
")",
",",
"index_summary",
")",
"if",
"self",
".",
"freq",
":",
"result",
"+=",
"'\\nFreq: %s'",
"%",
"self",
".",
"freqstr",
"# display as values, not quoted",
"result",
"=",
"result",
".",
"replace",
"(",
"\"'\"",
",",
"\"\"",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin._concat_same_dtype | Concatenate to_concat which has the same class. | pandas/core/indexes/datetimelike.py | def _concat_same_dtype(self, to_concat, name):
"""
Concatenate to_concat which has the same class.
"""
attribs = self._get_attributes_dict()
attribs['name'] = name
# do not pass tz to set because tzlocal cannot be hashed
if len({str(x.dtype) for x in to_concat}) != 1:
raise ValueError('to_concat must have the same tz')
new_data = type(self._values)._concat_same_type(to_concat).asi8
# GH 3232: If the concat result is evenly spaced, we can retain the
# original frequency
is_diff_evenly_spaced = len(unique_deltas(new_data)) == 1
if not is_period_dtype(self) and not is_diff_evenly_spaced:
# reset freq
attribs['freq'] = None
return self._simple_new(new_data, **attribs) | def _concat_same_dtype(self, to_concat, name):
"""
Concatenate to_concat which has the same class.
"""
attribs = self._get_attributes_dict()
attribs['name'] = name
# do not pass tz to set because tzlocal cannot be hashed
if len({str(x.dtype) for x in to_concat}) != 1:
raise ValueError('to_concat must have the same tz')
new_data = type(self._values)._concat_same_type(to_concat).asi8
# GH 3232: If the concat result is evenly spaced, we can retain the
# original frequency
is_diff_evenly_spaced = len(unique_deltas(new_data)) == 1
if not is_period_dtype(self) and not is_diff_evenly_spaced:
# reset freq
attribs['freq'] = None
return self._simple_new(new_data, **attribs) | [
"Concatenate",
"to_concat",
"which",
"has",
"the",
"same",
"class",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L578-L597 | [
"def",
"_concat_same_dtype",
"(",
"self",
",",
"to_concat",
",",
"name",
")",
":",
"attribs",
"=",
"self",
".",
"_get_attributes_dict",
"(",
")",
"attribs",
"[",
"'name'",
"]",
"=",
"name",
"# do not pass tz to set because tzlocal cannot be hashed",
"if",
"len",
"(",
"{",
"str",
"(",
"x",
".",
"dtype",
")",
"for",
"x",
"in",
"to_concat",
"}",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'to_concat must have the same tz'",
")",
"new_data",
"=",
"type",
"(",
"self",
".",
"_values",
")",
".",
"_concat_same_type",
"(",
"to_concat",
")",
".",
"asi8",
"# GH 3232: If the concat result is evenly spaced, we can retain the",
"# original frequency",
"is_diff_evenly_spaced",
"=",
"len",
"(",
"unique_deltas",
"(",
"new_data",
")",
")",
"==",
"1",
"if",
"not",
"is_period_dtype",
"(",
"self",
")",
"and",
"not",
"is_diff_evenly_spaced",
":",
"# reset freq",
"attribs",
"[",
"'freq'",
"]",
"=",
"None",
"return",
"self",
".",
"_simple_new",
"(",
"new_data",
",",
"*",
"*",
"attribs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | DatetimeIndexOpsMixin.shift | Shift index by desired number of time frequency increments.
This method is for shifting the values of datetime-like indexes
by a specified time increment a given number of times.
Parameters
----------
periods : int
Number of periods (or increments) to shift by,
can be positive or negative.
.. versionchanged:: 0.24.0
freq : pandas.DateOffset, pandas.Timedelta or string, optional
Frequency increment to shift by.
If None, the index is shifted by its own `freq` attribute.
Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc.
Returns
-------
pandas.DatetimeIndex
Shifted index.
See Also
--------
Index.shift : Shift values of Index.
PeriodIndex.shift : Shift values of PeriodIndex. | pandas/core/indexes/datetimelike.py | def shift(self, periods, freq=None):
"""
Shift index by desired number of time frequency increments.
This method is for shifting the values of datetime-like indexes
by a specified time increment a given number of times.
Parameters
----------
periods : int
Number of periods (or increments) to shift by,
can be positive or negative.
.. versionchanged:: 0.24.0
freq : pandas.DateOffset, pandas.Timedelta or string, optional
Frequency increment to shift by.
If None, the index is shifted by its own `freq` attribute.
Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc.
Returns
-------
pandas.DatetimeIndex
Shifted index.
See Also
--------
Index.shift : Shift values of Index.
PeriodIndex.shift : Shift values of PeriodIndex.
"""
result = self._data._time_shift(periods, freq=freq)
return type(self)(result, name=self.name) | def shift(self, periods, freq=None):
"""
Shift index by desired number of time frequency increments.
This method is for shifting the values of datetime-like indexes
by a specified time increment a given number of times.
Parameters
----------
periods : int
Number of periods (or increments) to shift by,
can be positive or negative.
.. versionchanged:: 0.24.0
freq : pandas.DateOffset, pandas.Timedelta or string, optional
Frequency increment to shift by.
If None, the index is shifted by its own `freq` attribute.
Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc.
Returns
-------
pandas.DatetimeIndex
Shifted index.
See Also
--------
Index.shift : Shift values of Index.
PeriodIndex.shift : Shift values of PeriodIndex.
"""
result = self._data._time_shift(periods, freq=freq)
return type(self)(result, name=self.name) | [
"Shift",
"index",
"by",
"desired",
"number",
"of",
"time",
"frequency",
"increments",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/datetimelike.py#L613-L644 | [
"def",
"shift",
"(",
"self",
",",
"periods",
",",
"freq",
"=",
"None",
")",
":",
"result",
"=",
"self",
".",
"_data",
".",
"_time_shift",
"(",
"periods",
",",
"freq",
"=",
"freq",
")",
"return",
"type",
"(",
"self",
")",
"(",
"result",
",",
"name",
"=",
"self",
".",
"name",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _single_replace | Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method | pandas/core/generic.py | def _single_replace(self, to_replace, method, inplace, limit):
"""
Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method
"""
if self.ndim != 1:
raise TypeError('cannot replace {0} with method {1} on a {2}'
.format(to_replace, method, type(self).__name__))
orig_dtype = self.dtype
result = self if inplace else self.copy()
fill_f = missing.get_fill_func(method)
mask = missing.mask_missing(result.values, to_replace)
values = fill_f(result.values, limit=limit, mask=mask)
if values.dtype == orig_dtype and inplace:
return
result = pd.Series(values, index=self.index,
dtype=self.dtype).__finalize__(self)
if inplace:
self._update_inplace(result._data)
return
return result | def _single_replace(self, to_replace, method, inplace, limit):
"""
Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method
"""
if self.ndim != 1:
raise TypeError('cannot replace {0} with method {1} on a {2}'
.format(to_replace, method, type(self).__name__))
orig_dtype = self.dtype
result = self if inplace else self.copy()
fill_f = missing.get_fill_func(method)
mask = missing.mask_missing(result.values, to_replace)
values = fill_f(result.values, limit=limit, mask=mask)
if values.dtype == orig_dtype and inplace:
return
result = pd.Series(values, index=self.index,
dtype=self.dtype).__finalize__(self)
if inplace:
self._update_inplace(result._data)
return
return result | [
"Replaces",
"values",
"in",
"a",
"Series",
"using",
"the",
"fill",
"method",
"specified",
"when",
"no",
"replacement",
"value",
"is",
"given",
"in",
"the",
"replace",
"method"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L69-L95 | [
"def",
"_single_replace",
"(",
"self",
",",
"to_replace",
",",
"method",
",",
"inplace",
",",
"limit",
")",
":",
"if",
"self",
".",
"ndim",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"'cannot replace {0} with method {1} on a {2}'",
".",
"format",
"(",
"to_replace",
",",
"method",
",",
"type",
"(",
"self",
")",
".",
"__name__",
")",
")",
"orig_dtype",
"=",
"self",
".",
"dtype",
"result",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
")",
"fill_f",
"=",
"missing",
".",
"get_fill_func",
"(",
"method",
")",
"mask",
"=",
"missing",
".",
"mask_missing",
"(",
"result",
".",
"values",
",",
"to_replace",
")",
"values",
"=",
"fill_f",
"(",
"result",
".",
"values",
",",
"limit",
"=",
"limit",
",",
"mask",
"=",
"mask",
")",
"if",
"values",
".",
"dtype",
"==",
"orig_dtype",
"and",
"inplace",
":",
"return",
"result",
"=",
"pd",
".",
"Series",
"(",
"values",
",",
"index",
"=",
"self",
".",
"index",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
".",
"__finalize__",
"(",
"self",
")",
"if",
"inplace",
":",
"self",
".",
"_update_inplace",
"(",
"result",
".",
"_data",
")",
"return",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | _doc_parms | Return a tuple of the doc parms. | pandas/core/generic.py | def _doc_parms(cls):
"""Return a tuple of the doc parms."""
axis_descr = "{%s}" % ', '.join("{0} ({1})".format(a, i)
for i, a in enumerate(cls._AXIS_ORDERS))
name = (cls._constructor_sliced.__name__
if cls._AXIS_LEN > 1 else 'scalar')
name2 = cls.__name__
return axis_descr, name, name2 | def _doc_parms(cls):
"""Return a tuple of the doc parms."""
axis_descr = "{%s}" % ', '.join("{0} ({1})".format(a, i)
for i, a in enumerate(cls._AXIS_ORDERS))
name = (cls._constructor_sliced.__name__
if cls._AXIS_LEN > 1 else 'scalar')
name2 = cls.__name__
return axis_descr, name, name2 | [
"Return",
"a",
"tuple",
"of",
"the",
"doc",
"parms",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L10299-L10306 | [
"def",
"_doc_parms",
"(",
"cls",
")",
":",
"axis_descr",
"=",
"\"{%s}\"",
"%",
"', '",
".",
"join",
"(",
"\"{0} ({1})\"",
".",
"format",
"(",
"a",
",",
"i",
")",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"cls",
".",
"_AXIS_ORDERS",
")",
")",
"name",
"=",
"(",
"cls",
".",
"_constructor_sliced",
".",
"__name__",
"if",
"cls",
".",
"_AXIS_LEN",
">",
"1",
"else",
"'scalar'",
")",
"name2",
"=",
"cls",
".",
"__name__",
"return",
"axis_descr",
",",
"name",
",",
"name2"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._init_mgr | passed a manager and a axes dict | pandas/core/generic.py | def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
""" passed a manager and a axes dict """
for a, axe in axes.items():
if axe is not None:
mgr = mgr.reindex_axis(axe,
axis=self._get_block_manager_axis(a),
copy=False)
# make a copy if explicitly requested
if copy:
mgr = mgr.copy()
if dtype is not None:
# avoid further copies if we can
if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype:
mgr = mgr.astype(dtype=dtype)
return mgr | def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
""" passed a manager and a axes dict """
for a, axe in axes.items():
if axe is not None:
mgr = mgr.reindex_axis(axe,
axis=self._get_block_manager_axis(a),
copy=False)
# make a copy if explicitly requested
if copy:
mgr = mgr.copy()
if dtype is not None:
# avoid further copies if we can
if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype:
mgr = mgr.astype(dtype=dtype)
return mgr | [
"passed",
"a",
"manager",
"and",
"a",
"axes",
"dict"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L141-L156 | [
"def",
"_init_mgr",
"(",
"self",
",",
"mgr",
",",
"axes",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"for",
"a",
",",
"axe",
"in",
"axes",
".",
"items",
"(",
")",
":",
"if",
"axe",
"is",
"not",
"None",
":",
"mgr",
"=",
"mgr",
".",
"reindex_axis",
"(",
"axe",
",",
"axis",
"=",
"self",
".",
"_get_block_manager_axis",
"(",
"a",
")",
",",
"copy",
"=",
"False",
")",
"# make a copy if explicitly requested",
"if",
"copy",
":",
"mgr",
"=",
"mgr",
".",
"copy",
"(",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"# avoid further copies if we can",
"if",
"len",
"(",
"mgr",
".",
"blocks",
")",
">",
"1",
"or",
"mgr",
".",
"blocks",
"[",
"0",
"]",
".",
"values",
".",
"dtype",
"!=",
"dtype",
":",
"mgr",
"=",
"mgr",
".",
"astype",
"(",
"dtype",
"=",
"dtype",
")",
"return",
"mgr"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._validate_dtype | validate the passed dtype | pandas/core/generic.py | def _validate_dtype(self, dtype):
""" validate the passed dtype """
if dtype is not None:
dtype = pandas_dtype(dtype)
# a compound dtype
if dtype.kind == 'V':
raise NotImplementedError("compound dtypes are not implemented"
" in the {0} constructor"
.format(self.__class__.__name__))
return dtype | def _validate_dtype(self, dtype):
""" validate the passed dtype """
if dtype is not None:
dtype = pandas_dtype(dtype)
# a compound dtype
if dtype.kind == 'V':
raise NotImplementedError("compound dtypes are not implemented"
" in the {0} constructor"
.format(self.__class__.__name__))
return dtype | [
"validate",
"the",
"passed",
"dtype"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L175-L187 | [
"def",
"_validate_dtype",
"(",
"self",
",",
"dtype",
")",
":",
"if",
"dtype",
"is",
"not",
"None",
":",
"dtype",
"=",
"pandas_dtype",
"(",
"dtype",
")",
"# a compound dtype",
"if",
"dtype",
".",
"kind",
"==",
"'V'",
":",
"raise",
"NotImplementedError",
"(",
"\"compound dtypes are not implemented\"",
"\" in the {0} constructor\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"return",
"dtype"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._setup_axes | Provide axes setup for the major PandasObjects.
Parameters
----------
axes : the names of the axes in order (lowest to highest)
info_axis_num : the axis of the selector dimension (int)
stat_axis_num : the number of axis for the default stats (int)
aliases : other names for a single axis (dict)
slicers : how axes slice to others (dict)
axes_are_reversed : boolean whether to treat passed axes as
reversed (DataFrame)
build_axes : setup the axis properties (default True) | pandas/core/generic.py | def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None,
slicers=None, axes_are_reversed=False, build_axes=True,
ns=None, docs=None):
"""Provide axes setup for the major PandasObjects.
Parameters
----------
axes : the names of the axes in order (lowest to highest)
info_axis_num : the axis of the selector dimension (int)
stat_axis_num : the number of axis for the default stats (int)
aliases : other names for a single axis (dict)
slicers : how axes slice to others (dict)
axes_are_reversed : boolean whether to treat passed axes as
reversed (DataFrame)
build_axes : setup the axis properties (default True)
"""
cls._AXIS_ORDERS = axes
cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)}
cls._AXIS_LEN = len(axes)
cls._AXIS_ALIASES = aliases or dict()
cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()}
cls._AXIS_NAMES = dict(enumerate(axes))
cls._AXIS_SLICEMAP = slicers or None
cls._AXIS_REVERSED = axes_are_reversed
# typ
setattr(cls, '_typ', cls.__name__.lower())
# indexing support
cls._ix = None
if info_axis is not None:
cls._info_axis_number = info_axis
cls._info_axis_name = axes[info_axis]
if stat_axis is not None:
cls._stat_axis_number = stat_axis
cls._stat_axis_name = axes[stat_axis]
# setup the actual axis
if build_axes:
def set_axis(a, i):
setattr(cls, a, properties.AxisProperty(i, docs.get(a, a)))
cls._internal_names_set.add(a)
if axes_are_reversed:
m = cls._AXIS_LEN - 1
for i, a in cls._AXIS_NAMES.items():
set_axis(a, m - i)
else:
for i, a in cls._AXIS_NAMES.items():
set_axis(a, i)
assert not isinstance(ns, dict) | def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None,
slicers=None, axes_are_reversed=False, build_axes=True,
ns=None, docs=None):
"""Provide axes setup for the major PandasObjects.
Parameters
----------
axes : the names of the axes in order (lowest to highest)
info_axis_num : the axis of the selector dimension (int)
stat_axis_num : the number of axis for the default stats (int)
aliases : other names for a single axis (dict)
slicers : how axes slice to others (dict)
axes_are_reversed : boolean whether to treat passed axes as
reversed (DataFrame)
build_axes : setup the axis properties (default True)
"""
cls._AXIS_ORDERS = axes
cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)}
cls._AXIS_LEN = len(axes)
cls._AXIS_ALIASES = aliases or dict()
cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()}
cls._AXIS_NAMES = dict(enumerate(axes))
cls._AXIS_SLICEMAP = slicers or None
cls._AXIS_REVERSED = axes_are_reversed
# typ
setattr(cls, '_typ', cls.__name__.lower())
# indexing support
cls._ix = None
if info_axis is not None:
cls._info_axis_number = info_axis
cls._info_axis_name = axes[info_axis]
if stat_axis is not None:
cls._stat_axis_number = stat_axis
cls._stat_axis_name = axes[stat_axis]
# setup the actual axis
if build_axes:
def set_axis(a, i):
setattr(cls, a, properties.AxisProperty(i, docs.get(a, a)))
cls._internal_names_set.add(a)
if axes_are_reversed:
m = cls._AXIS_LEN - 1
for i, a in cls._AXIS_NAMES.items():
set_axis(a, m - i)
else:
for i, a in cls._AXIS_NAMES.items():
set_axis(a, i)
assert not isinstance(ns, dict) | [
"Provide",
"axes",
"setup",
"for",
"the",
"major",
"PandasObjects",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L217-L272 | [
"def",
"_setup_axes",
"(",
"cls",
",",
"axes",
",",
"info_axis",
"=",
"None",
",",
"stat_axis",
"=",
"None",
",",
"aliases",
"=",
"None",
",",
"slicers",
"=",
"None",
",",
"axes_are_reversed",
"=",
"False",
",",
"build_axes",
"=",
"True",
",",
"ns",
"=",
"None",
",",
"docs",
"=",
"None",
")",
":",
"cls",
".",
"_AXIS_ORDERS",
"=",
"axes",
"cls",
".",
"_AXIS_NUMBERS",
"=",
"{",
"a",
":",
"i",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"axes",
")",
"}",
"cls",
".",
"_AXIS_LEN",
"=",
"len",
"(",
"axes",
")",
"cls",
".",
"_AXIS_ALIASES",
"=",
"aliases",
"or",
"dict",
"(",
")",
"cls",
".",
"_AXIS_IALIASES",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"cls",
".",
"_AXIS_ALIASES",
".",
"items",
"(",
")",
"}",
"cls",
".",
"_AXIS_NAMES",
"=",
"dict",
"(",
"enumerate",
"(",
"axes",
")",
")",
"cls",
".",
"_AXIS_SLICEMAP",
"=",
"slicers",
"or",
"None",
"cls",
".",
"_AXIS_REVERSED",
"=",
"axes_are_reversed",
"# typ",
"setattr",
"(",
"cls",
",",
"'_typ'",
",",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
")",
"# indexing support",
"cls",
".",
"_ix",
"=",
"None",
"if",
"info_axis",
"is",
"not",
"None",
":",
"cls",
".",
"_info_axis_number",
"=",
"info_axis",
"cls",
".",
"_info_axis_name",
"=",
"axes",
"[",
"info_axis",
"]",
"if",
"stat_axis",
"is",
"not",
"None",
":",
"cls",
".",
"_stat_axis_number",
"=",
"stat_axis",
"cls",
".",
"_stat_axis_name",
"=",
"axes",
"[",
"stat_axis",
"]",
"# setup the actual axis",
"if",
"build_axes",
":",
"def",
"set_axis",
"(",
"a",
",",
"i",
")",
":",
"setattr",
"(",
"cls",
",",
"a",
",",
"properties",
".",
"AxisProperty",
"(",
"i",
",",
"docs",
".",
"get",
"(",
"a",
",",
"a",
")",
")",
")",
"cls",
".",
"_internal_names_set",
".",
"add",
"(",
"a",
")",
"if",
"axes_are_reversed",
":",
"m",
"=",
"cls",
".",
"_AXIS_LEN",
"-",
"1",
"for",
"i",
",",
"a",
"in",
"cls",
".",
"_AXIS_NAMES",
".",
"items",
"(",
")",
":",
"set_axis",
"(",
"a",
",",
"m",
"-",
"i",
")",
"else",
":",
"for",
"i",
",",
"a",
"in",
"cls",
".",
"_AXIS_NAMES",
".",
"items",
"(",
")",
":",
"set_axis",
"(",
"a",
",",
"i",
")",
"assert",
"not",
"isinstance",
"(",
"ns",
",",
"dict",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._construct_axes_dict | Return an axes dictionary for myself. | pandas/core/generic.py | def _construct_axes_dict(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
d.update(kwargs)
return d | def _construct_axes_dict(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
d.update(kwargs)
return d | [
"Return",
"an",
"axes",
"dictionary",
"for",
"myself",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L274-L278 | [
"def",
"_construct_axes_dict",
"(",
"self",
",",
"axes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"a",
":",
"self",
".",
"_get_axis",
"(",
"a",
")",
"for",
"a",
"in",
"(",
"axes",
"or",
"self",
".",
"_AXIS_ORDERS",
")",
"}",
"d",
".",
"update",
"(",
"kwargs",
")",
"return",
"d"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._construct_axes_dict_from | Return an axes dictionary for the passed axes. | pandas/core/generic.py | def _construct_axes_dict_from(self, axes, **kwargs):
"""Return an axes dictionary for the passed axes."""
d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)}
d.update(kwargs)
return d | def _construct_axes_dict_from(self, axes, **kwargs):
"""Return an axes dictionary for the passed axes."""
d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)}
d.update(kwargs)
return d | [
"Return",
"an",
"axes",
"dictionary",
"for",
"the",
"passed",
"axes",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L281-L285 | [
"def",
"_construct_axes_dict_from",
"(",
"self",
",",
"axes",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"a",
":",
"ax",
"for",
"a",
",",
"ax",
"in",
"zip",
"(",
"self",
".",
"_AXIS_ORDERS",
",",
"axes",
")",
"}",
"d",
".",
"update",
"(",
"kwargs",
")",
"return",
"d"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._construct_axes_dict_for_slice | Return an axes dictionary for myself. | pandas/core/generic.py | def _construct_axes_dict_for_slice(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
d = {self._AXIS_SLICEMAP[a]: self._get_axis(a)
for a in (axes or self._AXIS_ORDERS)}
d.update(kwargs)
return d | def _construct_axes_dict_for_slice(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
d = {self._AXIS_SLICEMAP[a]: self._get_axis(a)
for a in (axes or self._AXIS_ORDERS)}
d.update(kwargs)
return d | [
"Return",
"an",
"axes",
"dictionary",
"for",
"myself",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L287-L292 | [
"def",
"_construct_axes_dict_for_slice",
"(",
"self",
",",
"axes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"self",
".",
"_AXIS_SLICEMAP",
"[",
"a",
"]",
":",
"self",
".",
"_get_axis",
"(",
"a",
")",
"for",
"a",
"in",
"(",
"axes",
"or",
"self",
".",
"_AXIS_ORDERS",
")",
"}",
"d",
".",
"update",
"(",
"kwargs",
")",
"return",
"d"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._construct_axes_from_arguments | Construct and returns axes if supplied in args/kwargs.
If require_all, raise if all axis arguments are not supplied
return a tuple of (axes, kwargs).
sentinel specifies the default parameter when an axis is not
supplied; useful to distinguish when a user explicitly passes None
in scenarios where None has special meaning. | pandas/core/generic.py | def _construct_axes_from_arguments(
self, args, kwargs, require_all=False, sentinel=None):
"""Construct and returns axes if supplied in args/kwargs.
If require_all, raise if all axis arguments are not supplied
return a tuple of (axes, kwargs).
sentinel specifies the default parameter when an axis is not
supplied; useful to distinguish when a user explicitly passes None
in scenarios where None has special meaning.
"""
# construct the args
args = list(args)
for a in self._AXIS_ORDERS:
# if we have an alias for this axis
alias = self._AXIS_IALIASES.get(a)
if alias is not None:
if a in kwargs:
if alias in kwargs:
raise TypeError("arguments are mutually exclusive "
"for [%s,%s]" % (a, alias))
continue
if alias in kwargs:
kwargs[a] = kwargs.pop(alias)
continue
# look for a argument by position
if a not in kwargs:
try:
kwargs[a] = args.pop(0)
except IndexError:
if require_all:
raise TypeError("not enough/duplicate arguments "
"specified!")
axes = {a: kwargs.pop(a, sentinel) for a in self._AXIS_ORDERS}
return axes, kwargs | def _construct_axes_from_arguments(
self, args, kwargs, require_all=False, sentinel=None):
"""Construct and returns axes if supplied in args/kwargs.
If require_all, raise if all axis arguments are not supplied
return a tuple of (axes, kwargs).
sentinel specifies the default parameter when an axis is not
supplied; useful to distinguish when a user explicitly passes None
in scenarios where None has special meaning.
"""
# construct the args
args = list(args)
for a in self._AXIS_ORDERS:
# if we have an alias for this axis
alias = self._AXIS_IALIASES.get(a)
if alias is not None:
if a in kwargs:
if alias in kwargs:
raise TypeError("arguments are mutually exclusive "
"for [%s,%s]" % (a, alias))
continue
if alias in kwargs:
kwargs[a] = kwargs.pop(alias)
continue
# look for a argument by position
if a not in kwargs:
try:
kwargs[a] = args.pop(0)
except IndexError:
if require_all:
raise TypeError("not enough/duplicate arguments "
"specified!")
axes = {a: kwargs.pop(a, sentinel) for a in self._AXIS_ORDERS}
return axes, kwargs | [
"Construct",
"and",
"returns",
"axes",
"if",
"supplied",
"in",
"args",
"/",
"kwargs",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L294-L332 | [
"def",
"_construct_axes_from_arguments",
"(",
"self",
",",
"args",
",",
"kwargs",
",",
"require_all",
"=",
"False",
",",
"sentinel",
"=",
"None",
")",
":",
"# construct the args",
"args",
"=",
"list",
"(",
"args",
")",
"for",
"a",
"in",
"self",
".",
"_AXIS_ORDERS",
":",
"# if we have an alias for this axis",
"alias",
"=",
"self",
".",
"_AXIS_IALIASES",
".",
"get",
"(",
"a",
")",
"if",
"alias",
"is",
"not",
"None",
":",
"if",
"a",
"in",
"kwargs",
":",
"if",
"alias",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"\"arguments are mutually exclusive \"",
"\"for [%s,%s]\"",
"%",
"(",
"a",
",",
"alias",
")",
")",
"continue",
"if",
"alias",
"in",
"kwargs",
":",
"kwargs",
"[",
"a",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"alias",
")",
"continue",
"# look for a argument by position",
"if",
"a",
"not",
"in",
"kwargs",
":",
"try",
":",
"kwargs",
"[",
"a",
"]",
"=",
"args",
".",
"pop",
"(",
"0",
")",
"except",
"IndexError",
":",
"if",
"require_all",
":",
"raise",
"TypeError",
"(",
"\"not enough/duplicate arguments \"",
"\"specified!\"",
")",
"axes",
"=",
"{",
"a",
":",
"kwargs",
".",
"pop",
"(",
"a",
",",
"sentinel",
")",
"for",
"a",
"in",
"self",
".",
"_AXIS_ORDERS",
"}",
"return",
"axes",
",",
"kwargs"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._get_block_manager_axis | Map the axis to the block_manager axis. | pandas/core/generic.py | def _get_block_manager_axis(cls, axis):
"""Map the axis to the block_manager axis."""
axis = cls._get_axis_number(axis)
if cls._AXIS_REVERSED:
m = cls._AXIS_LEN - 1
return m - axis
return axis | def _get_block_manager_axis(cls, axis):
"""Map the axis to the block_manager axis."""
axis = cls._get_axis_number(axis)
if cls._AXIS_REVERSED:
m = cls._AXIS_LEN - 1
return m - axis
return axis | [
"Map",
"the",
"axis",
"to",
"the",
"block_manager",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L379-L385 | [
"def",
"_get_block_manager_axis",
"(",
"cls",
",",
"axis",
")",
":",
"axis",
"=",
"cls",
".",
"_get_axis_number",
"(",
"axis",
")",
"if",
"cls",
".",
"_AXIS_REVERSED",
":",
"m",
"=",
"cls",
".",
"_AXIS_LEN",
"-",
"1",
"return",
"m",
"-",
"axis",
"return",
"axis"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._get_space_character_free_column_resolvers | Return the space character free column resolvers of a dataframe.
Column names with spaces are 'cleaned up' so that they can be referred
to by backtick quoting.
Used in :meth:`DataFrame.eval`. | pandas/core/generic.py | def _get_space_character_free_column_resolvers(self):
"""Return the space character free column resolvers of a dataframe.
Column names with spaces are 'cleaned up' so that they can be referred
to by backtick quoting.
Used in :meth:`DataFrame.eval`.
"""
from pandas.core.computation.common import _remove_spaces_column_name
return {_remove_spaces_column_name(k): v for k, v
in self.iteritems()} | def _get_space_character_free_column_resolvers(self):
"""Return the space character free column resolvers of a dataframe.
Column names with spaces are 'cleaned up' so that they can be referred
to by backtick quoting.
Used in :meth:`DataFrame.eval`.
"""
from pandas.core.computation.common import _remove_spaces_column_name
return {_remove_spaces_column_name(k): v for k, v
in self.iteritems()} | [
"Return",
"the",
"space",
"character",
"free",
"column",
"resolvers",
"of",
"a",
"dataframe",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L423-L433 | [
"def",
"_get_space_character_free_column_resolvers",
"(",
"self",
")",
":",
"from",
"pandas",
".",
"core",
".",
"computation",
".",
"common",
"import",
"_remove_spaces_column_name",
"return",
"{",
"_remove_spaces_column_name",
"(",
"k",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"iteritems",
"(",
")",
"}"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.shape | Return a tuple of axis dimensions | pandas/core/generic.py | def shape(self):
"""
Return a tuple of axis dimensions
"""
return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS) | def shape(self):
"""
Return a tuple of axis dimensions
"""
return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS) | [
"Return",
"a",
"tuple",
"of",
"axis",
"dimensions"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L444-L448 | [
"def",
"shape",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"len",
"(",
"self",
".",
"_get_axis",
"(",
"a",
")",
")",
"for",
"a",
"in",
"self",
".",
"_AXIS_ORDERS",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.transpose | Permute the dimensions of the %(klass)s
Parameters
----------
args : %(args_transpose)s
copy : boolean, default False
Make a copy of the underlying data. Mixed-dtype data will
always result in a copy
**kwargs
Additional keyword arguments will be passed to the function.
Returns
-------
y : same as input
Examples
--------
>>> p.transpose(2, 0, 1)
>>> p.transpose(2, 0, 1, copy=True) | pandas/core/generic.py | def transpose(self, *args, **kwargs):
"""
Permute the dimensions of the %(klass)s
Parameters
----------
args : %(args_transpose)s
copy : boolean, default False
Make a copy of the underlying data. Mixed-dtype data will
always result in a copy
**kwargs
Additional keyword arguments will be passed to the function.
Returns
-------
y : same as input
Examples
--------
>>> p.transpose(2, 0, 1)
>>> p.transpose(2, 0, 1, copy=True)
"""
# construct the args
axes, kwargs = self._construct_axes_from_arguments(args, kwargs,
require_all=True)
axes_names = tuple(self._get_axis_name(axes[a])
for a in self._AXIS_ORDERS)
axes_numbers = tuple(self._get_axis_number(axes[a])
for a in self._AXIS_ORDERS)
# we must have unique axes
if len(axes) != len(set(axes)):
raise ValueError('Must specify %s unique axes' % self._AXIS_LEN)
new_axes = self._construct_axes_dict_from(self, [self._get_axis(x)
for x in axes_names])
new_values = self.values.transpose(axes_numbers)
if kwargs.pop('copy', None) or (len(args) and args[-1]):
new_values = new_values.copy()
nv.validate_transpose_for_generic(self, kwargs)
return self._constructor(new_values, **new_axes).__finalize__(self) | def transpose(self, *args, **kwargs):
"""
Permute the dimensions of the %(klass)s
Parameters
----------
args : %(args_transpose)s
copy : boolean, default False
Make a copy of the underlying data. Mixed-dtype data will
always result in a copy
**kwargs
Additional keyword arguments will be passed to the function.
Returns
-------
y : same as input
Examples
--------
>>> p.transpose(2, 0, 1)
>>> p.transpose(2, 0, 1, copy=True)
"""
# construct the args
axes, kwargs = self._construct_axes_from_arguments(args, kwargs,
require_all=True)
axes_names = tuple(self._get_axis_name(axes[a])
for a in self._AXIS_ORDERS)
axes_numbers = tuple(self._get_axis_number(axes[a])
for a in self._AXIS_ORDERS)
# we must have unique axes
if len(axes) != len(set(axes)):
raise ValueError('Must specify %s unique axes' % self._AXIS_LEN)
new_axes = self._construct_axes_dict_from(self, [self._get_axis(x)
for x in axes_names])
new_values = self.values.transpose(axes_numbers)
if kwargs.pop('copy', None) or (len(args) and args[-1]):
new_values = new_values.copy()
nv.validate_transpose_for_generic(self, kwargs)
return self._constructor(new_values, **new_axes).__finalize__(self) | [
"Permute",
"the",
"dimensions",
"of",
"the",
"%",
"(",
"klass",
")",
"s"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L650-L692 | [
"def",
"transpose",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# construct the args",
"axes",
",",
"kwargs",
"=",
"self",
".",
"_construct_axes_from_arguments",
"(",
"args",
",",
"kwargs",
",",
"require_all",
"=",
"True",
")",
"axes_names",
"=",
"tuple",
"(",
"self",
".",
"_get_axis_name",
"(",
"axes",
"[",
"a",
"]",
")",
"for",
"a",
"in",
"self",
".",
"_AXIS_ORDERS",
")",
"axes_numbers",
"=",
"tuple",
"(",
"self",
".",
"_get_axis_number",
"(",
"axes",
"[",
"a",
"]",
")",
"for",
"a",
"in",
"self",
".",
"_AXIS_ORDERS",
")",
"# we must have unique axes",
"if",
"len",
"(",
"axes",
")",
"!=",
"len",
"(",
"set",
"(",
"axes",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Must specify %s unique axes'",
"%",
"self",
".",
"_AXIS_LEN",
")",
"new_axes",
"=",
"self",
".",
"_construct_axes_dict_from",
"(",
"self",
",",
"[",
"self",
".",
"_get_axis",
"(",
"x",
")",
"for",
"x",
"in",
"axes_names",
"]",
")",
"new_values",
"=",
"self",
".",
"values",
".",
"transpose",
"(",
"axes_numbers",
")",
"if",
"kwargs",
".",
"pop",
"(",
"'copy'",
",",
"None",
")",
"or",
"(",
"len",
"(",
"args",
")",
"and",
"args",
"[",
"-",
"1",
"]",
")",
":",
"new_values",
"=",
"new_values",
".",
"copy",
"(",
")",
"nv",
".",
"validate_transpose_for_generic",
"(",
"self",
",",
"kwargs",
")",
"return",
"self",
".",
"_constructor",
"(",
"new_values",
",",
"*",
"*",
"new_axes",
")",
".",
"__finalize__",
"(",
"self",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.swapaxes | Interchange axes and swap values axes appropriately.
Returns
-------
y : same as input | pandas/core/generic.py | def swapaxes(self, axis1, axis2, copy=True):
"""
Interchange axes and swap values axes appropriately.
Returns
-------
y : same as input
"""
i = self._get_axis_number(axis1)
j = self._get_axis_number(axis2)
if i == j:
if copy:
return self.copy()
return self
mapping = {i: j, j: i}
new_axes = (self._get_axis(mapping.get(k, k))
for k in range(self._AXIS_LEN))
new_values = self.values.swapaxes(i, j)
if copy:
new_values = new_values.copy()
return self._constructor(new_values, *new_axes).__finalize__(self) | def swapaxes(self, axis1, axis2, copy=True):
"""
Interchange axes and swap values axes appropriately.
Returns
-------
y : same as input
"""
i = self._get_axis_number(axis1)
j = self._get_axis_number(axis2)
if i == j:
if copy:
return self.copy()
return self
mapping = {i: j, j: i}
new_axes = (self._get_axis(mapping.get(k, k))
for k in range(self._AXIS_LEN))
new_values = self.values.swapaxes(i, j)
if copy:
new_values = new_values.copy()
return self._constructor(new_values, *new_axes).__finalize__(self) | [
"Interchange",
"axes",
"and",
"swap",
"values",
"axes",
"appropriately",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L694-L718 | [
"def",
"swapaxes",
"(",
"self",
",",
"axis1",
",",
"axis2",
",",
"copy",
"=",
"True",
")",
":",
"i",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis1",
")",
"j",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis2",
")",
"if",
"i",
"==",
"j",
":",
"if",
"copy",
":",
"return",
"self",
".",
"copy",
"(",
")",
"return",
"self",
"mapping",
"=",
"{",
"i",
":",
"j",
",",
"j",
":",
"i",
"}",
"new_axes",
"=",
"(",
"self",
".",
"_get_axis",
"(",
"mapping",
".",
"get",
"(",
"k",
",",
"k",
")",
")",
"for",
"k",
"in",
"range",
"(",
"self",
".",
"_AXIS_LEN",
")",
")",
"new_values",
"=",
"self",
".",
"values",
".",
"swapaxes",
"(",
"i",
",",
"j",
")",
"if",
"copy",
":",
"new_values",
"=",
"new_values",
".",
"copy",
"(",
")",
"return",
"self",
".",
"_constructor",
"(",
"new_values",
",",
"*",
"new_axes",
")",
".",
"__finalize__",
"(",
"self",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.droplevel | Return DataFrame with requested index / column level(s) removed.
.. versionadded:: 0.24.0
Parameters
----------
level : int, str, or list-like
If a string is given, must be the name of a level
If list-like, elements must be names or positional indexes
of levels.
axis : {0 or 'index', 1 or 'columns'}, default 0
Returns
-------
DataFrame.droplevel()
Examples
--------
>>> df = pd.DataFrame([
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12]
... ]).set_index([0, 1]).rename_axis(['a', 'b'])
>>> df.columns = pd.MultiIndex.from_tuples([
... ('c', 'e'), ('d', 'f')
... ], names=['level_1', 'level_2'])
>>> df
level_1 c d
level_2 e f
a b
1 2 3 4
5 6 7 8
9 10 11 12
>>> df.droplevel('a')
level_1 c d
level_2 e f
b
2 3 4
6 7 8
10 11 12
>>> df.droplevel('level2', axis=1)
level_1 c d
a b
1 2 3 4
5 6 7 8
9 10 11 12 | pandas/core/generic.py | def droplevel(self, level, axis=0):
"""
Return DataFrame with requested index / column level(s) removed.
.. versionadded:: 0.24.0
Parameters
----------
level : int, str, or list-like
If a string is given, must be the name of a level
If list-like, elements must be names or positional indexes
of levels.
axis : {0 or 'index', 1 or 'columns'}, default 0
Returns
-------
DataFrame.droplevel()
Examples
--------
>>> df = pd.DataFrame([
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12]
... ]).set_index([0, 1]).rename_axis(['a', 'b'])
>>> df.columns = pd.MultiIndex.from_tuples([
... ('c', 'e'), ('d', 'f')
... ], names=['level_1', 'level_2'])
>>> df
level_1 c d
level_2 e f
a b
1 2 3 4
5 6 7 8
9 10 11 12
>>> df.droplevel('a')
level_1 c d
level_2 e f
b
2 3 4
6 7 8
10 11 12
>>> df.droplevel('level2', axis=1)
level_1 c d
a b
1 2 3 4
5 6 7 8
9 10 11 12
"""
labels = self._get_axis(axis)
new_labels = labels.droplevel(level)
result = self.set_axis(new_labels, axis=axis, inplace=False)
return result | def droplevel(self, level, axis=0):
"""
Return DataFrame with requested index / column level(s) removed.
.. versionadded:: 0.24.0
Parameters
----------
level : int, str, or list-like
If a string is given, must be the name of a level
If list-like, elements must be names or positional indexes
of levels.
axis : {0 or 'index', 1 or 'columns'}, default 0
Returns
-------
DataFrame.droplevel()
Examples
--------
>>> df = pd.DataFrame([
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12]
... ]).set_index([0, 1]).rename_axis(['a', 'b'])
>>> df.columns = pd.MultiIndex.from_tuples([
... ('c', 'e'), ('d', 'f')
... ], names=['level_1', 'level_2'])
>>> df
level_1 c d
level_2 e f
a b
1 2 3 4
5 6 7 8
9 10 11 12
>>> df.droplevel('a')
level_1 c d
level_2 e f
b
2 3 4
6 7 8
10 11 12
>>> df.droplevel('level2', axis=1)
level_1 c d
a b
1 2 3 4
5 6 7 8
9 10 11 12
"""
labels = self._get_axis(axis)
new_labels = labels.droplevel(level)
result = self.set_axis(new_labels, axis=axis, inplace=False)
return result | [
"Return",
"DataFrame",
"with",
"requested",
"index",
"/",
"column",
"level",
"(",
"s",
")",
"removed",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L720-L777 | [
"def",
"droplevel",
"(",
"self",
",",
"level",
",",
"axis",
"=",
"0",
")",
":",
"labels",
"=",
"self",
".",
"_get_axis",
"(",
"axis",
")",
"new_labels",
"=",
"labels",
".",
"droplevel",
"(",
"level",
")",
"result",
"=",
"self",
".",
"set_axis",
"(",
"new_labels",
",",
"axis",
"=",
"axis",
",",
"inplace",
"=",
"False",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.pop | Return item and drop from frame. Raise KeyError if not found.
Parameters
----------
item : str
Label of column to be popped.
Returns
-------
Series
Examples
--------
>>> df = pd.DataFrame([('falcon', 'bird', 389.0),
... ('parrot', 'bird', 24.0),
... ('lion', 'mammal', 80.5),
... ('monkey','mammal', np.nan)],
... columns=('name', 'class', 'max_speed'))
>>> df
name class max_speed
0 falcon bird 389.0
1 parrot bird 24.0
2 lion mammal 80.5
3 monkey mammal NaN
>>> df.pop('class')
0 bird
1 bird
2 mammal
3 mammal
Name: class, dtype: object
>>> df
name max_speed
0 falcon 389.0
1 parrot 24.0
2 lion 80.5
3 monkey NaN | pandas/core/generic.py | def pop(self, item):
"""
Return item and drop from frame. Raise KeyError if not found.
Parameters
----------
item : str
Label of column to be popped.
Returns
-------
Series
Examples
--------
>>> df = pd.DataFrame([('falcon', 'bird', 389.0),
... ('parrot', 'bird', 24.0),
... ('lion', 'mammal', 80.5),
... ('monkey','mammal', np.nan)],
... columns=('name', 'class', 'max_speed'))
>>> df
name class max_speed
0 falcon bird 389.0
1 parrot bird 24.0
2 lion mammal 80.5
3 monkey mammal NaN
>>> df.pop('class')
0 bird
1 bird
2 mammal
3 mammal
Name: class, dtype: object
>>> df
name max_speed
0 falcon 389.0
1 parrot 24.0
2 lion 80.5
3 monkey NaN
"""
result = self[item]
del self[item]
try:
result._reset_cacher()
except AttributeError:
pass
return result | def pop(self, item):
"""
Return item and drop from frame. Raise KeyError if not found.
Parameters
----------
item : str
Label of column to be popped.
Returns
-------
Series
Examples
--------
>>> df = pd.DataFrame([('falcon', 'bird', 389.0),
... ('parrot', 'bird', 24.0),
... ('lion', 'mammal', 80.5),
... ('monkey','mammal', np.nan)],
... columns=('name', 'class', 'max_speed'))
>>> df
name class max_speed
0 falcon bird 389.0
1 parrot bird 24.0
2 lion mammal 80.5
3 monkey mammal NaN
>>> df.pop('class')
0 bird
1 bird
2 mammal
3 mammal
Name: class, dtype: object
>>> df
name max_speed
0 falcon 389.0
1 parrot 24.0
2 lion 80.5
3 monkey NaN
"""
result = self[item]
del self[item]
try:
result._reset_cacher()
except AttributeError:
pass
return result | [
"Return",
"item",
"and",
"drop",
"from",
"frame",
".",
"Raise",
"KeyError",
"if",
"not",
"found",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L779-L827 | [
"def",
"pop",
"(",
"self",
",",
"item",
")",
":",
"result",
"=",
"self",
"[",
"item",
"]",
"del",
"self",
"[",
"item",
"]",
"try",
":",
"result",
".",
"_reset_cacher",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.squeeze | Squeeze 1 dimensional axis objects into scalars.
Series or DataFrames with a single element are squeezed to a scalar.
DataFrames with a single column or a single row are squeezed to a
Series. Otherwise the object is unchanged.
This method is most useful when you don't know if your
object is a Series or DataFrame, but you do know it has just a single
column. In that case you can safely call `squeeze` to ensure you have a
Series.
Parameters
----------
axis : {0 or 'index', 1 or 'columns', None}, default None
A specific axis to squeeze. By default, all length-1 axes are
squeezed.
.. versionadded:: 0.20.0
Returns
-------
DataFrame, Series, or scalar
The projection after squeezing `axis` or all the axes.
See Also
--------
Series.iloc : Integer-location based indexing for selecting scalars.
DataFrame.iloc : Integer-location based indexing for selecting Series.
Series.to_frame : Inverse of DataFrame.squeeze for a
single-column DataFrame.
Examples
--------
>>> primes = pd.Series([2, 3, 5, 7])
Slicing might produce a Series with a single value:
>>> even_primes = primes[primes % 2 == 0]
>>> even_primes
0 2
dtype: int64
>>> even_primes.squeeze()
2
Squeezing objects with more than one value in every axis does nothing:
>>> odd_primes = primes[primes % 2 == 1]
>>> odd_primes
1 3
2 5
3 7
dtype: int64
>>> odd_primes.squeeze()
1 3
2 5
3 7
dtype: int64
Squeezing is even more effective when used with DataFrames.
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
>>> df
a b
0 1 2
1 3 4
Slicing a single column will produce a DataFrame with the columns
having only one value:
>>> df_a = df[['a']]
>>> df_a
a
0 1
1 3
So the columns can be squeezed down, resulting in a Series:
>>> df_a.squeeze('columns')
0 1
1 3
Name: a, dtype: int64
Slicing a single row from a single column will produce a single
scalar DataFrame:
>>> df_0a = df.loc[df.index < 1, ['a']]
>>> df_0a
a
0 1
Squeezing the rows produces a single scalar Series:
>>> df_0a.squeeze('rows')
a 1
Name: 0, dtype: int64
Squeezing all axes wil project directly into a scalar:
>>> df_0a.squeeze()
1 | pandas/core/generic.py | def squeeze(self, axis=None):
"""
Squeeze 1 dimensional axis objects into scalars.
Series or DataFrames with a single element are squeezed to a scalar.
DataFrames with a single column or a single row are squeezed to a
Series. Otherwise the object is unchanged.
This method is most useful when you don't know if your
object is a Series or DataFrame, but you do know it has just a single
column. In that case you can safely call `squeeze` to ensure you have a
Series.
Parameters
----------
axis : {0 or 'index', 1 or 'columns', None}, default None
A specific axis to squeeze. By default, all length-1 axes are
squeezed.
.. versionadded:: 0.20.0
Returns
-------
DataFrame, Series, or scalar
The projection after squeezing `axis` or all the axes.
See Also
--------
Series.iloc : Integer-location based indexing for selecting scalars.
DataFrame.iloc : Integer-location based indexing for selecting Series.
Series.to_frame : Inverse of DataFrame.squeeze for a
single-column DataFrame.
Examples
--------
>>> primes = pd.Series([2, 3, 5, 7])
Slicing might produce a Series with a single value:
>>> even_primes = primes[primes % 2 == 0]
>>> even_primes
0 2
dtype: int64
>>> even_primes.squeeze()
2
Squeezing objects with more than one value in every axis does nothing:
>>> odd_primes = primes[primes % 2 == 1]
>>> odd_primes
1 3
2 5
3 7
dtype: int64
>>> odd_primes.squeeze()
1 3
2 5
3 7
dtype: int64
Squeezing is even more effective when used with DataFrames.
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
>>> df
a b
0 1 2
1 3 4
Slicing a single column will produce a DataFrame with the columns
having only one value:
>>> df_a = df[['a']]
>>> df_a
a
0 1
1 3
So the columns can be squeezed down, resulting in a Series:
>>> df_a.squeeze('columns')
0 1
1 3
Name: a, dtype: int64
Slicing a single row from a single column will produce a single
scalar DataFrame:
>>> df_0a = df.loc[df.index < 1, ['a']]
>>> df_0a
a
0 1
Squeezing the rows produces a single scalar Series:
>>> df_0a.squeeze('rows')
a 1
Name: 0, dtype: int64
Squeezing all axes wil project directly into a scalar:
>>> df_0a.squeeze()
1
"""
axis = (self._AXIS_NAMES if axis is None else
(self._get_axis_number(axis),))
try:
return self.iloc[
tuple(0 if i in axis and len(a) == 1 else slice(None)
for i, a in enumerate(self.axes))]
except Exception:
return self | def squeeze(self, axis=None):
"""
Squeeze 1 dimensional axis objects into scalars.
Series or DataFrames with a single element are squeezed to a scalar.
DataFrames with a single column or a single row are squeezed to a
Series. Otherwise the object is unchanged.
This method is most useful when you don't know if your
object is a Series or DataFrame, but you do know it has just a single
column. In that case you can safely call `squeeze` to ensure you have a
Series.
Parameters
----------
axis : {0 or 'index', 1 or 'columns', None}, default None
A specific axis to squeeze. By default, all length-1 axes are
squeezed.
.. versionadded:: 0.20.0
Returns
-------
DataFrame, Series, or scalar
The projection after squeezing `axis` or all the axes.
See Also
--------
Series.iloc : Integer-location based indexing for selecting scalars.
DataFrame.iloc : Integer-location based indexing for selecting Series.
Series.to_frame : Inverse of DataFrame.squeeze for a
single-column DataFrame.
Examples
--------
>>> primes = pd.Series([2, 3, 5, 7])
Slicing might produce a Series with a single value:
>>> even_primes = primes[primes % 2 == 0]
>>> even_primes
0 2
dtype: int64
>>> even_primes.squeeze()
2
Squeezing objects with more than one value in every axis does nothing:
>>> odd_primes = primes[primes % 2 == 1]
>>> odd_primes
1 3
2 5
3 7
dtype: int64
>>> odd_primes.squeeze()
1 3
2 5
3 7
dtype: int64
Squeezing is even more effective when used with DataFrames.
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
>>> df
a b
0 1 2
1 3 4
Slicing a single column will produce a DataFrame with the columns
having only one value:
>>> df_a = df[['a']]
>>> df_a
a
0 1
1 3
So the columns can be squeezed down, resulting in a Series:
>>> df_a.squeeze('columns')
0 1
1 3
Name: a, dtype: int64
Slicing a single row from a single column will produce a single
scalar DataFrame:
>>> df_0a = df.loc[df.index < 1, ['a']]
>>> df_0a
a
0 1
Squeezing the rows produces a single scalar Series:
>>> df_0a.squeeze('rows')
a 1
Name: 0, dtype: int64
Squeezing all axes wil project directly into a scalar:
>>> df_0a.squeeze()
1
"""
axis = (self._AXIS_NAMES if axis is None else
(self._get_axis_number(axis),))
try:
return self.iloc[
tuple(0 if i in axis and len(a) == 1 else slice(None)
for i, a in enumerate(self.axes))]
except Exception:
return self | [
"Squeeze",
"1",
"dimensional",
"axis",
"objects",
"into",
"scalars",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L829-L941 | [
"def",
"squeeze",
"(",
"self",
",",
"axis",
"=",
"None",
")",
":",
"axis",
"=",
"(",
"self",
".",
"_AXIS_NAMES",
"if",
"axis",
"is",
"None",
"else",
"(",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
",",
")",
")",
"try",
":",
"return",
"self",
".",
"iloc",
"[",
"tuple",
"(",
"0",
"if",
"i",
"in",
"axis",
"and",
"len",
"(",
"a",
")",
"==",
"1",
"else",
"slice",
"(",
"None",
")",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"self",
".",
"axes",
")",
")",
"]",
"except",
"Exception",
":",
"return",
"self"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.swaplevel | Swap levels i and j in a MultiIndex on a particular axis
Parameters
----------
i, j : int, str (can be mixed)
Level of index to be swapped. Can pass level name as string.
Returns
-------
swapped : same type as caller (new object)
.. versionchanged:: 0.18.1
The indexes ``i`` and ``j`` are now optional, and default to
the two innermost levels of the index. | pandas/core/generic.py | def swaplevel(self, i=-2, j=-1, axis=0):
"""
Swap levels i and j in a MultiIndex on a particular axis
Parameters
----------
i, j : int, str (can be mixed)
Level of index to be swapped. Can pass level name as string.
Returns
-------
swapped : same type as caller (new object)
.. versionchanged:: 0.18.1
The indexes ``i`` and ``j`` are now optional, and default to
the two innermost levels of the index.
"""
axis = self._get_axis_number(axis)
result = self.copy()
labels = result._data.axes[axis]
result._data.set_axis(axis, labels.swaplevel(i, j))
return result | def swaplevel(self, i=-2, j=-1, axis=0):
"""
Swap levels i and j in a MultiIndex on a particular axis
Parameters
----------
i, j : int, str (can be mixed)
Level of index to be swapped. Can pass level name as string.
Returns
-------
swapped : same type as caller (new object)
.. versionchanged:: 0.18.1
The indexes ``i`` and ``j`` are now optional, and default to
the two innermost levels of the index.
"""
axis = self._get_axis_number(axis)
result = self.copy()
labels = result._data.axes[axis]
result._data.set_axis(axis, labels.swaplevel(i, j))
return result | [
"Swap",
"levels",
"i",
"and",
"j",
"in",
"a",
"MultiIndex",
"on",
"a",
"particular",
"axis"
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L943-L965 | [
"def",
"swaplevel",
"(",
"self",
",",
"i",
"=",
"-",
"2",
",",
"j",
"=",
"-",
"1",
",",
"axis",
"=",
"0",
")",
":",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"labels",
"=",
"result",
".",
"_data",
".",
"axes",
"[",
"axis",
"]",
"result",
".",
"_data",
".",
"set_axis",
"(",
"axis",
",",
"labels",
".",
"swaplevel",
"(",
"i",
",",
"j",
")",
")",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.rename | Alter axes input function or functions. Function / dict values must be
unique (1-to-1). Labels not contained in a dict / Series will be left
as-is. Extra labels listed don't throw an error. Alternatively, change
``Series.name`` with a scalar value (Series only).
Parameters
----------
%(axes)s : scalar, list-like, dict-like or function, optional
Scalar or list-like will alter the ``Series.name`` attribute,
and raise on DataFrame or Panel.
dict-like or functions are transformations to apply to
that axis' values
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new %(klass)s. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.
Returns
-------
renamed : %(klass)s (new object)
Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
See Also
--------
NDFrame.rename_axis
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
>>> s.rename(lambda x: x ** 2) # function, changes labels
0 1
1 2
4 3
dtype: int64
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
0 1
3 2
5 3
dtype: int64
Since ``DataFrame`` doesn't have a ``.name`` attribute,
only mapping-type arguments are allowed.
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(2)
Traceback (most recent call last):
...
TypeError: 'int' object is not callable
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6
Using axis-style parameters
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
See the :ref:`user guide <basics.rename>` for more. | pandas/core/generic.py | def rename(self, *args, **kwargs):
"""
Alter axes input function or functions. Function / dict values must be
unique (1-to-1). Labels not contained in a dict / Series will be left
as-is. Extra labels listed don't throw an error. Alternatively, change
``Series.name`` with a scalar value (Series only).
Parameters
----------
%(axes)s : scalar, list-like, dict-like or function, optional
Scalar or list-like will alter the ``Series.name`` attribute,
and raise on DataFrame or Panel.
dict-like or functions are transformations to apply to
that axis' values
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new %(klass)s. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.
Returns
-------
renamed : %(klass)s (new object)
Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
See Also
--------
NDFrame.rename_axis
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
>>> s.rename(lambda x: x ** 2) # function, changes labels
0 1
1 2
4 3
dtype: int64
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
0 1
3 2
5 3
dtype: int64
Since ``DataFrame`` doesn't have a ``.name`` attribute,
only mapping-type arguments are allowed.
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(2)
Traceback (most recent call last):
...
TypeError: 'int' object is not callable
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6
Using axis-style parameters
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
See the :ref:`user guide <basics.rename>` for more.
"""
axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
copy = kwargs.pop('copy', True)
inplace = kwargs.pop('inplace', False)
level = kwargs.pop('level', None)
axis = kwargs.pop('axis', None)
errors = kwargs.pop('errors', 'ignore')
if axis is not None:
# Validate the axis
self._get_axis_number(axis)
if kwargs:
raise TypeError('rename() got an unexpected keyword '
'argument "{0}"'.format(list(kwargs.keys())[0]))
if com.count_not_none(*axes.values()) == 0:
raise TypeError('must pass an index to rename')
self._consolidate_inplace()
result = self if inplace else self.copy(deep=copy)
# start in the axis order to eliminate too many copies
for axis in lrange(self._AXIS_LEN):
v = axes.get(self._AXIS_NAMES[axis])
if v is None:
continue
f = com._get_rename_function(v)
baxis = self._get_block_manager_axis(axis)
if level is not None:
level = self.axes[axis]._get_level_number(level)
# GH 13473
if not callable(v):
indexer = self.axes[axis].get_indexer_for(v)
if errors == 'raise' and len(indexer[indexer == -1]):
missing_labels = [label for index, label in enumerate(v)
if indexer[index] == -1]
raise KeyError('{} not found in axis'
.format(missing_labels))
result._data = result._data.rename_axis(f, axis=baxis, copy=copy,
level=level)
result._clear_item_cache()
if inplace:
self._update_inplace(result._data)
else:
return result.__finalize__(self) | def rename(self, *args, **kwargs):
"""
Alter axes input function or functions. Function / dict values must be
unique (1-to-1). Labels not contained in a dict / Series will be left
as-is. Extra labels listed don't throw an error. Alternatively, change
``Series.name`` with a scalar value (Series only).
Parameters
----------
%(axes)s : scalar, list-like, dict-like or function, optional
Scalar or list-like will alter the ``Series.name`` attribute,
and raise on DataFrame or Panel.
dict-like or functions are transformations to apply to
that axis' values
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new %(klass)s. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.
Returns
-------
renamed : %(klass)s (new object)
Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
See Also
--------
NDFrame.rename_axis
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
>>> s.rename(lambda x: x ** 2) # function, changes labels
0 1
1 2
4 3
dtype: int64
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
0 1
3 2
5 3
dtype: int64
Since ``DataFrame`` doesn't have a ``.name`` attribute,
only mapping-type arguments are allowed.
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(2)
Traceback (most recent call last):
...
TypeError: 'int' object is not callable
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6
Using axis-style parameters
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
See the :ref:`user guide <basics.rename>` for more.
"""
axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
copy = kwargs.pop('copy', True)
inplace = kwargs.pop('inplace', False)
level = kwargs.pop('level', None)
axis = kwargs.pop('axis', None)
errors = kwargs.pop('errors', 'ignore')
if axis is not None:
# Validate the axis
self._get_axis_number(axis)
if kwargs:
raise TypeError('rename() got an unexpected keyword '
'argument "{0}"'.format(list(kwargs.keys())[0]))
if com.count_not_none(*axes.values()) == 0:
raise TypeError('must pass an index to rename')
self._consolidate_inplace()
result = self if inplace else self.copy(deep=copy)
# start in the axis order to eliminate too many copies
for axis in lrange(self._AXIS_LEN):
v = axes.get(self._AXIS_NAMES[axis])
if v is None:
continue
f = com._get_rename_function(v)
baxis = self._get_block_manager_axis(axis)
if level is not None:
level = self.axes[axis]._get_level_number(level)
# GH 13473
if not callable(v):
indexer = self.axes[axis].get_indexer_for(v)
if errors == 'raise' and len(indexer[indexer == -1]):
missing_labels = [label for index, label in enumerate(v)
if indexer[index] == -1]
raise KeyError('{} not found in axis'
.format(missing_labels))
result._data = result._data.rename_axis(f, axis=baxis, copy=copy,
level=level)
result._clear_item_cache()
if inplace:
self._update_inplace(result._data)
else:
return result.__finalize__(self) | [
"Alter",
"axes",
"input",
"function",
"or",
"functions",
".",
"Function",
"/",
"dict",
"values",
"must",
"be",
"unique",
"(",
"1",
"-",
"to",
"-",
"1",
")",
".",
"Labels",
"not",
"contained",
"in",
"a",
"dict",
"/",
"Series",
"will",
"be",
"left",
"as",
"-",
"is",
".",
"Extra",
"labels",
"listed",
"don",
"t",
"throw",
"an",
"error",
".",
"Alternatively",
"change",
"Series",
".",
"name",
"with",
"a",
"scalar",
"value",
"(",
"Series",
"only",
")",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L970-L1129 | [
"def",
"rename",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"axes",
",",
"kwargs",
"=",
"self",
".",
"_construct_axes_from_arguments",
"(",
"args",
",",
"kwargs",
")",
"copy",
"=",
"kwargs",
".",
"pop",
"(",
"'copy'",
",",
"True",
")",
"inplace",
"=",
"kwargs",
".",
"pop",
"(",
"'inplace'",
",",
"False",
")",
"level",
"=",
"kwargs",
".",
"pop",
"(",
"'level'",
",",
"None",
")",
"axis",
"=",
"kwargs",
".",
"pop",
"(",
"'axis'",
",",
"None",
")",
"errors",
"=",
"kwargs",
".",
"pop",
"(",
"'errors'",
",",
"'ignore'",
")",
"if",
"axis",
"is",
"not",
"None",
":",
"# Validate the axis",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'rename() got an unexpected keyword '",
"'argument \"{0}\"'",
".",
"format",
"(",
"list",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
")",
")",
"if",
"com",
".",
"count_not_none",
"(",
"*",
"axes",
".",
"values",
"(",
")",
")",
"==",
"0",
":",
"raise",
"TypeError",
"(",
"'must pass an index to rename'",
")",
"self",
".",
"_consolidate_inplace",
"(",
")",
"result",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
"deep",
"=",
"copy",
")",
"# start in the axis order to eliminate too many copies",
"for",
"axis",
"in",
"lrange",
"(",
"self",
".",
"_AXIS_LEN",
")",
":",
"v",
"=",
"axes",
".",
"get",
"(",
"self",
".",
"_AXIS_NAMES",
"[",
"axis",
"]",
")",
"if",
"v",
"is",
"None",
":",
"continue",
"f",
"=",
"com",
".",
"_get_rename_function",
"(",
"v",
")",
"baxis",
"=",
"self",
".",
"_get_block_manager_axis",
"(",
"axis",
")",
"if",
"level",
"is",
"not",
"None",
":",
"level",
"=",
"self",
".",
"axes",
"[",
"axis",
"]",
".",
"_get_level_number",
"(",
"level",
")",
"# GH 13473",
"if",
"not",
"callable",
"(",
"v",
")",
":",
"indexer",
"=",
"self",
".",
"axes",
"[",
"axis",
"]",
".",
"get_indexer_for",
"(",
"v",
")",
"if",
"errors",
"==",
"'raise'",
"and",
"len",
"(",
"indexer",
"[",
"indexer",
"==",
"-",
"1",
"]",
")",
":",
"missing_labels",
"=",
"[",
"label",
"for",
"index",
",",
"label",
"in",
"enumerate",
"(",
"v",
")",
"if",
"indexer",
"[",
"index",
"]",
"==",
"-",
"1",
"]",
"raise",
"KeyError",
"(",
"'{} not found in axis'",
".",
"format",
"(",
"missing_labels",
")",
")",
"result",
".",
"_data",
"=",
"result",
".",
"_data",
".",
"rename_axis",
"(",
"f",
",",
"axis",
"=",
"baxis",
",",
"copy",
"=",
"copy",
",",
"level",
"=",
"level",
")",
"result",
".",
"_clear_item_cache",
"(",
")",
"if",
"inplace",
":",
"self",
".",
"_update_inplace",
"(",
"result",
".",
"_data",
")",
"else",
":",
"return",
"result",
".",
"__finalize__",
"(",
"self",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.rename_axis | Set the name of the axis for the index or columns.
Parameters
----------
mapper : scalar, list-like, optional
Value to set the axis name attribute.
index, columns : scalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to
apply to that axis' values.
Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index``
and/or ``columns``.
.. versionchanged:: 0.24.0
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to rename.
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Modifies the object directly, instead of creating a new Series
or DataFrame.
Returns
-------
Series, DataFrame, or None
The same type as the caller or None if `inplace` is True.
See Also
--------
Series.rename : Alter Series index labels or name.
DataFrame.rename : Alter DataFrame index labels or name.
Index.rename : Set new names on index.
Notes
-----
Prior to version 0.21.0, ``rename_axis`` could also be used to change
the axis *labels* by passing a mapping or scalar. This behavior is
deprecated and will be removed in a future version. Use ``rename``
instead.
``DataFrame.rename_axis`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
The first calling convention will only modify the names of
the index and/or the names of the Index object that is the columns.
In this case, the parameter ``copy`` is ignored.
The second calling convention will modify the names of the
the corresponding index if mapper is a list or a scalar.
However, if mapper is dict-like or a function, it will use the
deprecated behavior of modifying the axis *labels*.
We *highly* recommend using keyword arguments to clarify your
intent.
Examples
--------
**Series**
>>> s = pd.Series(["dog", "cat", "monkey"])
>>> s
0 dog
1 cat
2 monkey
dtype: object
>>> s.rename_axis("animal")
animal
0 dog
1 cat
2 monkey
dtype: object
**DataFrame**
>>> df = pd.DataFrame({"num_legs": [4, 4, 2],
... "num_arms": [0, 0, 2]},
... ["dog", "cat", "monkey"])
>>> df
num_legs num_arms
dog 4 0
cat 4 0
monkey 2 2
>>> df = df.rename_axis("animal")
>>> df
num_legs num_arms
animal
dog 4 0
cat 4 0
monkey 2 2
>>> df = df.rename_axis("limbs", axis="columns")
>>> df
limbs num_legs num_arms
animal
dog 4 0
cat 4 0
monkey 2 2
**MultiIndex**
>>> df.index = pd.MultiIndex.from_product([['mammal'],
... ['dog', 'cat', 'monkey']],
... names=['type', 'name'])
>>> df
limbs num_legs num_arms
type name
mammal dog 4 0
cat 4 0
monkey 2 2
>>> df.rename_axis(index={'type': 'class'})
limbs num_legs num_arms
class name
mammal dog 4 0
cat 4 0
monkey 2 2
>>> df.rename_axis(columns=str.upper)
LIMBS num_legs num_arms
type name
mammal dog 4 0
cat 4 0
monkey 2 2 | pandas/core/generic.py | def rename_axis(self, mapper=sentinel, **kwargs):
"""
Set the name of the axis for the index or columns.
Parameters
----------
mapper : scalar, list-like, optional
Value to set the axis name attribute.
index, columns : scalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to
apply to that axis' values.
Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index``
and/or ``columns``.
.. versionchanged:: 0.24.0
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to rename.
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Modifies the object directly, instead of creating a new Series
or DataFrame.
Returns
-------
Series, DataFrame, or None
The same type as the caller or None if `inplace` is True.
See Also
--------
Series.rename : Alter Series index labels or name.
DataFrame.rename : Alter DataFrame index labels or name.
Index.rename : Set new names on index.
Notes
-----
Prior to version 0.21.0, ``rename_axis`` could also be used to change
the axis *labels* by passing a mapping or scalar. This behavior is
deprecated and will be removed in a future version. Use ``rename``
instead.
``DataFrame.rename_axis`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
The first calling convention will only modify the names of
the index and/or the names of the Index object that is the columns.
In this case, the parameter ``copy`` is ignored.
The second calling convention will modify the names of the
the corresponding index if mapper is a list or a scalar.
However, if mapper is dict-like or a function, it will use the
deprecated behavior of modifying the axis *labels*.
We *highly* recommend using keyword arguments to clarify your
intent.
Examples
--------
**Series**
>>> s = pd.Series(["dog", "cat", "monkey"])
>>> s
0 dog
1 cat
2 monkey
dtype: object
>>> s.rename_axis("animal")
animal
0 dog
1 cat
2 monkey
dtype: object
**DataFrame**
>>> df = pd.DataFrame({"num_legs": [4, 4, 2],
... "num_arms": [0, 0, 2]},
... ["dog", "cat", "monkey"])
>>> df
num_legs num_arms
dog 4 0
cat 4 0
monkey 2 2
>>> df = df.rename_axis("animal")
>>> df
num_legs num_arms
animal
dog 4 0
cat 4 0
monkey 2 2
>>> df = df.rename_axis("limbs", axis="columns")
>>> df
limbs num_legs num_arms
animal
dog 4 0
cat 4 0
monkey 2 2
**MultiIndex**
>>> df.index = pd.MultiIndex.from_product([['mammal'],
... ['dog', 'cat', 'monkey']],
... names=['type', 'name'])
>>> df
limbs num_legs num_arms
type name
mammal dog 4 0
cat 4 0
monkey 2 2
>>> df.rename_axis(index={'type': 'class'})
limbs num_legs num_arms
class name
mammal dog 4 0
cat 4 0
monkey 2 2
>>> df.rename_axis(columns=str.upper)
LIMBS num_legs num_arms
type name
mammal dog 4 0
cat 4 0
monkey 2 2
"""
axes, kwargs = self._construct_axes_from_arguments(
(), kwargs, sentinel=sentinel)
copy = kwargs.pop('copy', True)
inplace = kwargs.pop('inplace', False)
axis = kwargs.pop('axis', 0)
if axis is not None:
axis = self._get_axis_number(axis)
if kwargs:
raise TypeError('rename_axis() got an unexpected keyword '
'argument "{0}"'.format(list(kwargs.keys())[0]))
inplace = validate_bool_kwarg(inplace, 'inplace')
if (mapper is not sentinel):
# Use v0.23 behavior if a scalar or list
non_mapper = is_scalar(mapper) or (is_list_like(mapper) and not
is_dict_like(mapper))
if non_mapper:
return self._set_axis_name(mapper, axis=axis, inplace=inplace)
else:
# Deprecated (v0.21) behavior is if mapper is specified,
# and not a list or scalar, then call rename
msg = ("Using 'rename_axis' to alter labels is deprecated. "
"Use '.rename' instead")
warnings.warn(msg, FutureWarning, stacklevel=3)
axis = self._get_axis_name(axis)
d = {'copy': copy, 'inplace': inplace}
d[axis] = mapper
return self.rename(**d)
else:
# Use new behavior. Means that index and/or columns
# is specified
result = self if inplace else self.copy(deep=copy)
for axis in lrange(self._AXIS_LEN):
v = axes.get(self._AXIS_NAMES[axis])
if v is sentinel:
continue
non_mapper = is_scalar(v) or (is_list_like(v) and not
is_dict_like(v))
if non_mapper:
newnames = v
else:
f = com._get_rename_function(v)
curnames = self._get_axis(axis).names
newnames = [f(name) for name in curnames]
result._set_axis_name(newnames, axis=axis,
inplace=True)
if not inplace:
return result | def rename_axis(self, mapper=sentinel, **kwargs):
"""
Set the name of the axis for the index or columns.
Parameters
----------
mapper : scalar, list-like, optional
Value to set the axis name attribute.
index, columns : scalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to
apply to that axis' values.
Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index``
and/or ``columns``.
.. versionchanged:: 0.24.0
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to rename.
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Modifies the object directly, instead of creating a new Series
or DataFrame.
Returns
-------
Series, DataFrame, or None
The same type as the caller or None if `inplace` is True.
See Also
--------
Series.rename : Alter Series index labels or name.
DataFrame.rename : Alter DataFrame index labels or name.
Index.rename : Set new names on index.
Notes
-----
Prior to version 0.21.0, ``rename_axis`` could also be used to change
the axis *labels* by passing a mapping or scalar. This behavior is
deprecated and will be removed in a future version. Use ``rename``
instead.
``DataFrame.rename_axis`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
The first calling convention will only modify the names of
the index and/or the names of the Index object that is the columns.
In this case, the parameter ``copy`` is ignored.
The second calling convention will modify the names of the
the corresponding index if mapper is a list or a scalar.
However, if mapper is dict-like or a function, it will use the
deprecated behavior of modifying the axis *labels*.
We *highly* recommend using keyword arguments to clarify your
intent.
Examples
--------
**Series**
>>> s = pd.Series(["dog", "cat", "monkey"])
>>> s
0 dog
1 cat
2 monkey
dtype: object
>>> s.rename_axis("animal")
animal
0 dog
1 cat
2 monkey
dtype: object
**DataFrame**
>>> df = pd.DataFrame({"num_legs": [4, 4, 2],
... "num_arms": [0, 0, 2]},
... ["dog", "cat", "monkey"])
>>> df
num_legs num_arms
dog 4 0
cat 4 0
monkey 2 2
>>> df = df.rename_axis("animal")
>>> df
num_legs num_arms
animal
dog 4 0
cat 4 0
monkey 2 2
>>> df = df.rename_axis("limbs", axis="columns")
>>> df
limbs num_legs num_arms
animal
dog 4 0
cat 4 0
monkey 2 2
**MultiIndex**
>>> df.index = pd.MultiIndex.from_product([['mammal'],
... ['dog', 'cat', 'monkey']],
... names=['type', 'name'])
>>> df
limbs num_legs num_arms
type name
mammal dog 4 0
cat 4 0
monkey 2 2
>>> df.rename_axis(index={'type': 'class'})
limbs num_legs num_arms
class name
mammal dog 4 0
cat 4 0
monkey 2 2
>>> df.rename_axis(columns=str.upper)
LIMBS num_legs num_arms
type name
mammal dog 4 0
cat 4 0
monkey 2 2
"""
axes, kwargs = self._construct_axes_from_arguments(
(), kwargs, sentinel=sentinel)
copy = kwargs.pop('copy', True)
inplace = kwargs.pop('inplace', False)
axis = kwargs.pop('axis', 0)
if axis is not None:
axis = self._get_axis_number(axis)
if kwargs:
raise TypeError('rename_axis() got an unexpected keyword '
'argument "{0}"'.format(list(kwargs.keys())[0]))
inplace = validate_bool_kwarg(inplace, 'inplace')
if (mapper is not sentinel):
# Use v0.23 behavior if a scalar or list
non_mapper = is_scalar(mapper) or (is_list_like(mapper) and not
is_dict_like(mapper))
if non_mapper:
return self._set_axis_name(mapper, axis=axis, inplace=inplace)
else:
# Deprecated (v0.21) behavior is if mapper is specified,
# and not a list or scalar, then call rename
msg = ("Using 'rename_axis' to alter labels is deprecated. "
"Use '.rename' instead")
warnings.warn(msg, FutureWarning, stacklevel=3)
axis = self._get_axis_name(axis)
d = {'copy': copy, 'inplace': inplace}
d[axis] = mapper
return self.rename(**d)
else:
# Use new behavior. Means that index and/or columns
# is specified
result = self if inplace else self.copy(deep=copy)
for axis in lrange(self._AXIS_LEN):
v = axes.get(self._AXIS_NAMES[axis])
if v is sentinel:
continue
non_mapper = is_scalar(v) or (is_list_like(v) and not
is_dict_like(v))
if non_mapper:
newnames = v
else:
f = com._get_rename_function(v)
curnames = self._get_axis(axis).names
newnames = [f(name) for name in curnames]
result._set_axis_name(newnames, axis=axis,
inplace=True)
if not inplace:
return result | [
"Set",
"the",
"name",
"of",
"the",
"axis",
"for",
"the",
"index",
"or",
"columns",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1133-L1312 | [
"def",
"rename_axis",
"(",
"self",
",",
"mapper",
"=",
"sentinel",
",",
"*",
"*",
"kwargs",
")",
":",
"axes",
",",
"kwargs",
"=",
"self",
".",
"_construct_axes_from_arguments",
"(",
"(",
")",
",",
"kwargs",
",",
"sentinel",
"=",
"sentinel",
")",
"copy",
"=",
"kwargs",
".",
"pop",
"(",
"'copy'",
",",
"True",
")",
"inplace",
"=",
"kwargs",
".",
"pop",
"(",
"'inplace'",
",",
"False",
")",
"axis",
"=",
"kwargs",
".",
"pop",
"(",
"'axis'",
",",
"0",
")",
"if",
"axis",
"is",
"not",
"None",
":",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'rename_axis() got an unexpected keyword '",
"'argument \"{0}\"'",
".",
"format",
"(",
"list",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
")",
")",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"(",
"mapper",
"is",
"not",
"sentinel",
")",
":",
"# Use v0.23 behavior if a scalar or list",
"non_mapper",
"=",
"is_scalar",
"(",
"mapper",
")",
"or",
"(",
"is_list_like",
"(",
"mapper",
")",
"and",
"not",
"is_dict_like",
"(",
"mapper",
")",
")",
"if",
"non_mapper",
":",
"return",
"self",
".",
"_set_axis_name",
"(",
"mapper",
",",
"axis",
"=",
"axis",
",",
"inplace",
"=",
"inplace",
")",
"else",
":",
"# Deprecated (v0.21) behavior is if mapper is specified,",
"# and not a list or scalar, then call rename",
"msg",
"=",
"(",
"\"Using 'rename_axis' to alter labels is deprecated. \"",
"\"Use '.rename' instead\"",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"3",
")",
"axis",
"=",
"self",
".",
"_get_axis_name",
"(",
"axis",
")",
"d",
"=",
"{",
"'copy'",
":",
"copy",
",",
"'inplace'",
":",
"inplace",
"}",
"d",
"[",
"axis",
"]",
"=",
"mapper",
"return",
"self",
".",
"rename",
"(",
"*",
"*",
"d",
")",
"else",
":",
"# Use new behavior. Means that index and/or columns",
"# is specified",
"result",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
"deep",
"=",
"copy",
")",
"for",
"axis",
"in",
"lrange",
"(",
"self",
".",
"_AXIS_LEN",
")",
":",
"v",
"=",
"axes",
".",
"get",
"(",
"self",
".",
"_AXIS_NAMES",
"[",
"axis",
"]",
")",
"if",
"v",
"is",
"sentinel",
":",
"continue",
"non_mapper",
"=",
"is_scalar",
"(",
"v",
")",
"or",
"(",
"is_list_like",
"(",
"v",
")",
"and",
"not",
"is_dict_like",
"(",
"v",
")",
")",
"if",
"non_mapper",
":",
"newnames",
"=",
"v",
"else",
":",
"f",
"=",
"com",
".",
"_get_rename_function",
"(",
"v",
")",
"curnames",
"=",
"self",
".",
"_get_axis",
"(",
"axis",
")",
".",
"names",
"newnames",
"=",
"[",
"f",
"(",
"name",
")",
"for",
"name",
"in",
"curnames",
"]",
"result",
".",
"_set_axis_name",
"(",
"newnames",
",",
"axis",
"=",
"axis",
",",
"inplace",
"=",
"True",
")",
"if",
"not",
"inplace",
":",
"return",
"result"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._set_axis_name | Set the name(s) of the axis.
Parameters
----------
name : str or list of str
Name(s) to set.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to set the label. The value 0 or 'index' specifies index,
and the value 1 or 'columns' specifies columns.
inplace : bool, default False
If `True`, do operation inplace and return None.
.. versionadded:: 0.21.0
Returns
-------
Series, DataFrame, or None
The same type as the caller or `None` if `inplace` is `True`.
See Also
--------
DataFrame.rename : Alter the axis labels of :class:`DataFrame`.
Series.rename : Alter the index labels or set the index name
of :class:`Series`.
Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.
Examples
--------
>>> df = pd.DataFrame({"num_legs": [4, 4, 2]},
... ["dog", "cat", "monkey"])
>>> df
num_legs
dog 4
cat 4
monkey 2
>>> df._set_axis_name("animal")
num_legs
animal
dog 4
cat 4
monkey 2
>>> df.index = pd.MultiIndex.from_product(
... [["mammal"], ['dog', 'cat', 'monkey']])
>>> df._set_axis_name(["type", "name"])
legs
type name
mammal dog 4
cat 4
monkey 2 | pandas/core/generic.py | def _set_axis_name(self, name, axis=0, inplace=False):
"""
Set the name(s) of the axis.
Parameters
----------
name : str or list of str
Name(s) to set.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to set the label. The value 0 or 'index' specifies index,
and the value 1 or 'columns' specifies columns.
inplace : bool, default False
If `True`, do operation inplace and return None.
.. versionadded:: 0.21.0
Returns
-------
Series, DataFrame, or None
The same type as the caller or `None` if `inplace` is `True`.
See Also
--------
DataFrame.rename : Alter the axis labels of :class:`DataFrame`.
Series.rename : Alter the index labels or set the index name
of :class:`Series`.
Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.
Examples
--------
>>> df = pd.DataFrame({"num_legs": [4, 4, 2]},
... ["dog", "cat", "monkey"])
>>> df
num_legs
dog 4
cat 4
monkey 2
>>> df._set_axis_name("animal")
num_legs
animal
dog 4
cat 4
monkey 2
>>> df.index = pd.MultiIndex.from_product(
... [["mammal"], ['dog', 'cat', 'monkey']])
>>> df._set_axis_name(["type", "name"])
legs
type name
mammal dog 4
cat 4
monkey 2
"""
axis = self._get_axis_number(axis)
idx = self._get_axis(axis).set_names(name)
inplace = validate_bool_kwarg(inplace, 'inplace')
renamed = self if inplace else self.copy()
renamed.set_axis(idx, axis=axis, inplace=True)
if not inplace:
return renamed | def _set_axis_name(self, name, axis=0, inplace=False):
"""
Set the name(s) of the axis.
Parameters
----------
name : str or list of str
Name(s) to set.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to set the label. The value 0 or 'index' specifies index,
and the value 1 or 'columns' specifies columns.
inplace : bool, default False
If `True`, do operation inplace and return None.
.. versionadded:: 0.21.0
Returns
-------
Series, DataFrame, or None
The same type as the caller or `None` if `inplace` is `True`.
See Also
--------
DataFrame.rename : Alter the axis labels of :class:`DataFrame`.
Series.rename : Alter the index labels or set the index name
of :class:`Series`.
Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.
Examples
--------
>>> df = pd.DataFrame({"num_legs": [4, 4, 2]},
... ["dog", "cat", "monkey"])
>>> df
num_legs
dog 4
cat 4
monkey 2
>>> df._set_axis_name("animal")
num_legs
animal
dog 4
cat 4
monkey 2
>>> df.index = pd.MultiIndex.from_product(
... [["mammal"], ['dog', 'cat', 'monkey']])
>>> df._set_axis_name(["type", "name"])
legs
type name
mammal dog 4
cat 4
monkey 2
"""
axis = self._get_axis_number(axis)
idx = self._get_axis(axis).set_names(name)
inplace = validate_bool_kwarg(inplace, 'inplace')
renamed = self if inplace else self.copy()
renamed.set_axis(idx, axis=axis, inplace=True)
if not inplace:
return renamed | [
"Set",
"the",
"name",
"(",
"s",
")",
"of",
"the",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1314-L1373 | [
"def",
"_set_axis_name",
"(",
"self",
",",
"name",
",",
"axis",
"=",
"0",
",",
"inplace",
"=",
"False",
")",
":",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"idx",
"=",
"self",
".",
"_get_axis",
"(",
"axis",
")",
".",
"set_names",
"(",
"name",
")",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"renamed",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"copy",
"(",
")",
"renamed",
".",
"set_axis",
"(",
"idx",
",",
"axis",
"=",
"axis",
",",
"inplace",
"=",
"True",
")",
"if",
"not",
"inplace",
":",
"return",
"renamed"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.equals | Test whether two objects contain the same elements.
This function allows two Series or DataFrames to be compared against
each other to see if they have the same shape and elements. NaNs in
the same location are considered equal. The column headers do not
need to have the same type, but the elements within the columns must
be the same dtype.
Parameters
----------
other : Series or DataFrame
The other Series or DataFrame to be compared with the first.
Returns
-------
bool
True if all elements are the same in both objects, False
otherwise.
See Also
--------
Series.eq : Compare two Series objects of the same length
and return a Series where each element is True if the element
in each Series is equal, False otherwise.
DataFrame.eq : Compare two DataFrame objects of the same shape and
return a DataFrame where each element is True if the respective
element in each DataFrame is equal, False otherwise.
assert_series_equal : Return True if left and right Series are equal,
False otherwise.
assert_frame_equal : Return True if left and right DataFrames are
equal, False otherwise.
numpy.array_equal : Return True if two arrays have the same shape
and elements, False otherwise.
Notes
-----
This function requires that the elements have the same dtype as their
respective elements in the other Series or DataFrame. However, the
column labels do not need to have the same type, as long as they are
still considered equal.
Examples
--------
>>> df = pd.DataFrame({1: [10], 2: [20]})
>>> df
1 2
0 10 20
DataFrames df and exactly_equal have the same types and values for
their elements and column labels, which will return True.
>>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})
>>> exactly_equal
1 2
0 10 20
>>> df.equals(exactly_equal)
True
DataFrames df and different_column_type have the same element
types and values, but have different types for the column labels,
which will still return True.
>>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})
>>> different_column_type
1.0 2.0
0 10 20
>>> df.equals(different_column_type)
True
DataFrames df and different_data_type have different types for the
same values for their elements, and will return False even though
their column labels are the same values and types.
>>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})
>>> different_data_type
1 2
0 10.0 20.0
>>> df.equals(different_data_type)
False | pandas/core/generic.py | def equals(self, other):
"""
Test whether two objects contain the same elements.
This function allows two Series or DataFrames to be compared against
each other to see if they have the same shape and elements. NaNs in
the same location are considered equal. The column headers do not
need to have the same type, but the elements within the columns must
be the same dtype.
Parameters
----------
other : Series or DataFrame
The other Series or DataFrame to be compared with the first.
Returns
-------
bool
True if all elements are the same in both objects, False
otherwise.
See Also
--------
Series.eq : Compare two Series objects of the same length
and return a Series where each element is True if the element
in each Series is equal, False otherwise.
DataFrame.eq : Compare two DataFrame objects of the same shape and
return a DataFrame where each element is True if the respective
element in each DataFrame is equal, False otherwise.
assert_series_equal : Return True if left and right Series are equal,
False otherwise.
assert_frame_equal : Return True if left and right DataFrames are
equal, False otherwise.
numpy.array_equal : Return True if two arrays have the same shape
and elements, False otherwise.
Notes
-----
This function requires that the elements have the same dtype as their
respective elements in the other Series or DataFrame. However, the
column labels do not need to have the same type, as long as they are
still considered equal.
Examples
--------
>>> df = pd.DataFrame({1: [10], 2: [20]})
>>> df
1 2
0 10 20
DataFrames df and exactly_equal have the same types and values for
their elements and column labels, which will return True.
>>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})
>>> exactly_equal
1 2
0 10 20
>>> df.equals(exactly_equal)
True
DataFrames df and different_column_type have the same element
types and values, but have different types for the column labels,
which will still return True.
>>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})
>>> different_column_type
1.0 2.0
0 10 20
>>> df.equals(different_column_type)
True
DataFrames df and different_data_type have different types for the
same values for their elements, and will return False even though
their column labels are the same values and types.
>>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})
>>> different_data_type
1 2
0 10.0 20.0
>>> df.equals(different_data_type)
False
"""
if not isinstance(other, self._constructor):
return False
return self._data.equals(other._data) | def equals(self, other):
"""
Test whether two objects contain the same elements.
This function allows two Series or DataFrames to be compared against
each other to see if they have the same shape and elements. NaNs in
the same location are considered equal. The column headers do not
need to have the same type, but the elements within the columns must
be the same dtype.
Parameters
----------
other : Series or DataFrame
The other Series or DataFrame to be compared with the first.
Returns
-------
bool
True if all elements are the same in both objects, False
otherwise.
See Also
--------
Series.eq : Compare two Series objects of the same length
and return a Series where each element is True if the element
in each Series is equal, False otherwise.
DataFrame.eq : Compare two DataFrame objects of the same shape and
return a DataFrame where each element is True if the respective
element in each DataFrame is equal, False otherwise.
assert_series_equal : Return True if left and right Series are equal,
False otherwise.
assert_frame_equal : Return True if left and right DataFrames are
equal, False otherwise.
numpy.array_equal : Return True if two arrays have the same shape
and elements, False otherwise.
Notes
-----
This function requires that the elements have the same dtype as their
respective elements in the other Series or DataFrame. However, the
column labels do not need to have the same type, as long as they are
still considered equal.
Examples
--------
>>> df = pd.DataFrame({1: [10], 2: [20]})
>>> df
1 2
0 10 20
DataFrames df and exactly_equal have the same types and values for
their elements and column labels, which will return True.
>>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})
>>> exactly_equal
1 2
0 10 20
>>> df.equals(exactly_equal)
True
DataFrames df and different_column_type have the same element
types and values, but have different types for the column labels,
which will still return True.
>>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})
>>> different_column_type
1.0 2.0
0 10 20
>>> df.equals(different_column_type)
True
DataFrames df and different_data_type have different types for the
same values for their elements, and will return False even though
their column labels are the same values and types.
>>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})
>>> different_data_type
1 2
0 10.0 20.0
>>> df.equals(different_data_type)
False
"""
if not isinstance(other, self._constructor):
return False
return self._data.equals(other._data) | [
"Test",
"whether",
"two",
"objects",
"contain",
"the",
"same",
"elements",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1382-L1466 | [
"def",
"equals",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"self",
".",
"_constructor",
")",
":",
"return",
"False",
"return",
"self",
".",
"_data",
".",
"equals",
"(",
"other",
".",
"_data",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.bool | Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean | pandas/core/generic.py | def bool(self):
"""
Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
"""
v = self.squeeze()
if isinstance(v, (bool, np.bool_)):
return bool(v)
elif is_scalar(v):
raise ValueError("bool cannot act on a non-boolean single element "
"{0}".format(self.__class__.__name__))
self.__nonzero__() | def bool(self):
"""
Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
"""
v = self.squeeze()
if isinstance(v, (bool, np.bool_)):
return bool(v)
elif is_scalar(v):
raise ValueError("bool cannot act on a non-boolean single element "
"{0}".format(self.__class__.__name__))
self.__nonzero__() | [
"Return",
"the",
"bool",
"of",
"a",
"single",
"element",
"PandasObject",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1514-L1529 | [
"def",
"bool",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"squeeze",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"(",
"bool",
",",
"np",
".",
"bool_",
")",
")",
":",
"return",
"bool",
"(",
"v",
")",
"elif",
"is_scalar",
"(",
"v",
")",
":",
"raise",
"ValueError",
"(",
"\"bool cannot act on a non-boolean single element \"",
"\"{0}\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"self",
".",
"__nonzero__",
"(",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._is_level_reference | Test whether a key is a level reference for a given axis.
To be considered a level reference, `key` must be a string that:
- (axis=0): Matches the name of an index level and does NOT match
a column label.
- (axis=1): Matches the name of a column level and does NOT match
an index label.
Parameters
----------
key : str
Potential level name for the given axis
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
is_level : bool | pandas/core/generic.py | def _is_level_reference(self, key, axis=0):
"""
Test whether a key is a level reference for a given axis.
To be considered a level reference, `key` must be a string that:
- (axis=0): Matches the name of an index level and does NOT match
a column label.
- (axis=1): Matches the name of a column level and does NOT match
an index label.
Parameters
----------
key : str
Potential level name for the given axis
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
is_level : bool
"""
axis = self._get_axis_number(axis)
if self.ndim > 2:
raise NotImplementedError(
"_is_level_reference is not implemented for {type}"
.format(type=type(self)))
return (key is not None and
is_hashable(key) and
key in self.axes[axis].names and
not self._is_label_reference(key, axis=axis)) | def _is_level_reference(self, key, axis=0):
"""
Test whether a key is a level reference for a given axis.
To be considered a level reference, `key` must be a string that:
- (axis=0): Matches the name of an index level and does NOT match
a column label.
- (axis=1): Matches the name of a column level and does NOT match
an index label.
Parameters
----------
key : str
Potential level name for the given axis
axis : int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
is_level : bool
"""
axis = self._get_axis_number(axis)
if self.ndim > 2:
raise NotImplementedError(
"_is_level_reference is not implemented for {type}"
.format(type=type(self)))
return (key is not None and
is_hashable(key) and
key in self.axes[axis].names and
not self._is_label_reference(key, axis=axis)) | [
"Test",
"whether",
"a",
"key",
"is",
"a",
"level",
"reference",
"for",
"a",
"given",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1545-L1576 | [
"def",
"_is_level_reference",
"(",
"self",
",",
"key",
",",
"axis",
"=",
"0",
")",
":",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"if",
"self",
".",
"ndim",
">",
"2",
":",
"raise",
"NotImplementedError",
"(",
"\"_is_level_reference is not implemented for {type}\"",
".",
"format",
"(",
"type",
"=",
"type",
"(",
"self",
")",
")",
")",
"return",
"(",
"key",
"is",
"not",
"None",
"and",
"is_hashable",
"(",
"key",
")",
"and",
"key",
"in",
"self",
".",
"axes",
"[",
"axis",
"]",
".",
"names",
"and",
"not",
"self",
".",
"_is_label_reference",
"(",
"key",
",",
"axis",
"=",
"axis",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._is_label_reference | Test whether a key is a label reference for a given axis.
To be considered a label reference, `key` must be a string that:
- (axis=0): Matches a column label
- (axis=1): Matches an index label
Parameters
----------
key: str
Potential label name
axis: int, default 0
Axis perpendicular to the axis that labels are associated with
(0 means search for column labels, 1 means search for index labels)
Returns
-------
is_label: bool | pandas/core/generic.py | def _is_label_reference(self, key, axis=0):
"""
Test whether a key is a label reference for a given axis.
To be considered a label reference, `key` must be a string that:
- (axis=0): Matches a column label
- (axis=1): Matches an index label
Parameters
----------
key: str
Potential label name
axis: int, default 0
Axis perpendicular to the axis that labels are associated with
(0 means search for column labels, 1 means search for index labels)
Returns
-------
is_label: bool
"""
if self.ndim > 2:
raise NotImplementedError(
"_is_label_reference is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(axis)
other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis)
return (key is not None and
is_hashable(key) and
any(key in self.axes[ax] for ax in other_axes)) | def _is_label_reference(self, key, axis=0):
"""
Test whether a key is a label reference for a given axis.
To be considered a label reference, `key` must be a string that:
- (axis=0): Matches a column label
- (axis=1): Matches an index label
Parameters
----------
key: str
Potential label name
axis: int, default 0
Axis perpendicular to the axis that labels are associated with
(0 means search for column labels, 1 means search for index labels)
Returns
-------
is_label: bool
"""
if self.ndim > 2:
raise NotImplementedError(
"_is_label_reference is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(axis)
other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis)
return (key is not None and
is_hashable(key) and
any(key in self.axes[ax] for ax in other_axes)) | [
"Test",
"whether",
"a",
"key",
"is",
"a",
"label",
"reference",
"for",
"a",
"given",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1578-L1608 | [
"def",
"_is_label_reference",
"(",
"self",
",",
"key",
",",
"axis",
"=",
"0",
")",
":",
"if",
"self",
".",
"ndim",
">",
"2",
":",
"raise",
"NotImplementedError",
"(",
"\"_is_label_reference is not implemented for {type}\"",
".",
"format",
"(",
"type",
"=",
"type",
"(",
"self",
")",
")",
")",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"other_axes",
"=",
"(",
"ax",
"for",
"ax",
"in",
"range",
"(",
"self",
".",
"_AXIS_LEN",
")",
"if",
"ax",
"!=",
"axis",
")",
"return",
"(",
"key",
"is",
"not",
"None",
"and",
"is_hashable",
"(",
"key",
")",
"and",
"any",
"(",
"key",
"in",
"self",
".",
"axes",
"[",
"ax",
"]",
"for",
"ax",
"in",
"other_axes",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._is_label_or_level_reference | Test whether a key is a label or level reference for a given axis.
To be considered either a label or a level reference, `key` must be a
string that:
- (axis=0): Matches a column label or an index level
- (axis=1): Matches an index label or a column level
Parameters
----------
key: str
Potential label or level name
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
is_label_or_level: bool | pandas/core/generic.py | def _is_label_or_level_reference(self, key, axis=0):
"""
Test whether a key is a label or level reference for a given axis.
To be considered either a label or a level reference, `key` must be a
string that:
- (axis=0): Matches a column label or an index level
- (axis=1): Matches an index label or a column level
Parameters
----------
key: str
Potential label or level name
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
is_label_or_level: bool
"""
if self.ndim > 2:
raise NotImplementedError(
"_is_label_or_level_reference is not implemented for {type}"
.format(type=type(self)))
return (self._is_level_reference(key, axis=axis) or
self._is_label_reference(key, axis=axis)) | def _is_label_or_level_reference(self, key, axis=0):
"""
Test whether a key is a label or level reference for a given axis.
To be considered either a label or a level reference, `key` must be a
string that:
- (axis=0): Matches a column label or an index level
- (axis=1): Matches an index label or a column level
Parameters
----------
key: str
Potential label or level name
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
is_label_or_level: bool
"""
if self.ndim > 2:
raise NotImplementedError(
"_is_label_or_level_reference is not implemented for {type}"
.format(type=type(self)))
return (self._is_level_reference(key, axis=axis) or
self._is_label_reference(key, axis=axis)) | [
"Test",
"whether",
"a",
"key",
"is",
"a",
"label",
"or",
"level",
"reference",
"for",
"a",
"given",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1610-L1637 | [
"def",
"_is_label_or_level_reference",
"(",
"self",
",",
"key",
",",
"axis",
"=",
"0",
")",
":",
"if",
"self",
".",
"ndim",
">",
"2",
":",
"raise",
"NotImplementedError",
"(",
"\"_is_label_or_level_reference is not implemented for {type}\"",
".",
"format",
"(",
"type",
"=",
"type",
"(",
"self",
")",
")",
")",
"return",
"(",
"self",
".",
"_is_level_reference",
"(",
"key",
",",
"axis",
"=",
"axis",
")",
"or",
"self",
".",
"_is_label_reference",
"(",
"key",
",",
"axis",
"=",
"axis",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._check_label_or_level_ambiguity | Check whether `key` is ambiguous.
By ambiguous, we mean that it matches both a level of the input
`axis` and a label of the other axis.
Parameters
----------
key: str or object
label or level name
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Raises
------
ValueError: `key` is ambiguous | pandas/core/generic.py | def _check_label_or_level_ambiguity(self, key, axis=0):
"""
Check whether `key` is ambiguous.
By ambiguous, we mean that it matches both a level of the input
`axis` and a label of the other axis.
Parameters
----------
key: str or object
label or level name
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Raises
------
ValueError: `key` is ambiguous
"""
if self.ndim > 2:
raise NotImplementedError(
"_check_label_or_level_ambiguity is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(axis)
other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis)
if (key is not None and
is_hashable(key) and
key in self.axes[axis].names and
any(key in self.axes[ax] for ax in other_axes)):
# Build an informative and grammatical warning
level_article, level_type = (('an', 'index')
if axis == 0 else
('a', 'column'))
label_article, label_type = (('a', 'column')
if axis == 0 else
('an', 'index'))
msg = ("'{key}' is both {level_article} {level_type} level and "
"{label_article} {label_type} label, which is ambiguous."
).format(key=key,
level_article=level_article,
level_type=level_type,
label_article=label_article,
label_type=label_type)
raise ValueError(msg) | def _check_label_or_level_ambiguity(self, key, axis=0):
"""
Check whether `key` is ambiguous.
By ambiguous, we mean that it matches both a level of the input
`axis` and a label of the other axis.
Parameters
----------
key: str or object
label or level name
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Raises
------
ValueError: `key` is ambiguous
"""
if self.ndim > 2:
raise NotImplementedError(
"_check_label_or_level_ambiguity is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(axis)
other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis)
if (key is not None and
is_hashable(key) and
key in self.axes[axis].names and
any(key in self.axes[ax] for ax in other_axes)):
# Build an informative and grammatical warning
level_article, level_type = (('an', 'index')
if axis == 0 else
('a', 'column'))
label_article, label_type = (('a', 'column')
if axis == 0 else
('an', 'index'))
msg = ("'{key}' is both {level_article} {level_type} level and "
"{label_article} {label_type} label, which is ambiguous."
).format(key=key,
level_article=level_article,
level_type=level_type,
label_article=label_article,
label_type=label_type)
raise ValueError(msg) | [
"Check",
"whether",
"key",
"is",
"ambiguous",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1639-L1686 | [
"def",
"_check_label_or_level_ambiguity",
"(",
"self",
",",
"key",
",",
"axis",
"=",
"0",
")",
":",
"if",
"self",
".",
"ndim",
">",
"2",
":",
"raise",
"NotImplementedError",
"(",
"\"_check_label_or_level_ambiguity is not implemented for {type}\"",
".",
"format",
"(",
"type",
"=",
"type",
"(",
"self",
")",
")",
")",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"other_axes",
"=",
"(",
"ax",
"for",
"ax",
"in",
"range",
"(",
"self",
".",
"_AXIS_LEN",
")",
"if",
"ax",
"!=",
"axis",
")",
"if",
"(",
"key",
"is",
"not",
"None",
"and",
"is_hashable",
"(",
"key",
")",
"and",
"key",
"in",
"self",
".",
"axes",
"[",
"axis",
"]",
".",
"names",
"and",
"any",
"(",
"key",
"in",
"self",
".",
"axes",
"[",
"ax",
"]",
"for",
"ax",
"in",
"other_axes",
")",
")",
":",
"# Build an informative and grammatical warning",
"level_article",
",",
"level_type",
"=",
"(",
"(",
"'an'",
",",
"'index'",
")",
"if",
"axis",
"==",
"0",
"else",
"(",
"'a'",
",",
"'column'",
")",
")",
"label_article",
",",
"label_type",
"=",
"(",
"(",
"'a'",
",",
"'column'",
")",
"if",
"axis",
"==",
"0",
"else",
"(",
"'an'",
",",
"'index'",
")",
")",
"msg",
"=",
"(",
"\"'{key}' is both {level_article} {level_type} level and \"",
"\"{label_article} {label_type} label, which is ambiguous.\"",
")",
".",
"format",
"(",
"key",
"=",
"key",
",",
"level_article",
"=",
"level_article",
",",
"level_type",
"=",
"level_type",
",",
"label_article",
"=",
"label_article",
",",
"label_type",
"=",
"label_type",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._get_label_or_level_values | Return a 1-D array of values associated with `key`, a label or level
from the given `axis`.
Retrieval logic:
- (axis=0): Return column values if `key` matches a column label.
Otherwise return index level values if `key` matches an index
level.
- (axis=1): Return row values if `key` matches an index label.
Otherwise return column level values if 'key' matches a column
level
Parameters
----------
key: str
Label or level name.
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
values: np.ndarray
Raises
------
KeyError
if `key` matches neither a label nor a level
ValueError
if `key` matches multiple labels
FutureWarning
if `key` is ambiguous. This will become an ambiguity error in a
future version | pandas/core/generic.py | def _get_label_or_level_values(self, key, axis=0):
"""
Return a 1-D array of values associated with `key`, a label or level
from the given `axis`.
Retrieval logic:
- (axis=0): Return column values if `key` matches a column label.
Otherwise return index level values if `key` matches an index
level.
- (axis=1): Return row values if `key` matches an index label.
Otherwise return column level values if 'key' matches a column
level
Parameters
----------
key: str
Label or level name.
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
values: np.ndarray
Raises
------
KeyError
if `key` matches neither a label nor a level
ValueError
if `key` matches multiple labels
FutureWarning
if `key` is ambiguous. This will become an ambiguity error in a
future version
"""
if self.ndim > 2:
raise NotImplementedError(
"_get_label_or_level_values is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(axis)
other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis]
if self._is_label_reference(key, axis=axis):
self._check_label_or_level_ambiguity(key, axis=axis)
values = self.xs(key, axis=other_axes[0])._values
elif self._is_level_reference(key, axis=axis):
values = self.axes[axis].get_level_values(key)._values
else:
raise KeyError(key)
# Check for duplicates
if values.ndim > 1:
if other_axes and isinstance(
self._get_axis(other_axes[0]), MultiIndex):
multi_message = ('\n'
'For a multi-index, the label must be a '
'tuple with elements corresponding to '
'each level.')
else:
multi_message = ''
label_axis_name = 'column' if axis == 0 else 'index'
raise ValueError(("The {label_axis_name} label '{key}' "
"is not unique.{multi_message}")
.format(key=key,
label_axis_name=label_axis_name,
multi_message=multi_message))
return values | def _get_label_or_level_values(self, key, axis=0):
"""
Return a 1-D array of values associated with `key`, a label or level
from the given `axis`.
Retrieval logic:
- (axis=0): Return column values if `key` matches a column label.
Otherwise return index level values if `key` matches an index
level.
- (axis=1): Return row values if `key` matches an index label.
Otherwise return column level values if 'key' matches a column
level
Parameters
----------
key: str
Label or level name.
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
values: np.ndarray
Raises
------
KeyError
if `key` matches neither a label nor a level
ValueError
if `key` matches multiple labels
FutureWarning
if `key` is ambiguous. This will become an ambiguity error in a
future version
"""
if self.ndim > 2:
raise NotImplementedError(
"_get_label_or_level_values is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(axis)
other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis]
if self._is_label_reference(key, axis=axis):
self._check_label_or_level_ambiguity(key, axis=axis)
values = self.xs(key, axis=other_axes[0])._values
elif self._is_level_reference(key, axis=axis):
values = self.axes[axis].get_level_values(key)._values
else:
raise KeyError(key)
# Check for duplicates
if values.ndim > 1:
if other_axes and isinstance(
self._get_axis(other_axes[0]), MultiIndex):
multi_message = ('\n'
'For a multi-index, the label must be a '
'tuple with elements corresponding to '
'each level.')
else:
multi_message = ''
label_axis_name = 'column' if axis == 0 else 'index'
raise ValueError(("The {label_axis_name} label '{key}' "
"is not unique.{multi_message}")
.format(key=key,
label_axis_name=label_axis_name,
multi_message=multi_message))
return values | [
"Return",
"a",
"1",
"-",
"D",
"array",
"of",
"values",
"associated",
"with",
"key",
"a",
"label",
"or",
"level",
"from",
"the",
"given",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1688-L1757 | [
"def",
"_get_label_or_level_values",
"(",
"self",
",",
"key",
",",
"axis",
"=",
"0",
")",
":",
"if",
"self",
".",
"ndim",
">",
"2",
":",
"raise",
"NotImplementedError",
"(",
"\"_get_label_or_level_values is not implemented for {type}\"",
".",
"format",
"(",
"type",
"=",
"type",
"(",
"self",
")",
")",
")",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"other_axes",
"=",
"[",
"ax",
"for",
"ax",
"in",
"range",
"(",
"self",
".",
"_AXIS_LEN",
")",
"if",
"ax",
"!=",
"axis",
"]",
"if",
"self",
".",
"_is_label_reference",
"(",
"key",
",",
"axis",
"=",
"axis",
")",
":",
"self",
".",
"_check_label_or_level_ambiguity",
"(",
"key",
",",
"axis",
"=",
"axis",
")",
"values",
"=",
"self",
".",
"xs",
"(",
"key",
",",
"axis",
"=",
"other_axes",
"[",
"0",
"]",
")",
".",
"_values",
"elif",
"self",
".",
"_is_level_reference",
"(",
"key",
",",
"axis",
"=",
"axis",
")",
":",
"values",
"=",
"self",
".",
"axes",
"[",
"axis",
"]",
".",
"get_level_values",
"(",
"key",
")",
".",
"_values",
"else",
":",
"raise",
"KeyError",
"(",
"key",
")",
"# Check for duplicates",
"if",
"values",
".",
"ndim",
">",
"1",
":",
"if",
"other_axes",
"and",
"isinstance",
"(",
"self",
".",
"_get_axis",
"(",
"other_axes",
"[",
"0",
"]",
")",
",",
"MultiIndex",
")",
":",
"multi_message",
"=",
"(",
"'\\n'",
"'For a multi-index, the label must be a '",
"'tuple with elements corresponding to '",
"'each level.'",
")",
"else",
":",
"multi_message",
"=",
"''",
"label_axis_name",
"=",
"'column'",
"if",
"axis",
"==",
"0",
"else",
"'index'",
"raise",
"ValueError",
"(",
"(",
"\"The {label_axis_name} label '{key}' \"",
"\"is not unique.{multi_message}\"",
")",
".",
"format",
"(",
"key",
"=",
"key",
",",
"label_axis_name",
"=",
"label_axis_name",
",",
"multi_message",
"=",
"multi_message",
")",
")",
"return",
"values"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._drop_labels_or_levels | Drop labels and/or levels for the given `axis`.
For each key in `keys`:
- (axis=0): If key matches a column label then drop the column.
Otherwise if key matches an index level then drop the level.
- (axis=1): If key matches an index label then drop the row.
Otherwise if key matches a column level then drop the level.
Parameters
----------
keys: str or list of str
labels or levels to drop
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
dropped: DataFrame
Raises
------
ValueError
if any `keys` match neither a label nor a level | pandas/core/generic.py | def _drop_labels_or_levels(self, keys, axis=0):
"""
Drop labels and/or levels for the given `axis`.
For each key in `keys`:
- (axis=0): If key matches a column label then drop the column.
Otherwise if key matches an index level then drop the level.
- (axis=1): If key matches an index label then drop the row.
Otherwise if key matches a column level then drop the level.
Parameters
----------
keys: str or list of str
labels or levels to drop
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
dropped: DataFrame
Raises
------
ValueError
if any `keys` match neither a label nor a level
"""
if self.ndim > 2:
raise NotImplementedError(
"_drop_labels_or_levels is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(axis)
# Validate keys
keys = com.maybe_make_list(keys)
invalid_keys = [k for k in keys if not
self._is_label_or_level_reference(k, axis=axis)]
if invalid_keys:
raise ValueError(("The following keys are not valid labels or "
"levels for axis {axis}: {invalid_keys}")
.format(axis=axis,
invalid_keys=invalid_keys))
# Compute levels and labels to drop
levels_to_drop = [k for k in keys
if self._is_level_reference(k, axis=axis)]
labels_to_drop = [k for k in keys
if not self._is_level_reference(k, axis=axis)]
# Perform copy upfront and then use inplace operations below.
# This ensures that we always perform exactly one copy.
# ``copy`` and/or ``inplace`` options could be added in the future.
dropped = self.copy()
if axis == 0:
# Handle dropping index levels
if levels_to_drop:
dropped.reset_index(levels_to_drop, drop=True, inplace=True)
# Handle dropping columns labels
if labels_to_drop:
dropped.drop(labels_to_drop, axis=1, inplace=True)
else:
# Handle dropping column levels
if levels_to_drop:
if isinstance(dropped.columns, MultiIndex):
# Drop the specified levels from the MultiIndex
dropped.columns = dropped.columns.droplevel(levels_to_drop)
else:
# Drop the last level of Index by replacing with
# a RangeIndex
dropped.columns = RangeIndex(dropped.columns.size)
# Handle dropping index labels
if labels_to_drop:
dropped.drop(labels_to_drop, axis=0, inplace=True)
return dropped | def _drop_labels_or_levels(self, keys, axis=0):
"""
Drop labels and/or levels for the given `axis`.
For each key in `keys`:
- (axis=0): If key matches a column label then drop the column.
Otherwise if key matches an index level then drop the level.
- (axis=1): If key matches an index label then drop the row.
Otherwise if key matches a column level then drop the level.
Parameters
----------
keys: str or list of str
labels or levels to drop
axis: int, default 0
Axis that levels are associated with (0 for index, 1 for columns)
Returns
-------
dropped: DataFrame
Raises
------
ValueError
if any `keys` match neither a label nor a level
"""
if self.ndim > 2:
raise NotImplementedError(
"_drop_labels_or_levels is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(axis)
# Validate keys
keys = com.maybe_make_list(keys)
invalid_keys = [k for k in keys if not
self._is_label_or_level_reference(k, axis=axis)]
if invalid_keys:
raise ValueError(("The following keys are not valid labels or "
"levels for axis {axis}: {invalid_keys}")
.format(axis=axis,
invalid_keys=invalid_keys))
# Compute levels and labels to drop
levels_to_drop = [k for k in keys
if self._is_level_reference(k, axis=axis)]
labels_to_drop = [k for k in keys
if not self._is_level_reference(k, axis=axis)]
# Perform copy upfront and then use inplace operations below.
# This ensures that we always perform exactly one copy.
# ``copy`` and/or ``inplace`` options could be added in the future.
dropped = self.copy()
if axis == 0:
# Handle dropping index levels
if levels_to_drop:
dropped.reset_index(levels_to_drop, drop=True, inplace=True)
# Handle dropping columns labels
if labels_to_drop:
dropped.drop(labels_to_drop, axis=1, inplace=True)
else:
# Handle dropping column levels
if levels_to_drop:
if isinstance(dropped.columns, MultiIndex):
# Drop the specified levels from the MultiIndex
dropped.columns = dropped.columns.droplevel(levels_to_drop)
else:
# Drop the last level of Index by replacing with
# a RangeIndex
dropped.columns = RangeIndex(dropped.columns.size)
# Handle dropping index labels
if labels_to_drop:
dropped.drop(labels_to_drop, axis=0, inplace=True)
return dropped | [
"Drop",
"labels",
"and",
"/",
"or",
"levels",
"for",
"the",
"given",
"axis",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1759-L1838 | [
"def",
"_drop_labels_or_levels",
"(",
"self",
",",
"keys",
",",
"axis",
"=",
"0",
")",
":",
"if",
"self",
".",
"ndim",
">",
"2",
":",
"raise",
"NotImplementedError",
"(",
"\"_drop_labels_or_levels is not implemented for {type}\"",
".",
"format",
"(",
"type",
"=",
"type",
"(",
"self",
")",
")",
")",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"# Validate keys",
"keys",
"=",
"com",
".",
"maybe_make_list",
"(",
"keys",
")",
"invalid_keys",
"=",
"[",
"k",
"for",
"k",
"in",
"keys",
"if",
"not",
"self",
".",
"_is_label_or_level_reference",
"(",
"k",
",",
"axis",
"=",
"axis",
")",
"]",
"if",
"invalid_keys",
":",
"raise",
"ValueError",
"(",
"(",
"\"The following keys are not valid labels or \"",
"\"levels for axis {axis}: {invalid_keys}\"",
")",
".",
"format",
"(",
"axis",
"=",
"axis",
",",
"invalid_keys",
"=",
"invalid_keys",
")",
")",
"# Compute levels and labels to drop",
"levels_to_drop",
"=",
"[",
"k",
"for",
"k",
"in",
"keys",
"if",
"self",
".",
"_is_level_reference",
"(",
"k",
",",
"axis",
"=",
"axis",
")",
"]",
"labels_to_drop",
"=",
"[",
"k",
"for",
"k",
"in",
"keys",
"if",
"not",
"self",
".",
"_is_level_reference",
"(",
"k",
",",
"axis",
"=",
"axis",
")",
"]",
"# Perform copy upfront and then use inplace operations below.",
"# This ensures that we always perform exactly one copy.",
"# ``copy`` and/or ``inplace`` options could be added in the future.",
"dropped",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"axis",
"==",
"0",
":",
"# Handle dropping index levels",
"if",
"levels_to_drop",
":",
"dropped",
".",
"reset_index",
"(",
"levels_to_drop",
",",
"drop",
"=",
"True",
",",
"inplace",
"=",
"True",
")",
"# Handle dropping columns labels",
"if",
"labels_to_drop",
":",
"dropped",
".",
"drop",
"(",
"labels_to_drop",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
"else",
":",
"# Handle dropping column levels",
"if",
"levels_to_drop",
":",
"if",
"isinstance",
"(",
"dropped",
".",
"columns",
",",
"MultiIndex",
")",
":",
"# Drop the specified levels from the MultiIndex",
"dropped",
".",
"columns",
"=",
"dropped",
".",
"columns",
".",
"droplevel",
"(",
"levels_to_drop",
")",
"else",
":",
"# Drop the last level of Index by replacing with",
"# a RangeIndex",
"dropped",
".",
"columns",
"=",
"RangeIndex",
"(",
"dropped",
".",
"columns",
".",
"size",
")",
"# Handle dropping index labels",
"if",
"labels_to_drop",
":",
"dropped",
".",
"drop",
"(",
"labels_to_drop",
",",
"axis",
"=",
"0",
",",
"inplace",
"=",
"True",
")",
"return",
"dropped"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.empty | Indicator whether DataFrame is empty.
True if DataFrame is entirely empty (no items), meaning any of the
axes are of length 0.
Returns
-------
bool
If DataFrame is empty, return True, if not return False.
See Also
--------
Series.dropna
DataFrame.dropna
Notes
-----
If DataFrame contains only NaNs, it is still not considered empty. See
the example below.
Examples
--------
An example of an actual empty DataFrame. Notice the index is empty:
>>> df_empty = pd.DataFrame({'A' : []})
>>> df_empty
Empty DataFrame
Columns: [A]
Index: []
>>> df_empty.empty
True
If we only have NaNs in our DataFrame, it is not considered empty! We
will need to drop the NaNs to make the DataFrame empty:
>>> df = pd.DataFrame({'A' : [np.nan]})
>>> df
A
0 NaN
>>> df.empty
False
>>> df.dropna().empty
True | pandas/core/generic.py | def empty(self):
"""
Indicator whether DataFrame is empty.
True if DataFrame is entirely empty (no items), meaning any of the
axes are of length 0.
Returns
-------
bool
If DataFrame is empty, return True, if not return False.
See Also
--------
Series.dropna
DataFrame.dropna
Notes
-----
If DataFrame contains only NaNs, it is still not considered empty. See
the example below.
Examples
--------
An example of an actual empty DataFrame. Notice the index is empty:
>>> df_empty = pd.DataFrame({'A' : []})
>>> df_empty
Empty DataFrame
Columns: [A]
Index: []
>>> df_empty.empty
True
If we only have NaNs in our DataFrame, it is not considered empty! We
will need to drop the NaNs to make the DataFrame empty:
>>> df = pd.DataFrame({'A' : [np.nan]})
>>> df
A
0 NaN
>>> df.empty
False
>>> df.dropna().empty
True
"""
return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS) | def empty(self):
"""
Indicator whether DataFrame is empty.
True if DataFrame is entirely empty (no items), meaning any of the
axes are of length 0.
Returns
-------
bool
If DataFrame is empty, return True, if not return False.
See Also
--------
Series.dropna
DataFrame.dropna
Notes
-----
If DataFrame contains only NaNs, it is still not considered empty. See
the example below.
Examples
--------
An example of an actual empty DataFrame. Notice the index is empty:
>>> df_empty = pd.DataFrame({'A' : []})
>>> df_empty
Empty DataFrame
Columns: [A]
Index: []
>>> df_empty.empty
True
If we only have NaNs in our DataFrame, it is not considered empty! We
will need to drop the NaNs to make the DataFrame empty:
>>> df = pd.DataFrame({'A' : [np.nan]})
>>> df
A
0 NaN
>>> df.empty
False
>>> df.dropna().empty
True
"""
return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS) | [
"Indicator",
"whether",
"DataFrame",
"is",
"empty",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1878-L1924 | [
"def",
"empty",
"(",
"self",
")",
":",
"return",
"any",
"(",
"len",
"(",
"self",
".",
"_get_axis",
"(",
"a",
")",
")",
"==",
"0",
"for",
"a",
"in",
"self",
".",
"_AXIS_ORDERS",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._repr_data_resource_ | Not a real Jupyter special repr method, but we use the same
naming convention. | pandas/core/generic.py | def _repr_data_resource_(self):
"""
Not a real Jupyter special repr method, but we use the same
naming convention.
"""
if config.get_option("display.html.table_schema"):
data = self.head(config.get_option('display.max_rows'))
payload = json.loads(data.to_json(orient='table'),
object_pairs_hook=collections.OrderedDict)
return payload | def _repr_data_resource_(self):
"""
Not a real Jupyter special repr method, but we use the same
naming convention.
"""
if config.get_option("display.html.table_schema"):
data = self.head(config.get_option('display.max_rows'))
payload = json.loads(data.to_json(orient='table'),
object_pairs_hook=collections.OrderedDict)
return payload | [
"Not",
"a",
"real",
"Jupyter",
"special",
"repr",
"method",
"but",
"we",
"use",
"the",
"same",
"naming",
"convention",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2021-L2030 | [
"def",
"_repr_data_resource_",
"(",
"self",
")",
":",
"if",
"config",
".",
"get_option",
"(",
"\"display.html.table_schema\"",
")",
":",
"data",
"=",
"self",
".",
"head",
"(",
"config",
".",
"get_option",
"(",
"'display.max_rows'",
")",
")",
"payload",
"=",
"json",
".",
"loads",
"(",
"data",
".",
"to_json",
"(",
"orient",
"=",
"'table'",
")",
",",
"object_pairs_hook",
"=",
"collections",
".",
"OrderedDict",
")",
"return",
"payload"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_json | Convert the object to a JSON string.
Note NaN's and None will be converted to null and datetime objects
will be converted to UNIX timestamps.
Parameters
----------
path_or_buf : string or file handle, optional
File path or object. If not specified, the result is returned as
a string.
orient : string
Indication of expected JSON string format.
* Series
- default is 'index'
- allowed values are: {'split','records','index','table'}
* DataFrame
- default is 'columns'
- allowed values are:
{'split','records','index','columns','values','table'}
* The format of the JSON string
- 'split' : dict like {'index' -> [index],
'columns' -> [columns], 'data' -> [values]}
- 'records' : list like
[{column -> value}, ... , {column -> value}]
- 'index' : dict like {index -> {column -> value}}
- 'columns' : dict like {column -> {index -> value}}
- 'values' : just the values array
- 'table' : dict like {'schema': {schema}, 'data': {data}}
describing the data, and the data component is
like ``orient='records'``.
.. versionchanged:: 0.20.0
date_format : {None, 'epoch', 'iso'}
Type of date conversion. 'epoch' = epoch milliseconds,
'iso' = ISO8601. The default depends on the `orient`. For
``orient='table'``, the default is 'iso'. For all other orients,
the default is 'epoch'.
double_precision : int, default 10
The number of decimal places to use when encoding
floating point values.
force_ascii : bool, default True
Force encoded string to be ASCII.
date_unit : string, default 'ms' (milliseconds)
The time unit to encode to, governs timestamp and ISO8601
precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,
microsecond, and nanosecond respectively.
default_handler : callable, default None
Handler to call if object cannot otherwise be converted to a
suitable format for JSON. Should receive a single argument which is
the object to convert and return a serialisable object.
lines : bool, default False
If 'orient' is 'records' write out line delimited json format. Will
throw ValueError if incorrect 'orient' since others are not list
like.
.. versionadded:: 0.19.0
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}
A string representing the compression to use in the output file,
only used when the first argument is a filename. By default, the
compression is inferred from the filename.
.. versionadded:: 0.21.0
.. versionchanged:: 0.24.0
'infer' option added and set to default
index : bool, default True
Whether to include the index values in the JSON string. Not
including the index (``index=False``) is only supported when
orient is 'split' or 'table'.
.. versionadded:: 0.23.0
See Also
--------
read_json
Examples
--------
>>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
... index=['row 1', 'row 2'],
... columns=['col 1', 'col 2'])
>>> df.to_json(orient='split')
'{"columns":["col 1","col 2"],
"index":["row 1","row 2"],
"data":[["a","b"],["c","d"]]}'
Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
Note that index labels are not preserved with this encoding.
>>> df.to_json(orient='records')
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
>>> df.to_json(orient='index')
'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:
>>> df.to_json(orient='columns')
'{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'
Encoding/decoding a Dataframe using ``'values'`` formatted JSON:
>>> df.to_json(orient='values')
'[["a","b"],["c","d"]]'
Encoding with Table Schema
>>> df.to_json(orient='table')
'{"schema": {"fields": [{"name": "index", "type": "string"},
{"name": "col 1", "type": "string"},
{"name": "col 2", "type": "string"}],
"primaryKey": "index",
"pandas_version": "0.20.0"},
"data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
{"index": "row 2", "col 1": "c", "col 2": "d"}]}' | pandas/core/generic.py | def to_json(self, path_or_buf=None, orient=None, date_format=None,
double_precision=10, force_ascii=True, date_unit='ms',
default_handler=None, lines=False, compression='infer',
index=True):
"""
Convert the object to a JSON string.
Note NaN's and None will be converted to null and datetime objects
will be converted to UNIX timestamps.
Parameters
----------
path_or_buf : string or file handle, optional
File path or object. If not specified, the result is returned as
a string.
orient : string
Indication of expected JSON string format.
* Series
- default is 'index'
- allowed values are: {'split','records','index','table'}
* DataFrame
- default is 'columns'
- allowed values are:
{'split','records','index','columns','values','table'}
* The format of the JSON string
- 'split' : dict like {'index' -> [index],
'columns' -> [columns], 'data' -> [values]}
- 'records' : list like
[{column -> value}, ... , {column -> value}]
- 'index' : dict like {index -> {column -> value}}
- 'columns' : dict like {column -> {index -> value}}
- 'values' : just the values array
- 'table' : dict like {'schema': {schema}, 'data': {data}}
describing the data, and the data component is
like ``orient='records'``.
.. versionchanged:: 0.20.0
date_format : {None, 'epoch', 'iso'}
Type of date conversion. 'epoch' = epoch milliseconds,
'iso' = ISO8601. The default depends on the `orient`. For
``orient='table'``, the default is 'iso'. For all other orients,
the default is 'epoch'.
double_precision : int, default 10
The number of decimal places to use when encoding
floating point values.
force_ascii : bool, default True
Force encoded string to be ASCII.
date_unit : string, default 'ms' (milliseconds)
The time unit to encode to, governs timestamp and ISO8601
precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,
microsecond, and nanosecond respectively.
default_handler : callable, default None
Handler to call if object cannot otherwise be converted to a
suitable format for JSON. Should receive a single argument which is
the object to convert and return a serialisable object.
lines : bool, default False
If 'orient' is 'records' write out line delimited json format. Will
throw ValueError if incorrect 'orient' since others are not list
like.
.. versionadded:: 0.19.0
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}
A string representing the compression to use in the output file,
only used when the first argument is a filename. By default, the
compression is inferred from the filename.
.. versionadded:: 0.21.0
.. versionchanged:: 0.24.0
'infer' option added and set to default
index : bool, default True
Whether to include the index values in the JSON string. Not
including the index (``index=False``) is only supported when
orient is 'split' or 'table'.
.. versionadded:: 0.23.0
See Also
--------
read_json
Examples
--------
>>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
... index=['row 1', 'row 2'],
... columns=['col 1', 'col 2'])
>>> df.to_json(orient='split')
'{"columns":["col 1","col 2"],
"index":["row 1","row 2"],
"data":[["a","b"],["c","d"]]}'
Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
Note that index labels are not preserved with this encoding.
>>> df.to_json(orient='records')
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
>>> df.to_json(orient='index')
'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:
>>> df.to_json(orient='columns')
'{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'
Encoding/decoding a Dataframe using ``'values'`` formatted JSON:
>>> df.to_json(orient='values')
'[["a","b"],["c","d"]]'
Encoding with Table Schema
>>> df.to_json(orient='table')
'{"schema": {"fields": [{"name": "index", "type": "string"},
{"name": "col 1", "type": "string"},
{"name": "col 2", "type": "string"}],
"primaryKey": "index",
"pandas_version": "0.20.0"},
"data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
{"index": "row 2", "col 1": "c", "col 2": "d"}]}'
"""
from pandas.io import json
if date_format is None and orient == 'table':
date_format = 'iso'
elif date_format is None:
date_format = 'epoch'
return json.to_json(path_or_buf=path_or_buf, obj=self, orient=orient,
date_format=date_format,
double_precision=double_precision,
force_ascii=force_ascii, date_unit=date_unit,
default_handler=default_handler,
lines=lines, compression=compression,
index=index) | def to_json(self, path_or_buf=None, orient=None, date_format=None,
double_precision=10, force_ascii=True, date_unit='ms',
default_handler=None, lines=False, compression='infer',
index=True):
"""
Convert the object to a JSON string.
Note NaN's and None will be converted to null and datetime objects
will be converted to UNIX timestamps.
Parameters
----------
path_or_buf : string or file handle, optional
File path or object. If not specified, the result is returned as
a string.
orient : string
Indication of expected JSON string format.
* Series
- default is 'index'
- allowed values are: {'split','records','index','table'}
* DataFrame
- default is 'columns'
- allowed values are:
{'split','records','index','columns','values','table'}
* The format of the JSON string
- 'split' : dict like {'index' -> [index],
'columns' -> [columns], 'data' -> [values]}
- 'records' : list like
[{column -> value}, ... , {column -> value}]
- 'index' : dict like {index -> {column -> value}}
- 'columns' : dict like {column -> {index -> value}}
- 'values' : just the values array
- 'table' : dict like {'schema': {schema}, 'data': {data}}
describing the data, and the data component is
like ``orient='records'``.
.. versionchanged:: 0.20.0
date_format : {None, 'epoch', 'iso'}
Type of date conversion. 'epoch' = epoch milliseconds,
'iso' = ISO8601. The default depends on the `orient`. For
``orient='table'``, the default is 'iso'. For all other orients,
the default is 'epoch'.
double_precision : int, default 10
The number of decimal places to use when encoding
floating point values.
force_ascii : bool, default True
Force encoded string to be ASCII.
date_unit : string, default 'ms' (milliseconds)
The time unit to encode to, governs timestamp and ISO8601
precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,
microsecond, and nanosecond respectively.
default_handler : callable, default None
Handler to call if object cannot otherwise be converted to a
suitable format for JSON. Should receive a single argument which is
the object to convert and return a serialisable object.
lines : bool, default False
If 'orient' is 'records' write out line delimited json format. Will
throw ValueError if incorrect 'orient' since others are not list
like.
.. versionadded:: 0.19.0
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}
A string representing the compression to use in the output file,
only used when the first argument is a filename. By default, the
compression is inferred from the filename.
.. versionadded:: 0.21.0
.. versionchanged:: 0.24.0
'infer' option added and set to default
index : bool, default True
Whether to include the index values in the JSON string. Not
including the index (``index=False``) is only supported when
orient is 'split' or 'table'.
.. versionadded:: 0.23.0
See Also
--------
read_json
Examples
--------
>>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
... index=['row 1', 'row 2'],
... columns=['col 1', 'col 2'])
>>> df.to_json(orient='split')
'{"columns":["col 1","col 2"],
"index":["row 1","row 2"],
"data":[["a","b"],["c","d"]]}'
Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
Note that index labels are not preserved with this encoding.
>>> df.to_json(orient='records')
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
>>> df.to_json(orient='index')
'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:
>>> df.to_json(orient='columns')
'{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'
Encoding/decoding a Dataframe using ``'values'`` formatted JSON:
>>> df.to_json(orient='values')
'[["a","b"],["c","d"]]'
Encoding with Table Schema
>>> df.to_json(orient='table')
'{"schema": {"fields": [{"name": "index", "type": "string"},
{"name": "col 1", "type": "string"},
{"name": "col 2", "type": "string"}],
"primaryKey": "index",
"pandas_version": "0.20.0"},
"data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
{"index": "row 2", "col 1": "c", "col 2": "d"}]}'
"""
from pandas.io import json
if date_format is None and orient == 'table':
date_format = 'iso'
elif date_format is None:
date_format = 'epoch'
return json.to_json(path_or_buf=path_or_buf, obj=self, orient=orient,
date_format=date_format,
double_precision=double_precision,
force_ascii=force_ascii, date_unit=date_unit,
default_handler=default_handler,
lines=lines, compression=compression,
index=index) | [
"Convert",
"the",
"object",
"to",
"a",
"JSON",
"string",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2158-L2302 | [
"def",
"to_json",
"(",
"self",
",",
"path_or_buf",
"=",
"None",
",",
"orient",
"=",
"None",
",",
"date_format",
"=",
"None",
",",
"double_precision",
"=",
"10",
",",
"force_ascii",
"=",
"True",
",",
"date_unit",
"=",
"'ms'",
",",
"default_handler",
"=",
"None",
",",
"lines",
"=",
"False",
",",
"compression",
"=",
"'infer'",
",",
"index",
"=",
"True",
")",
":",
"from",
"pandas",
".",
"io",
"import",
"json",
"if",
"date_format",
"is",
"None",
"and",
"orient",
"==",
"'table'",
":",
"date_format",
"=",
"'iso'",
"elif",
"date_format",
"is",
"None",
":",
"date_format",
"=",
"'epoch'",
"return",
"json",
".",
"to_json",
"(",
"path_or_buf",
"=",
"path_or_buf",
",",
"obj",
"=",
"self",
",",
"orient",
"=",
"orient",
",",
"date_format",
"=",
"date_format",
",",
"double_precision",
"=",
"double_precision",
",",
"force_ascii",
"=",
"force_ascii",
",",
"date_unit",
"=",
"date_unit",
",",
"default_handler",
"=",
"default_handler",
",",
"lines",
"=",
"lines",
",",
"compression",
"=",
"compression",
",",
"index",
"=",
"index",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_hdf | Write the contained data to an HDF5 file using HDFStore.
Hierarchical Data Format (HDF) is self-describing, allowing an
application to interpret the structure and contents of a file with
no outside information. One HDF file can hold a mix of related objects
which can be accessed as a group or as individual objects.
In order to add another DataFrame or Series to an existing HDF file
please use append mode and a different a key.
For more information see the :ref:`user guide <io.hdf5>`.
Parameters
----------
path_or_buf : str or pandas.HDFStore
File path or HDFStore object.
key : str
Identifier for the group in the store.
mode : {'a', 'w', 'r+'}, default 'a'
Mode to open file:
- 'w': write, a new file is created (an existing file with
the same name would be deleted).
- 'a': append, an existing file is opened for reading and
writing, and if the file does not exist it is created.
- 'r+': similar to 'a', but the file must already exist.
format : {'fixed', 'table'}, default 'fixed'
Possible values:
- 'fixed': Fixed format. Fast writing/reading. Not-appendable,
nor searchable.
- 'table': Table format. Write as a PyTables Table structure
which may perform worse but allow more flexible operations
like searching / selecting subsets of the data.
append : bool, default False
For Table formats, append the input data to the existing.
data_columns : list of columns or True, optional
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See :ref:`io.hdf5-query-data-columns`.
Applicable only to format='table'.
complevel : {0-9}, optional
Specifies a compression level for data.
A value of 0 disables compression.
complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
Specifies the compression library to be used.
As of v0.20.2 these additional compressors for Blosc are supported
(default if no compressor specified: 'blosc:blosclz'):
{'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
'blosc:zlib', 'blosc:zstd'}.
Specifying a compression library which is not available issues
a ValueError.
fletcher32 : bool, default False
If applying compression use the fletcher32 checksum.
dropna : bool, default False
If true, ALL nan rows will not be written to store.
errors : str, default 'strict'
Specifies how encoding and decoding errors are to be handled.
See the errors argument for :func:`open` for a full list
of options.
See Also
--------
DataFrame.read_hdf : Read from HDF file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
DataFrame.to_sql : Write to a sql table.
DataFrame.to_feather : Write out feather-format for DataFrames.
DataFrame.to_csv : Write out to a csv file.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
... index=['a', 'b', 'c'])
>>> df.to_hdf('data.h5', key='df', mode='w')
We can add another object to the same file:
>>> s = pd.Series([1, 2, 3, 4])
>>> s.to_hdf('data.h5', key='s')
Reading from HDF file:
>>> pd.read_hdf('data.h5', 'df')
A B
a 1 4
b 2 5
c 3 6
>>> pd.read_hdf('data.h5', 's')
0 1
1 2
2 3
3 4
dtype: int64
Deleting file with data:
>>> import os
>>> os.remove('data.h5') | pandas/core/generic.py | def to_hdf(self, path_or_buf, key, **kwargs):
"""
Write the contained data to an HDF5 file using HDFStore.
Hierarchical Data Format (HDF) is self-describing, allowing an
application to interpret the structure and contents of a file with
no outside information. One HDF file can hold a mix of related objects
which can be accessed as a group or as individual objects.
In order to add another DataFrame or Series to an existing HDF file
please use append mode and a different a key.
For more information see the :ref:`user guide <io.hdf5>`.
Parameters
----------
path_or_buf : str or pandas.HDFStore
File path or HDFStore object.
key : str
Identifier for the group in the store.
mode : {'a', 'w', 'r+'}, default 'a'
Mode to open file:
- 'w': write, a new file is created (an existing file with
the same name would be deleted).
- 'a': append, an existing file is opened for reading and
writing, and if the file does not exist it is created.
- 'r+': similar to 'a', but the file must already exist.
format : {'fixed', 'table'}, default 'fixed'
Possible values:
- 'fixed': Fixed format. Fast writing/reading. Not-appendable,
nor searchable.
- 'table': Table format. Write as a PyTables Table structure
which may perform worse but allow more flexible operations
like searching / selecting subsets of the data.
append : bool, default False
For Table formats, append the input data to the existing.
data_columns : list of columns or True, optional
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See :ref:`io.hdf5-query-data-columns`.
Applicable only to format='table'.
complevel : {0-9}, optional
Specifies a compression level for data.
A value of 0 disables compression.
complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
Specifies the compression library to be used.
As of v0.20.2 these additional compressors for Blosc are supported
(default if no compressor specified: 'blosc:blosclz'):
{'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
'blosc:zlib', 'blosc:zstd'}.
Specifying a compression library which is not available issues
a ValueError.
fletcher32 : bool, default False
If applying compression use the fletcher32 checksum.
dropna : bool, default False
If true, ALL nan rows will not be written to store.
errors : str, default 'strict'
Specifies how encoding and decoding errors are to be handled.
See the errors argument for :func:`open` for a full list
of options.
See Also
--------
DataFrame.read_hdf : Read from HDF file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
DataFrame.to_sql : Write to a sql table.
DataFrame.to_feather : Write out feather-format for DataFrames.
DataFrame.to_csv : Write out to a csv file.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
... index=['a', 'b', 'c'])
>>> df.to_hdf('data.h5', key='df', mode='w')
We can add another object to the same file:
>>> s = pd.Series([1, 2, 3, 4])
>>> s.to_hdf('data.h5', key='s')
Reading from HDF file:
>>> pd.read_hdf('data.h5', 'df')
A B
a 1 4
b 2 5
c 3 6
>>> pd.read_hdf('data.h5', 's')
0 1
1 2
2 3
3 4
dtype: int64
Deleting file with data:
>>> import os
>>> os.remove('data.h5')
"""
from pandas.io import pytables
return pytables.to_hdf(path_or_buf, key, self, **kwargs) | def to_hdf(self, path_or_buf, key, **kwargs):
"""
Write the contained data to an HDF5 file using HDFStore.
Hierarchical Data Format (HDF) is self-describing, allowing an
application to interpret the structure and contents of a file with
no outside information. One HDF file can hold a mix of related objects
which can be accessed as a group or as individual objects.
In order to add another DataFrame or Series to an existing HDF file
please use append mode and a different a key.
For more information see the :ref:`user guide <io.hdf5>`.
Parameters
----------
path_or_buf : str or pandas.HDFStore
File path or HDFStore object.
key : str
Identifier for the group in the store.
mode : {'a', 'w', 'r+'}, default 'a'
Mode to open file:
- 'w': write, a new file is created (an existing file with
the same name would be deleted).
- 'a': append, an existing file is opened for reading and
writing, and if the file does not exist it is created.
- 'r+': similar to 'a', but the file must already exist.
format : {'fixed', 'table'}, default 'fixed'
Possible values:
- 'fixed': Fixed format. Fast writing/reading. Not-appendable,
nor searchable.
- 'table': Table format. Write as a PyTables Table structure
which may perform worse but allow more flexible operations
like searching / selecting subsets of the data.
append : bool, default False
For Table formats, append the input data to the existing.
data_columns : list of columns or True, optional
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See :ref:`io.hdf5-query-data-columns`.
Applicable only to format='table'.
complevel : {0-9}, optional
Specifies a compression level for data.
A value of 0 disables compression.
complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
Specifies the compression library to be used.
As of v0.20.2 these additional compressors for Blosc are supported
(default if no compressor specified: 'blosc:blosclz'):
{'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
'blosc:zlib', 'blosc:zstd'}.
Specifying a compression library which is not available issues
a ValueError.
fletcher32 : bool, default False
If applying compression use the fletcher32 checksum.
dropna : bool, default False
If true, ALL nan rows will not be written to store.
errors : str, default 'strict'
Specifies how encoding and decoding errors are to be handled.
See the errors argument for :func:`open` for a full list
of options.
See Also
--------
DataFrame.read_hdf : Read from HDF file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
DataFrame.to_sql : Write to a sql table.
DataFrame.to_feather : Write out feather-format for DataFrames.
DataFrame.to_csv : Write out to a csv file.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
... index=['a', 'b', 'c'])
>>> df.to_hdf('data.h5', key='df', mode='w')
We can add another object to the same file:
>>> s = pd.Series([1, 2, 3, 4])
>>> s.to_hdf('data.h5', key='s')
Reading from HDF file:
>>> pd.read_hdf('data.h5', 'df')
A B
a 1 4
b 2 5
c 3 6
>>> pd.read_hdf('data.h5', 's')
0 1
1 2
2 3
3 4
dtype: int64
Deleting file with data:
>>> import os
>>> os.remove('data.h5')
"""
from pandas.io import pytables
return pytables.to_hdf(path_or_buf, key, self, **kwargs) | [
"Write",
"the",
"contained",
"data",
"to",
"an",
"HDF5",
"file",
"using",
"HDFStore",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2304-L2406 | [
"def",
"to_hdf",
"(",
"self",
",",
"path_or_buf",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pandas",
".",
"io",
"import",
"pytables",
"return",
"pytables",
".",
"to_hdf",
"(",
"path_or_buf",
",",
"key",
",",
"self",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_msgpack | Serialize object to input file path using msgpack format.
THIS IS AN EXPERIMENTAL LIBRARY and the storage format
may not be stable until a future release.
Parameters
----------
path : string File path, buffer-like, or None
if None, return generated string
append : bool whether to append to an existing msgpack
(default is False)
compress : type of compressor (zlib or blosc), default to None (no
compression) | pandas/core/generic.py | def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs):
"""
Serialize object to input file path using msgpack format.
THIS IS AN EXPERIMENTAL LIBRARY and the storage format
may not be stable until a future release.
Parameters
----------
path : string File path, buffer-like, or None
if None, return generated string
append : bool whether to append to an existing msgpack
(default is False)
compress : type of compressor (zlib or blosc), default to None (no
compression)
"""
from pandas.io import packers
return packers.to_msgpack(path_or_buf, self, encoding=encoding,
**kwargs) | def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs):
"""
Serialize object to input file path using msgpack format.
THIS IS AN EXPERIMENTAL LIBRARY and the storage format
may not be stable until a future release.
Parameters
----------
path : string File path, buffer-like, or None
if None, return generated string
append : bool whether to append to an existing msgpack
(default is False)
compress : type of compressor (zlib or blosc), default to None (no
compression)
"""
from pandas.io import packers
return packers.to_msgpack(path_or_buf, self, encoding=encoding,
**kwargs) | [
"Serialize",
"object",
"to",
"input",
"file",
"path",
"using",
"msgpack",
"format",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2408-L2427 | [
"def",
"to_msgpack",
"(",
"self",
",",
"path_or_buf",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pandas",
".",
"io",
"import",
"packers",
"return",
"packers",
".",
"to_msgpack",
"(",
"path_or_buf",
",",
"self",
",",
"encoding",
"=",
"encoding",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_sql | Write records stored in a DataFrame to a SQL database.
Databases supported by SQLAlchemy [1]_ are supported. Tables can be
newly created, appended to, or overwritten.
Parameters
----------
name : string
Name of SQL table.
con : sqlalchemy.engine.Engine or sqlite3.Connection
Using SQLAlchemy makes it possible to use any DB supported by that
library. Legacy support is provided for sqlite3.Connection objects.
schema : string, optional
Specify the schema (if database flavor supports this). If None, use
default schema.
if_exists : {'fail', 'replace', 'append'}, default 'fail'
How to behave if the table already exists.
* fail: Raise a ValueError.
* replace: Drop the table before inserting new values.
* append: Insert new values to the existing table.
index : bool, default True
Write DataFrame index as a column. Uses `index_label` as the column
name in the table.
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, optional
Rows will be written in batches of this size at a time. By default,
all rows will be written at once.
dtype : dict, optional
Specifying the datatype for columns. The keys should be the column
names and the values should be the SQLAlchemy types or strings for
the sqlite3 legacy mode.
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
Raises
------
ValueError
When the table already exists and `if_exists` is 'fail' (the
default).
See Also
--------
read_sql : Read a DataFrame from a table.
Notes
-----
Timezone aware datetime columns will be written as
``Timestamp with timezone`` type with SQLAlchemy if supported by the
database. Otherwise, the datetimes will be stored as timezone unaware
timestamps local to the original timezone.
.. versionadded:: 0.24.0
References
----------
.. [1] http://docs.sqlalchemy.org
.. [2] https://www.python.org/dev/peps/pep-0249/
Examples
--------
Create an in-memory SQLite database.
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite://', echo=False)
Create a table from scratch with 3 rows.
>>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
>>> df
name
0 User 1
1 User 2
2 User 3
>>> df.to_sql('users', con=engine)
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]
>>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
>>> df1.to_sql('users', con=engine, if_exists='append')
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
(0, 'User 4'), (1, 'User 5')]
Overwrite the table with just ``df1``.
>>> df1.to_sql('users', con=engine, if_exists='replace',
... index_label='id')
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 4'), (1, 'User 5')]
Specify the dtype (especially useful for integers with missing values).
Notice that while pandas is forced to store the data as floating point,
the database supports nullable integers. When fetching the data with
Python, we get back integer scalars.
>>> df = pd.DataFrame({"A": [1, None, 2]})
>>> df
A
0 1.0
1 NaN
2 2.0
>>> from sqlalchemy.types import Integer
>>> df.to_sql('integers', con=engine, index=False,
... dtype={"A": Integer()})
>>> engine.execute("SELECT * FROM integers").fetchall()
[(1,), (None,), (2,)] | pandas/core/generic.py | def to_sql(self, 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.
Databases supported by SQLAlchemy [1]_ are supported. Tables can be
newly created, appended to, or overwritten.
Parameters
----------
name : string
Name of SQL table.
con : sqlalchemy.engine.Engine or sqlite3.Connection
Using SQLAlchemy makes it possible to use any DB supported by that
library. Legacy support is provided for sqlite3.Connection objects.
schema : string, optional
Specify the schema (if database flavor supports this). If None, use
default schema.
if_exists : {'fail', 'replace', 'append'}, default 'fail'
How to behave if the table already exists.
* fail: Raise a ValueError.
* replace: Drop the table before inserting new values.
* append: Insert new values to the existing table.
index : bool, default True
Write DataFrame index as a column. Uses `index_label` as the column
name in the table.
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, optional
Rows will be written in batches of this size at a time. By default,
all rows will be written at once.
dtype : dict, optional
Specifying the datatype for columns. The keys should be the column
names and the values should be the SQLAlchemy types or strings for
the sqlite3 legacy mode.
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
Raises
------
ValueError
When the table already exists and `if_exists` is 'fail' (the
default).
See Also
--------
read_sql : Read a DataFrame from a table.
Notes
-----
Timezone aware datetime columns will be written as
``Timestamp with timezone`` type with SQLAlchemy if supported by the
database. Otherwise, the datetimes will be stored as timezone unaware
timestamps local to the original timezone.
.. versionadded:: 0.24.0
References
----------
.. [1] http://docs.sqlalchemy.org
.. [2] https://www.python.org/dev/peps/pep-0249/
Examples
--------
Create an in-memory SQLite database.
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite://', echo=False)
Create a table from scratch with 3 rows.
>>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
>>> df
name
0 User 1
1 User 2
2 User 3
>>> df.to_sql('users', con=engine)
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]
>>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
>>> df1.to_sql('users', con=engine, if_exists='append')
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
(0, 'User 4'), (1, 'User 5')]
Overwrite the table with just ``df1``.
>>> df1.to_sql('users', con=engine, if_exists='replace',
... index_label='id')
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 4'), (1, 'User 5')]
Specify the dtype (especially useful for integers with missing values).
Notice that while pandas is forced to store the data as floating point,
the database supports nullable integers. When fetching the data with
Python, we get back integer scalars.
>>> df = pd.DataFrame({"A": [1, None, 2]})
>>> df
A
0 1.0
1 NaN
2 2.0
>>> from sqlalchemy.types import Integer
>>> df.to_sql('integers', con=engine, index=False,
... dtype={"A": Integer()})
>>> engine.execute("SELECT * FROM integers").fetchall()
[(1,), (None,), (2,)]
"""
from pandas.io import sql
sql.to_sql(self, name, con, schema=schema, if_exists=if_exists,
index=index, index_label=index_label, chunksize=chunksize,
dtype=dtype, method=method) | def to_sql(self, 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.
Databases supported by SQLAlchemy [1]_ are supported. Tables can be
newly created, appended to, or overwritten.
Parameters
----------
name : string
Name of SQL table.
con : sqlalchemy.engine.Engine or sqlite3.Connection
Using SQLAlchemy makes it possible to use any DB supported by that
library. Legacy support is provided for sqlite3.Connection objects.
schema : string, optional
Specify the schema (if database flavor supports this). If None, use
default schema.
if_exists : {'fail', 'replace', 'append'}, default 'fail'
How to behave if the table already exists.
* fail: Raise a ValueError.
* replace: Drop the table before inserting new values.
* append: Insert new values to the existing table.
index : bool, default True
Write DataFrame index as a column. Uses `index_label` as the column
name in the table.
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, optional
Rows will be written in batches of this size at a time. By default,
all rows will be written at once.
dtype : dict, optional
Specifying the datatype for columns. The keys should be the column
names and the values should be the SQLAlchemy types or strings for
the sqlite3 legacy mode.
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
Raises
------
ValueError
When the table already exists and `if_exists` is 'fail' (the
default).
See Also
--------
read_sql : Read a DataFrame from a table.
Notes
-----
Timezone aware datetime columns will be written as
``Timestamp with timezone`` type with SQLAlchemy if supported by the
database. Otherwise, the datetimes will be stored as timezone unaware
timestamps local to the original timezone.
.. versionadded:: 0.24.0
References
----------
.. [1] http://docs.sqlalchemy.org
.. [2] https://www.python.org/dev/peps/pep-0249/
Examples
--------
Create an in-memory SQLite database.
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite://', echo=False)
Create a table from scratch with 3 rows.
>>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
>>> df
name
0 User 1
1 User 2
2 User 3
>>> df.to_sql('users', con=engine)
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]
>>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})
>>> df1.to_sql('users', con=engine, if_exists='append')
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
(0, 'User 4'), (1, 'User 5')]
Overwrite the table with just ``df1``.
>>> df1.to_sql('users', con=engine, if_exists='replace',
... index_label='id')
>>> engine.execute("SELECT * FROM users").fetchall()
[(0, 'User 4'), (1, 'User 5')]
Specify the dtype (especially useful for integers with missing values).
Notice that while pandas is forced to store the data as floating point,
the database supports nullable integers. When fetching the data with
Python, we get back integer scalars.
>>> df = pd.DataFrame({"A": [1, None, 2]})
>>> df
A
0 1.0
1 NaN
2 2.0
>>> from sqlalchemy.types import Integer
>>> df.to_sql('integers', con=engine, index=False,
... dtype={"A": Integer()})
>>> engine.execute("SELECT * FROM integers").fetchall()
[(1,), (None,), (2,)]
"""
from pandas.io import sql
sql.to_sql(self, name, con, schema=schema, if_exists=if_exists,
index=index, index_label=index_label, 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/core/generic.py#L2429-L2560 | [
"def",
"to_sql",
"(",
"self",
",",
"name",
",",
"con",
",",
"schema",
"=",
"None",
",",
"if_exists",
"=",
"'fail'",
",",
"index",
"=",
"True",
",",
"index_label",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"from",
"pandas",
".",
"io",
"import",
"sql",
"sql",
".",
"to_sql",
"(",
"self",
",",
"name",
",",
"con",
",",
"schema",
"=",
"schema",
",",
"if_exists",
"=",
"if_exists",
",",
"index",
"=",
"index",
",",
"index_label",
"=",
"index_label",
",",
"chunksize",
"=",
"chunksize",
",",
"dtype",
"=",
"dtype",
",",
"method",
"=",
"method",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_pickle | Pickle (serialize) object to file.
Parameters
----------
path : str
File path where the pickled object will be stored.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \
default 'infer'
A string representing the compression to use in the output file. By
default, infers from the file extension in specified path.
.. versionadded:: 0.20.0
protocol : int
Int which indicates which protocol should be used by the pickler,
default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
values are 0, 1, 2, 3, 4. A negative value for the protocol
parameter is equivalent to setting its value to HIGHEST_PROTOCOL.
.. [1] https://docs.python.org/3/library/pickle.html
.. versionadded:: 0.21.0
See Also
--------
read_pickle : Load pickled pandas object (or any object) from file.
DataFrame.to_hdf : Write DataFrame to an HDF5 file.
DataFrame.to_sql : Write DataFrame to a SQL database.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
Examples
--------
>>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)})
>>> original_df
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> original_df.to_pickle("./dummy.pkl")
>>> unpickled_df = pd.read_pickle("./dummy.pkl")
>>> unpickled_df
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> import os
>>> os.remove("./dummy.pkl") | pandas/core/generic.py | def to_pickle(self, path, compression='infer',
protocol=pickle.HIGHEST_PROTOCOL):
"""
Pickle (serialize) object to file.
Parameters
----------
path : str
File path where the pickled object will be stored.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \
default 'infer'
A string representing the compression to use in the output file. By
default, infers from the file extension in specified path.
.. versionadded:: 0.20.0
protocol : int
Int which indicates which protocol should be used by the pickler,
default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
values are 0, 1, 2, 3, 4. A negative value for the protocol
parameter is equivalent to setting its value to HIGHEST_PROTOCOL.
.. [1] https://docs.python.org/3/library/pickle.html
.. versionadded:: 0.21.0
See Also
--------
read_pickle : Load pickled pandas object (or any object) from file.
DataFrame.to_hdf : Write DataFrame to an HDF5 file.
DataFrame.to_sql : Write DataFrame to a SQL database.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
Examples
--------
>>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)})
>>> original_df
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> original_df.to_pickle("./dummy.pkl")
>>> unpickled_df = pd.read_pickle("./dummy.pkl")
>>> unpickled_df
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> import os
>>> os.remove("./dummy.pkl")
"""
from pandas.io.pickle import to_pickle
return to_pickle(self, path, compression=compression,
protocol=protocol) | def to_pickle(self, path, compression='infer',
protocol=pickle.HIGHEST_PROTOCOL):
"""
Pickle (serialize) object to file.
Parameters
----------
path : str
File path where the pickled object will be stored.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \
default 'infer'
A string representing the compression to use in the output file. By
default, infers from the file extension in specified path.
.. versionadded:: 0.20.0
protocol : int
Int which indicates which protocol should be used by the pickler,
default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
values are 0, 1, 2, 3, 4. A negative value for the protocol
parameter is equivalent to setting its value to HIGHEST_PROTOCOL.
.. [1] https://docs.python.org/3/library/pickle.html
.. versionadded:: 0.21.0
See Also
--------
read_pickle : Load pickled pandas object (or any object) from file.
DataFrame.to_hdf : Write DataFrame to an HDF5 file.
DataFrame.to_sql : Write DataFrame to a SQL database.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
Examples
--------
>>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)})
>>> original_df
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> original_df.to_pickle("./dummy.pkl")
>>> unpickled_df = pd.read_pickle("./dummy.pkl")
>>> unpickled_df
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> import os
>>> os.remove("./dummy.pkl")
"""
from pandas.io.pickle import to_pickle
return to_pickle(self, path, compression=compression,
protocol=protocol) | [
"Pickle",
"(",
"serialize",
")",
"object",
"to",
"file",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2562-L2619 | [
"def",
"to_pickle",
"(",
"self",
",",
"path",
",",
"compression",
"=",
"'infer'",
",",
"protocol",
"=",
"pickle",
".",
"HIGHEST_PROTOCOL",
")",
":",
"from",
"pandas",
".",
"io",
".",
"pickle",
"import",
"to_pickle",
"return",
"to_pickle",
"(",
"self",
",",
"path",
",",
"compression",
"=",
"compression",
",",
"protocol",
"=",
"protocol",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_clipboard | r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
- True, use the provided separator, writing in a csv format for
allowing easy pasting into excel.
- False, write a string representation of the object to the
clipboard.
sep : str, default ``'\t'``
Field delimiter.
**kwargs
These parameters will be passed to DataFrame.to_csv.
See Also
--------
DataFrame.to_csv : Write a DataFrame to a comma-separated values
(csv) file.
read_clipboard : Read text from clipboard and pass to read_table.
Notes
-----
Requirements for your platform.
- Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules)
- Windows : none
- OS X : none
Examples
--------
Copy the contents of a DataFrame to the clipboard.
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])
>>> df.to_clipboard(sep=',')
... # Wrote the following to the system clipboard:
... # ,A,B,C
... # 0,1,2,3
... # 1,4,5,6
We can omit the the index by passing the keyword `index` and setting
it to false.
>>> df.to_clipboard(sep=',', index=False)
... # Wrote the following to the system clipboard:
... # A,B,C
... # 1,2,3
... # 4,5,6 | pandas/core/generic.py | def to_clipboard(self, excel=True, sep=None, **kwargs):
r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
- True, use the provided separator, writing in a csv format for
allowing easy pasting into excel.
- False, write a string representation of the object to the
clipboard.
sep : str, default ``'\t'``
Field delimiter.
**kwargs
These parameters will be passed to DataFrame.to_csv.
See Also
--------
DataFrame.to_csv : Write a DataFrame to a comma-separated values
(csv) file.
read_clipboard : Read text from clipboard and pass to read_table.
Notes
-----
Requirements for your platform.
- Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules)
- Windows : none
- OS X : none
Examples
--------
Copy the contents of a DataFrame to the clipboard.
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])
>>> df.to_clipboard(sep=',')
... # Wrote the following to the system clipboard:
... # ,A,B,C
... # 0,1,2,3
... # 1,4,5,6
We can omit the the index by passing the keyword `index` and setting
it to false.
>>> df.to_clipboard(sep=',', index=False)
... # Wrote the following to the system clipboard:
... # A,B,C
... # 1,2,3
... # 4,5,6
"""
from pandas.io import clipboards
clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs) | def to_clipboard(self, excel=True, sep=None, **kwargs):
r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
- True, use the provided separator, writing in a csv format for
allowing easy pasting into excel.
- False, write a string representation of the object to the
clipboard.
sep : str, default ``'\t'``
Field delimiter.
**kwargs
These parameters will be passed to DataFrame.to_csv.
See Also
--------
DataFrame.to_csv : Write a DataFrame to a comma-separated values
(csv) file.
read_clipboard : Read text from clipboard and pass to read_table.
Notes
-----
Requirements for your platform.
- Linux : `xclip`, or `xsel` (with `gtk` or `PyQt4` modules)
- Windows : none
- OS X : none
Examples
--------
Copy the contents of a DataFrame to the clipboard.
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])
>>> df.to_clipboard(sep=',')
... # Wrote the following to the system clipboard:
... # ,A,B,C
... # 0,1,2,3
... # 1,4,5,6
We can omit the the index by passing the keyword `index` and setting
it to false.
>>> df.to_clipboard(sep=',', index=False)
... # Wrote the following to the system clipboard:
... # A,B,C
... # 1,2,3
... # 4,5,6
"""
from pandas.io import clipboards
clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs) | [
"r",
"Copy",
"object",
"to",
"the",
"system",
"clipboard",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2621-L2676 | [
"def",
"to_clipboard",
"(",
"self",
",",
"excel",
"=",
"True",
",",
"sep",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pandas",
".",
"io",
"import",
"clipboards",
"clipboards",
".",
"to_clipboard",
"(",
"self",
",",
"excel",
"=",
"excel",
",",
"sep",
"=",
"sep",
",",
"*",
"*",
"kwargs",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_xarray | Return an xarray object from the pandas object.
Returns
-------
xarray.DataArray or xarray.Dataset
Data in the pandas structure converted to Dataset if the object is
a DataFrame, or a DataArray if the object is a Series.
See Also
--------
DataFrame.to_hdf : Write DataFrame to an HDF5 file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
Notes
-----
See the `xarray docs <http://xarray.pydata.org/en/stable/>`__
Examples
--------
>>> df = pd.DataFrame([('falcon', 'bird', 389.0, 2),
... ('parrot', 'bird', 24.0, 2),
... ('lion', 'mammal', 80.5, 4),
... ('monkey', 'mammal', np.nan, 4)],
... columns=['name', 'class', 'max_speed',
... 'num_legs'])
>>> df
name class max_speed num_legs
0 falcon bird 389.0 2
1 parrot bird 24.0 2
2 lion mammal 80.5 4
3 monkey mammal NaN 4
>>> df.to_xarray()
<xarray.Dataset>
Dimensions: (index: 4)
Coordinates:
* index (index) int64 0 1 2 3
Data variables:
name (index) object 'falcon' 'parrot' 'lion' 'monkey'
class (index) object 'bird' 'bird' 'mammal' 'mammal'
max_speed (index) float64 389.0 24.0 80.5 nan
num_legs (index) int64 2 2 4 4
>>> df['max_speed'].to_xarray()
<xarray.DataArray 'max_speed' (index: 4)>
array([389. , 24. , 80.5, nan])
Coordinates:
* index (index) int64 0 1 2 3
>>> dates = pd.to_datetime(['2018-01-01', '2018-01-01',
... '2018-01-02', '2018-01-02'])
>>> df_multiindex = pd.DataFrame({'date': dates,
... 'animal': ['falcon', 'parrot', 'falcon',
... 'parrot'],
... 'speed': [350, 18, 361, 15]}).set_index(['date',
... 'animal'])
>>> df_multiindex
speed
date animal
2018-01-01 falcon 350
parrot 18
2018-01-02 falcon 361
parrot 15
>>> df_multiindex.to_xarray()
<xarray.Dataset>
Dimensions: (animal: 2, date: 2)
Coordinates:
* date (date) datetime64[ns] 2018-01-01 2018-01-02
* animal (animal) object 'falcon' 'parrot'
Data variables:
speed (date, animal) int64 350 18 361 15 | pandas/core/generic.py | def to_xarray(self):
"""
Return an xarray object from the pandas object.
Returns
-------
xarray.DataArray or xarray.Dataset
Data in the pandas structure converted to Dataset if the object is
a DataFrame, or a DataArray if the object is a Series.
See Also
--------
DataFrame.to_hdf : Write DataFrame to an HDF5 file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
Notes
-----
See the `xarray docs <http://xarray.pydata.org/en/stable/>`__
Examples
--------
>>> df = pd.DataFrame([('falcon', 'bird', 389.0, 2),
... ('parrot', 'bird', 24.0, 2),
... ('lion', 'mammal', 80.5, 4),
... ('monkey', 'mammal', np.nan, 4)],
... columns=['name', 'class', 'max_speed',
... 'num_legs'])
>>> df
name class max_speed num_legs
0 falcon bird 389.0 2
1 parrot bird 24.0 2
2 lion mammal 80.5 4
3 monkey mammal NaN 4
>>> df.to_xarray()
<xarray.Dataset>
Dimensions: (index: 4)
Coordinates:
* index (index) int64 0 1 2 3
Data variables:
name (index) object 'falcon' 'parrot' 'lion' 'monkey'
class (index) object 'bird' 'bird' 'mammal' 'mammal'
max_speed (index) float64 389.0 24.0 80.5 nan
num_legs (index) int64 2 2 4 4
>>> df['max_speed'].to_xarray()
<xarray.DataArray 'max_speed' (index: 4)>
array([389. , 24. , 80.5, nan])
Coordinates:
* index (index) int64 0 1 2 3
>>> dates = pd.to_datetime(['2018-01-01', '2018-01-01',
... '2018-01-02', '2018-01-02'])
>>> df_multiindex = pd.DataFrame({'date': dates,
... 'animal': ['falcon', 'parrot', 'falcon',
... 'parrot'],
... 'speed': [350, 18, 361, 15]}).set_index(['date',
... 'animal'])
>>> df_multiindex
speed
date animal
2018-01-01 falcon 350
parrot 18
2018-01-02 falcon 361
parrot 15
>>> df_multiindex.to_xarray()
<xarray.Dataset>
Dimensions: (animal: 2, date: 2)
Coordinates:
* date (date) datetime64[ns] 2018-01-01 2018-01-02
* animal (animal) object 'falcon' 'parrot'
Data variables:
speed (date, animal) int64 350 18 361 15
"""
try:
import xarray
except ImportError:
# Give a nice error message
raise ImportError("the xarray library is not installed\n"
"you can install via conda\n"
"conda install xarray\n"
"or via pip\n"
"pip install xarray\n")
if self.ndim == 1:
return xarray.DataArray.from_series(self)
elif self.ndim == 2:
return xarray.Dataset.from_dataframe(self)
# > 2 dims
coords = [(a, self._get_axis(a)) for a in self._AXIS_ORDERS]
return xarray.DataArray(self,
coords=coords,
) | def to_xarray(self):
"""
Return an xarray object from the pandas object.
Returns
-------
xarray.DataArray or xarray.Dataset
Data in the pandas structure converted to Dataset if the object is
a DataFrame, or a DataArray if the object is a Series.
See Also
--------
DataFrame.to_hdf : Write DataFrame to an HDF5 file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
Notes
-----
See the `xarray docs <http://xarray.pydata.org/en/stable/>`__
Examples
--------
>>> df = pd.DataFrame([('falcon', 'bird', 389.0, 2),
... ('parrot', 'bird', 24.0, 2),
... ('lion', 'mammal', 80.5, 4),
... ('monkey', 'mammal', np.nan, 4)],
... columns=['name', 'class', 'max_speed',
... 'num_legs'])
>>> df
name class max_speed num_legs
0 falcon bird 389.0 2
1 parrot bird 24.0 2
2 lion mammal 80.5 4
3 monkey mammal NaN 4
>>> df.to_xarray()
<xarray.Dataset>
Dimensions: (index: 4)
Coordinates:
* index (index) int64 0 1 2 3
Data variables:
name (index) object 'falcon' 'parrot' 'lion' 'monkey'
class (index) object 'bird' 'bird' 'mammal' 'mammal'
max_speed (index) float64 389.0 24.0 80.5 nan
num_legs (index) int64 2 2 4 4
>>> df['max_speed'].to_xarray()
<xarray.DataArray 'max_speed' (index: 4)>
array([389. , 24. , 80.5, nan])
Coordinates:
* index (index) int64 0 1 2 3
>>> dates = pd.to_datetime(['2018-01-01', '2018-01-01',
... '2018-01-02', '2018-01-02'])
>>> df_multiindex = pd.DataFrame({'date': dates,
... 'animal': ['falcon', 'parrot', 'falcon',
... 'parrot'],
... 'speed': [350, 18, 361, 15]}).set_index(['date',
... 'animal'])
>>> df_multiindex
speed
date animal
2018-01-01 falcon 350
parrot 18
2018-01-02 falcon 361
parrot 15
>>> df_multiindex.to_xarray()
<xarray.Dataset>
Dimensions: (animal: 2, date: 2)
Coordinates:
* date (date) datetime64[ns] 2018-01-01 2018-01-02
* animal (animal) object 'falcon' 'parrot'
Data variables:
speed (date, animal) int64 350 18 361 15
"""
try:
import xarray
except ImportError:
# Give a nice error message
raise ImportError("the xarray library is not installed\n"
"you can install via conda\n"
"conda install xarray\n"
"or via pip\n"
"pip install xarray\n")
if self.ndim == 1:
return xarray.DataArray.from_series(self)
elif self.ndim == 2:
return xarray.Dataset.from_dataframe(self)
# > 2 dims
coords = [(a, self._get_axis(a)) for a in self._AXIS_ORDERS]
return xarray.DataArray(self,
coords=coords,
) | [
"Return",
"an",
"xarray",
"object",
"from",
"the",
"pandas",
"object",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2678-L2773 | [
"def",
"to_xarray",
"(",
"self",
")",
":",
"try",
":",
"import",
"xarray",
"except",
"ImportError",
":",
"# Give a nice error message",
"raise",
"ImportError",
"(",
"\"the xarray library is not installed\\n\"",
"\"you can install via conda\\n\"",
"\"conda install xarray\\n\"",
"\"or via pip\\n\"",
"\"pip install xarray\\n\"",
")",
"if",
"self",
".",
"ndim",
"==",
"1",
":",
"return",
"xarray",
".",
"DataArray",
".",
"from_series",
"(",
"self",
")",
"elif",
"self",
".",
"ndim",
"==",
"2",
":",
"return",
"xarray",
".",
"Dataset",
".",
"from_dataframe",
"(",
"self",
")",
"# > 2 dims",
"coords",
"=",
"[",
"(",
"a",
",",
"self",
".",
"_get_axis",
"(",
"a",
")",
")",
"for",
"a",
"in",
"self",
".",
"_AXIS_ORDERS",
"]",
"return",
"xarray",
".",
"DataArray",
"(",
"self",
",",
"coords",
"=",
"coords",
",",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_latex | r"""
Render an object to a LaTeX tabular environment table.
Render an object to a tabular environment table. You can splice
this into a LaTeX document. Requires \usepackage{booktabs}.
.. versionchanged:: 0.20.2
Added to Series
Parameters
----------
buf : file descriptor or None
Buffer to write to. If None, the output is returned as a string.
columns : list of label, optional
The subset of columns to write. Writes all columns by default.
col_space : int, optional
The minimum width of each column.
header : bool or list of str, default True
Write out the column names. If a list of strings is given,
it is assumed to be aliases for the column names.
index : bool, default True
Write row names (index).
na_rep : str, default 'NaN'
Missing data representation.
formatters : list of functions or dict of {str: function}, optional
Formatter functions to apply to columns' elements by position or
name. The result of each function must be a unicode string.
List must be of length equal to the number of columns.
float_format : str, optional
Format string for floating point numbers.
sparsify : bool, optional
Set to False for a DataFrame with a hierarchical index to print
every multiindex key at each row. By default, the value will be
read from the config module.
index_names : bool, default True
Prints the names of the indexes.
bold_rows : bool, default False
Make the row labels bold in the output.
column_format : str, optional
The columns format as specified in `LaTeX table format
<https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3
columns. By default, 'l' will be used for all columns except
columns of numbers, which default to 'r'.
longtable : bool, optional
By default, the value will be read from the pandas config
module. Use a longtable environment instead of tabular. Requires
adding a \usepackage{longtable} to your LaTeX preamble.
escape : bool, optional
By default, the value will be read from the pandas config
module. When set to False prevents from escaping latex special
characters in column names.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'utf-8'.
decimal : str, default '.'
Character recognized as decimal separator, e.g. ',' in Europe.
.. versionadded:: 0.18.0
multicolumn : bool, default True
Use \multicolumn to enhance MultiIndex columns.
The default will be read from the config module.
.. versionadded:: 0.20.0
multicolumn_format : str, default 'l'
The alignment for multicolumns, similar to `column_format`
The default will be read from the config module.
.. versionadded:: 0.20.0
multirow : bool, default False
Use \multirow to enhance MultiIndex rows. Requires adding a
\usepackage{multirow} to your LaTeX preamble. Will print
centered labels (instead of top-aligned) across the contained
rows, separating groups via clines. The default will be read
from the pandas config module.
.. versionadded:: 0.20.0
Returns
-------
str or None
If buf is None, returns the resulting LateX format as a
string. Otherwise returns None.
See Also
--------
DataFrame.to_string : Render a DataFrame to a console-friendly
tabular output.
DataFrame.to_html : Render a DataFrame as an HTML table.
Examples
--------
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
... 'mask': ['red', 'purple'],
... 'weapon': ['sai', 'bo staff']})
>>> df.to_latex(index=False) # doctest: +NORMALIZE_WHITESPACE
'\\begin{tabular}{lll}\n\\toprule\n name & mask & weapon
\\\\\n\\midrule\n Raphael & red & sai \\\\\n Donatello &
purple & bo staff \\\\\n\\bottomrule\n\\end{tabular}\n' | pandas/core/generic.py | def to_latex(self, buf=None, columns=None, col_space=None, header=True,
index=True, na_rep='NaN', formatters=None, float_format=None,
sparsify=None, index_names=True, bold_rows=False,
column_format=None, longtable=None, escape=None,
encoding=None, decimal='.', multicolumn=None,
multicolumn_format=None, multirow=None):
r"""
Render an object to a LaTeX tabular environment table.
Render an object to a tabular environment table. You can splice
this into a LaTeX document. Requires \usepackage{booktabs}.
.. versionchanged:: 0.20.2
Added to Series
Parameters
----------
buf : file descriptor or None
Buffer to write to. If None, the output is returned as a string.
columns : list of label, optional
The subset of columns to write. Writes all columns by default.
col_space : int, optional
The minimum width of each column.
header : bool or list of str, default True
Write out the column names. If a list of strings is given,
it is assumed to be aliases for the column names.
index : bool, default True
Write row names (index).
na_rep : str, default 'NaN'
Missing data representation.
formatters : list of functions or dict of {str: function}, optional
Formatter functions to apply to columns' elements by position or
name. The result of each function must be a unicode string.
List must be of length equal to the number of columns.
float_format : str, optional
Format string for floating point numbers.
sparsify : bool, optional
Set to False for a DataFrame with a hierarchical index to print
every multiindex key at each row. By default, the value will be
read from the config module.
index_names : bool, default True
Prints the names of the indexes.
bold_rows : bool, default False
Make the row labels bold in the output.
column_format : str, optional
The columns format as specified in `LaTeX table format
<https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3
columns. By default, 'l' will be used for all columns except
columns of numbers, which default to 'r'.
longtable : bool, optional
By default, the value will be read from the pandas config
module. Use a longtable environment instead of tabular. Requires
adding a \usepackage{longtable} to your LaTeX preamble.
escape : bool, optional
By default, the value will be read from the pandas config
module. When set to False prevents from escaping latex special
characters in column names.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'utf-8'.
decimal : str, default '.'
Character recognized as decimal separator, e.g. ',' in Europe.
.. versionadded:: 0.18.0
multicolumn : bool, default True
Use \multicolumn to enhance MultiIndex columns.
The default will be read from the config module.
.. versionadded:: 0.20.0
multicolumn_format : str, default 'l'
The alignment for multicolumns, similar to `column_format`
The default will be read from the config module.
.. versionadded:: 0.20.0
multirow : bool, default False
Use \multirow to enhance MultiIndex rows. Requires adding a
\usepackage{multirow} to your LaTeX preamble. Will print
centered labels (instead of top-aligned) across the contained
rows, separating groups via clines. The default will be read
from the pandas config module.
.. versionadded:: 0.20.0
Returns
-------
str or None
If buf is None, returns the resulting LateX format as a
string. Otherwise returns None.
See Also
--------
DataFrame.to_string : Render a DataFrame to a console-friendly
tabular output.
DataFrame.to_html : Render a DataFrame as an HTML table.
Examples
--------
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
... 'mask': ['red', 'purple'],
... 'weapon': ['sai', 'bo staff']})
>>> df.to_latex(index=False) # doctest: +NORMALIZE_WHITESPACE
'\\begin{tabular}{lll}\n\\toprule\n name & mask & weapon
\\\\\n\\midrule\n Raphael & red & sai \\\\\n Donatello &
purple & bo staff \\\\\n\\bottomrule\n\\end{tabular}\n'
"""
# Get defaults from the pandas config
if self.ndim == 1:
self = self.to_frame()
if longtable is None:
longtable = config.get_option("display.latex.longtable")
if escape is None:
escape = config.get_option("display.latex.escape")
if multicolumn is None:
multicolumn = config.get_option("display.latex.multicolumn")
if multicolumn_format is None:
multicolumn_format = config.get_option(
"display.latex.multicolumn_format")
if multirow is None:
multirow = config.get_option("display.latex.multirow")
formatter = DataFrameFormatter(self, buf=buf, columns=columns,
col_space=col_space, na_rep=na_rep,
header=header, index=index,
formatters=formatters,
float_format=float_format,
bold_rows=bold_rows,
sparsify=sparsify,
index_names=index_names,
escape=escape, decimal=decimal)
formatter.to_latex(column_format=column_format, longtable=longtable,
encoding=encoding, multicolumn=multicolumn,
multicolumn_format=multicolumn_format,
multirow=multirow)
if buf is None:
return formatter.buf.getvalue() | def to_latex(self, buf=None, columns=None, col_space=None, header=True,
index=True, na_rep='NaN', formatters=None, float_format=None,
sparsify=None, index_names=True, bold_rows=False,
column_format=None, longtable=None, escape=None,
encoding=None, decimal='.', multicolumn=None,
multicolumn_format=None, multirow=None):
r"""
Render an object to a LaTeX tabular environment table.
Render an object to a tabular environment table. You can splice
this into a LaTeX document. Requires \usepackage{booktabs}.
.. versionchanged:: 0.20.2
Added to Series
Parameters
----------
buf : file descriptor or None
Buffer to write to. If None, the output is returned as a string.
columns : list of label, optional
The subset of columns to write. Writes all columns by default.
col_space : int, optional
The minimum width of each column.
header : bool or list of str, default True
Write out the column names. If a list of strings is given,
it is assumed to be aliases for the column names.
index : bool, default True
Write row names (index).
na_rep : str, default 'NaN'
Missing data representation.
formatters : list of functions or dict of {str: function}, optional
Formatter functions to apply to columns' elements by position or
name. The result of each function must be a unicode string.
List must be of length equal to the number of columns.
float_format : str, optional
Format string for floating point numbers.
sparsify : bool, optional
Set to False for a DataFrame with a hierarchical index to print
every multiindex key at each row. By default, the value will be
read from the config module.
index_names : bool, default True
Prints the names of the indexes.
bold_rows : bool, default False
Make the row labels bold in the output.
column_format : str, optional
The columns format as specified in `LaTeX table format
<https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3
columns. By default, 'l' will be used for all columns except
columns of numbers, which default to 'r'.
longtable : bool, optional
By default, the value will be read from the pandas config
module. Use a longtable environment instead of tabular. Requires
adding a \usepackage{longtable} to your LaTeX preamble.
escape : bool, optional
By default, the value will be read from the pandas config
module. When set to False prevents from escaping latex special
characters in column names.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'utf-8'.
decimal : str, default '.'
Character recognized as decimal separator, e.g. ',' in Europe.
.. versionadded:: 0.18.0
multicolumn : bool, default True
Use \multicolumn to enhance MultiIndex columns.
The default will be read from the config module.
.. versionadded:: 0.20.0
multicolumn_format : str, default 'l'
The alignment for multicolumns, similar to `column_format`
The default will be read from the config module.
.. versionadded:: 0.20.0
multirow : bool, default False
Use \multirow to enhance MultiIndex rows. Requires adding a
\usepackage{multirow} to your LaTeX preamble. Will print
centered labels (instead of top-aligned) across the contained
rows, separating groups via clines. The default will be read
from the pandas config module.
.. versionadded:: 0.20.0
Returns
-------
str or None
If buf is None, returns the resulting LateX format as a
string. Otherwise returns None.
See Also
--------
DataFrame.to_string : Render a DataFrame to a console-friendly
tabular output.
DataFrame.to_html : Render a DataFrame as an HTML table.
Examples
--------
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
... 'mask': ['red', 'purple'],
... 'weapon': ['sai', 'bo staff']})
>>> df.to_latex(index=False) # doctest: +NORMALIZE_WHITESPACE
'\\begin{tabular}{lll}\n\\toprule\n name & mask & weapon
\\\\\n\\midrule\n Raphael & red & sai \\\\\n Donatello &
purple & bo staff \\\\\n\\bottomrule\n\\end{tabular}\n'
"""
# Get defaults from the pandas config
if self.ndim == 1:
self = self.to_frame()
if longtable is None:
longtable = config.get_option("display.latex.longtable")
if escape is None:
escape = config.get_option("display.latex.escape")
if multicolumn is None:
multicolumn = config.get_option("display.latex.multicolumn")
if multicolumn_format is None:
multicolumn_format = config.get_option(
"display.latex.multicolumn_format")
if multirow is None:
multirow = config.get_option("display.latex.multirow")
formatter = DataFrameFormatter(self, buf=buf, columns=columns,
col_space=col_space, na_rep=na_rep,
header=header, index=index,
formatters=formatters,
float_format=float_format,
bold_rows=bold_rows,
sparsify=sparsify,
index_names=index_names,
escape=escape, decimal=decimal)
formatter.to_latex(column_format=column_format, longtable=longtable,
encoding=encoding, multicolumn=multicolumn,
multicolumn_format=multicolumn_format,
multirow=multirow)
if buf is None:
return formatter.buf.getvalue() | [
"r",
"Render",
"an",
"object",
"to",
"a",
"LaTeX",
"tabular",
"environment",
"table",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2775-L2910 | [
"def",
"to_latex",
"(",
"self",
",",
"buf",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"col_space",
"=",
"None",
",",
"header",
"=",
"True",
",",
"index",
"=",
"True",
",",
"na_rep",
"=",
"'NaN'",
",",
"formatters",
"=",
"None",
",",
"float_format",
"=",
"None",
",",
"sparsify",
"=",
"None",
",",
"index_names",
"=",
"True",
",",
"bold_rows",
"=",
"False",
",",
"column_format",
"=",
"None",
",",
"longtable",
"=",
"None",
",",
"escape",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"decimal",
"=",
"'.'",
",",
"multicolumn",
"=",
"None",
",",
"multicolumn_format",
"=",
"None",
",",
"multirow",
"=",
"None",
")",
":",
"# Get defaults from the pandas config",
"if",
"self",
".",
"ndim",
"==",
"1",
":",
"self",
"=",
"self",
".",
"to_frame",
"(",
")",
"if",
"longtable",
"is",
"None",
":",
"longtable",
"=",
"config",
".",
"get_option",
"(",
"\"display.latex.longtable\"",
")",
"if",
"escape",
"is",
"None",
":",
"escape",
"=",
"config",
".",
"get_option",
"(",
"\"display.latex.escape\"",
")",
"if",
"multicolumn",
"is",
"None",
":",
"multicolumn",
"=",
"config",
".",
"get_option",
"(",
"\"display.latex.multicolumn\"",
")",
"if",
"multicolumn_format",
"is",
"None",
":",
"multicolumn_format",
"=",
"config",
".",
"get_option",
"(",
"\"display.latex.multicolumn_format\"",
")",
"if",
"multirow",
"is",
"None",
":",
"multirow",
"=",
"config",
".",
"get_option",
"(",
"\"display.latex.multirow\"",
")",
"formatter",
"=",
"DataFrameFormatter",
"(",
"self",
",",
"buf",
"=",
"buf",
",",
"columns",
"=",
"columns",
",",
"col_space",
"=",
"col_space",
",",
"na_rep",
"=",
"na_rep",
",",
"header",
"=",
"header",
",",
"index",
"=",
"index",
",",
"formatters",
"=",
"formatters",
",",
"float_format",
"=",
"float_format",
",",
"bold_rows",
"=",
"bold_rows",
",",
"sparsify",
"=",
"sparsify",
",",
"index_names",
"=",
"index_names",
",",
"escape",
"=",
"escape",
",",
"decimal",
"=",
"decimal",
")",
"formatter",
".",
"to_latex",
"(",
"column_format",
"=",
"column_format",
",",
"longtable",
"=",
"longtable",
",",
"encoding",
"=",
"encoding",
",",
"multicolumn",
"=",
"multicolumn",
",",
"multicolumn_format",
"=",
"multicolumn_format",
",",
"multirow",
"=",
"multirow",
")",
"if",
"buf",
"is",
"None",
":",
"return",
"formatter",
".",
"buf",
".",
"getvalue",
"(",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame.to_csv | r"""
Write object to a comma-separated values (csv) file.
.. versionchanged:: 0.24.0
The order of arguments for Series was changed.
Parameters
----------
path_or_buf : str or file handle, default None
File path or object, if None is provided the result is returned as
a string. If a file object is passed it should be opened with
`newline=''`, disabling universal newlines.
.. versionchanged:: 0.24.0
Was previously named "path" for Series.
sep : str, default ','
String of length 1. Field delimiter for the output file.
na_rep : str, default ''
Missing data representation.
float_format : str, default None
Format string for floating point numbers.
columns : sequence, optional
Columns to write.
header : bool or list of str, default True
Write out the column names. If a list of strings is given it is
assumed to be aliases for the column names.
.. versionchanged:: 0.24.0
Previously defaulted to False for Series.
index : bool, default True
Write row names (index).
index_label : str or sequence, or False, default None
Column label for index column(s) if desired. If None is given, and
`header` and `index` are True, then the index names are used. A
sequence should be given if the object uses MultiIndex. If
False do not print fields for index names. Use index_label=False
for easier importing in R.
mode : str
Python write mode, default 'w'.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'utf-8'.
compression : str, default 'infer'
Compression mode among the following possible values: {'infer',
'gzip', 'bz2', 'zip', 'xz', None}. If 'infer' and `path_or_buf`
is path-like, then detect compression from the following
extensions: '.gz', '.bz2', '.zip' or '.xz'. (otherwise no
compression).
.. versionchanged:: 0.24.0
'infer' option added and set to default.
quoting : optional constant from csv module
Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`
then floats are converted to strings and thus csv.QUOTE_NONNUMERIC
will treat them as non-numeric.
quotechar : str, default '\"'
String of length 1. Character used to quote fields.
line_terminator : str, optional
The newline character or character sequence to use in the output
file. Defaults to `os.linesep`, which depends on the OS in which
this method is called ('\n' for linux, '\r\n' for Windows, i.e.).
.. versionchanged:: 0.24.0
chunksize : int or None
Rows to write at a time.
tupleize_cols : bool, default False
Write MultiIndex columns as a list of tuples (if True) or in
the new, expanded format, where each MultiIndex column is a row
in the CSV (if False).
.. deprecated:: 0.21.0
This argument will be removed and will always write each row
of the multi-index as a separate row in the CSV file.
date_format : str, default None
Format string for datetime objects.
doublequote : bool, default True
Control quoting of `quotechar` inside a field.
escapechar : str, default None
String of length 1. Character used to escape `sep` and `quotechar`
when appropriate.
decimal : str, default '.'
Character recognized as decimal separator. E.g. use ',' for
European data.
Returns
-------
None or str
If path_or_buf is None, returns the resulting csv format as a
string. Otherwise returns None.
See Also
--------
read_csv : Load a CSV file into a DataFrame.
to_excel : Write DataFrame to an Excel file.
Examples
--------
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
... 'mask': ['red', 'purple'],
... 'weapon': ['sai', 'bo staff']})
>>> df.to_csv(index=False)
'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n' | pandas/core/generic.py | def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
columns=None, header=True, index=True, index_label=None,
mode='w', encoding=None, compression='infer', quoting=None,
quotechar='"', line_terminator=None, chunksize=None,
tupleize_cols=None, date_format=None, doublequote=True,
escapechar=None, decimal='.'):
r"""
Write object to a comma-separated values (csv) file.
.. versionchanged:: 0.24.0
The order of arguments for Series was changed.
Parameters
----------
path_or_buf : str or file handle, default None
File path or object, if None is provided the result is returned as
a string. If a file object is passed it should be opened with
`newline=''`, disabling universal newlines.
.. versionchanged:: 0.24.0
Was previously named "path" for Series.
sep : str, default ','
String of length 1. Field delimiter for the output file.
na_rep : str, default ''
Missing data representation.
float_format : str, default None
Format string for floating point numbers.
columns : sequence, optional
Columns to write.
header : bool or list of str, default True
Write out the column names. If a list of strings is given it is
assumed to be aliases for the column names.
.. versionchanged:: 0.24.0
Previously defaulted to False for Series.
index : bool, default True
Write row names (index).
index_label : str or sequence, or False, default None
Column label for index column(s) if desired. If None is given, and
`header` and `index` are True, then the index names are used. A
sequence should be given if the object uses MultiIndex. If
False do not print fields for index names. Use index_label=False
for easier importing in R.
mode : str
Python write mode, default 'w'.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'utf-8'.
compression : str, default 'infer'
Compression mode among the following possible values: {'infer',
'gzip', 'bz2', 'zip', 'xz', None}. If 'infer' and `path_or_buf`
is path-like, then detect compression from the following
extensions: '.gz', '.bz2', '.zip' or '.xz'. (otherwise no
compression).
.. versionchanged:: 0.24.0
'infer' option added and set to default.
quoting : optional constant from csv module
Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`
then floats are converted to strings and thus csv.QUOTE_NONNUMERIC
will treat them as non-numeric.
quotechar : str, default '\"'
String of length 1. Character used to quote fields.
line_terminator : str, optional
The newline character or character sequence to use in the output
file. Defaults to `os.linesep`, which depends on the OS in which
this method is called ('\n' for linux, '\r\n' for Windows, i.e.).
.. versionchanged:: 0.24.0
chunksize : int or None
Rows to write at a time.
tupleize_cols : bool, default False
Write MultiIndex columns as a list of tuples (if True) or in
the new, expanded format, where each MultiIndex column is a row
in the CSV (if False).
.. deprecated:: 0.21.0
This argument will be removed and will always write each row
of the multi-index as a separate row in the CSV file.
date_format : str, default None
Format string for datetime objects.
doublequote : bool, default True
Control quoting of `quotechar` inside a field.
escapechar : str, default None
String of length 1. Character used to escape `sep` and `quotechar`
when appropriate.
decimal : str, default '.'
Character recognized as decimal separator. E.g. use ',' for
European data.
Returns
-------
None or str
If path_or_buf is None, returns the resulting csv format as a
string. Otherwise returns None.
See Also
--------
read_csv : Load a CSV file into a DataFrame.
to_excel : Write DataFrame to an Excel file.
Examples
--------
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
... 'mask': ['red', 'purple'],
... 'weapon': ['sai', 'bo staff']})
>>> df.to_csv(index=False)
'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
"""
df = self if isinstance(self, ABCDataFrame) else self.to_frame()
if tupleize_cols is not None:
warnings.warn("The 'tupleize_cols' parameter is deprecated and "
"will be removed in a future version",
FutureWarning, stacklevel=2)
else:
tupleize_cols = False
from pandas.io.formats.csvs import CSVFormatter
formatter = CSVFormatter(df, path_or_buf,
line_terminator=line_terminator, sep=sep,
encoding=encoding,
compression=compression, quoting=quoting,
na_rep=na_rep, float_format=float_format,
cols=columns, header=header, index=index,
index_label=index_label, mode=mode,
chunksize=chunksize, quotechar=quotechar,
tupleize_cols=tupleize_cols,
date_format=date_format,
doublequote=doublequote,
escapechar=escapechar, decimal=decimal)
formatter.save()
if path_or_buf is None:
return formatter.path_or_buf.getvalue() | def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
columns=None, header=True, index=True, index_label=None,
mode='w', encoding=None, compression='infer', quoting=None,
quotechar='"', line_terminator=None, chunksize=None,
tupleize_cols=None, date_format=None, doublequote=True,
escapechar=None, decimal='.'):
r"""
Write object to a comma-separated values (csv) file.
.. versionchanged:: 0.24.0
The order of arguments for Series was changed.
Parameters
----------
path_or_buf : str or file handle, default None
File path or object, if None is provided the result is returned as
a string. If a file object is passed it should be opened with
`newline=''`, disabling universal newlines.
.. versionchanged:: 0.24.0
Was previously named "path" for Series.
sep : str, default ','
String of length 1. Field delimiter for the output file.
na_rep : str, default ''
Missing data representation.
float_format : str, default None
Format string for floating point numbers.
columns : sequence, optional
Columns to write.
header : bool or list of str, default True
Write out the column names. If a list of strings is given it is
assumed to be aliases for the column names.
.. versionchanged:: 0.24.0
Previously defaulted to False for Series.
index : bool, default True
Write row names (index).
index_label : str or sequence, or False, default None
Column label for index column(s) if desired. If None is given, and
`header` and `index` are True, then the index names are used. A
sequence should be given if the object uses MultiIndex. If
False do not print fields for index names. Use index_label=False
for easier importing in R.
mode : str
Python write mode, default 'w'.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'utf-8'.
compression : str, default 'infer'
Compression mode among the following possible values: {'infer',
'gzip', 'bz2', 'zip', 'xz', None}. If 'infer' and `path_or_buf`
is path-like, then detect compression from the following
extensions: '.gz', '.bz2', '.zip' or '.xz'. (otherwise no
compression).
.. versionchanged:: 0.24.0
'infer' option added and set to default.
quoting : optional constant from csv module
Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`
then floats are converted to strings and thus csv.QUOTE_NONNUMERIC
will treat them as non-numeric.
quotechar : str, default '\"'
String of length 1. Character used to quote fields.
line_terminator : str, optional
The newline character or character sequence to use in the output
file. Defaults to `os.linesep`, which depends on the OS in which
this method is called ('\n' for linux, '\r\n' for Windows, i.e.).
.. versionchanged:: 0.24.0
chunksize : int or None
Rows to write at a time.
tupleize_cols : bool, default False
Write MultiIndex columns as a list of tuples (if True) or in
the new, expanded format, where each MultiIndex column is a row
in the CSV (if False).
.. deprecated:: 0.21.0
This argument will be removed and will always write each row
of the multi-index as a separate row in the CSV file.
date_format : str, default None
Format string for datetime objects.
doublequote : bool, default True
Control quoting of `quotechar` inside a field.
escapechar : str, default None
String of length 1. Character used to escape `sep` and `quotechar`
when appropriate.
decimal : str, default '.'
Character recognized as decimal separator. E.g. use ',' for
European data.
Returns
-------
None or str
If path_or_buf is None, returns the resulting csv format as a
string. Otherwise returns None.
See Also
--------
read_csv : Load a CSV file into a DataFrame.
to_excel : Write DataFrame to an Excel file.
Examples
--------
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
... 'mask': ['red', 'purple'],
... 'weapon': ['sai', 'bo staff']})
>>> df.to_csv(index=False)
'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
"""
df = self if isinstance(self, ABCDataFrame) else self.to_frame()
if tupleize_cols is not None:
warnings.warn("The 'tupleize_cols' parameter is deprecated and "
"will be removed in a future version",
FutureWarning, stacklevel=2)
else:
tupleize_cols = False
from pandas.io.formats.csvs import CSVFormatter
formatter = CSVFormatter(df, path_or_buf,
line_terminator=line_terminator, sep=sep,
encoding=encoding,
compression=compression, quoting=quoting,
na_rep=na_rep, float_format=float_format,
cols=columns, header=header, index=index,
index_label=index_label, mode=mode,
chunksize=chunksize, quotechar=quotechar,
tupleize_cols=tupleize_cols,
date_format=date_format,
doublequote=doublequote,
escapechar=escapechar, decimal=decimal)
formatter.save()
if path_or_buf is None:
return formatter.path_or_buf.getvalue() | [
"r",
"Write",
"object",
"to",
"a",
"comma",
"-",
"separated",
"values",
"(",
"csv",
")",
"file",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2912-L3053 | [
"def",
"to_csv",
"(",
"self",
",",
"path_or_buf",
"=",
"None",
",",
"sep",
"=",
"\",\"",
",",
"na_rep",
"=",
"''",
",",
"float_format",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"header",
"=",
"True",
",",
"index",
"=",
"True",
",",
"index_label",
"=",
"None",
",",
"mode",
"=",
"'w'",
",",
"encoding",
"=",
"None",
",",
"compression",
"=",
"'infer'",
",",
"quoting",
"=",
"None",
",",
"quotechar",
"=",
"'\"'",
",",
"line_terminator",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"tupleize_cols",
"=",
"None",
",",
"date_format",
"=",
"None",
",",
"doublequote",
"=",
"True",
",",
"escapechar",
"=",
"None",
",",
"decimal",
"=",
"'.'",
")",
":",
"df",
"=",
"self",
"if",
"isinstance",
"(",
"self",
",",
"ABCDataFrame",
")",
"else",
"self",
".",
"to_frame",
"(",
")",
"if",
"tupleize_cols",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"The 'tupleize_cols' parameter is deprecated and \"",
"\"will be removed in a future version\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"else",
":",
"tupleize_cols",
"=",
"False",
"from",
"pandas",
".",
"io",
".",
"formats",
".",
"csvs",
"import",
"CSVFormatter",
"formatter",
"=",
"CSVFormatter",
"(",
"df",
",",
"path_or_buf",
",",
"line_terminator",
"=",
"line_terminator",
",",
"sep",
"=",
"sep",
",",
"encoding",
"=",
"encoding",
",",
"compression",
"=",
"compression",
",",
"quoting",
"=",
"quoting",
",",
"na_rep",
"=",
"na_rep",
",",
"float_format",
"=",
"float_format",
",",
"cols",
"=",
"columns",
",",
"header",
"=",
"header",
",",
"index",
"=",
"index",
",",
"index_label",
"=",
"index_label",
",",
"mode",
"=",
"mode",
",",
"chunksize",
"=",
"chunksize",
",",
"quotechar",
"=",
"quotechar",
",",
"tupleize_cols",
"=",
"tupleize_cols",
",",
"date_format",
"=",
"date_format",
",",
"doublequote",
"=",
"doublequote",
",",
"escapechar",
"=",
"escapechar",
",",
"decimal",
"=",
"decimal",
")",
"formatter",
".",
"save",
"(",
")",
"if",
"path_or_buf",
"is",
"None",
":",
"return",
"formatter",
".",
"path_or_buf",
".",
"getvalue",
"(",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
train | NDFrame._create_indexer | Create an indexer like _name in the class. | pandas/core/generic.py | def _create_indexer(cls, name, indexer):
"""Create an indexer like _name in the class."""
if getattr(cls, name, None) is None:
_indexer = functools.partial(indexer, name)
setattr(cls, name, property(_indexer, doc=indexer.__doc__)) | def _create_indexer(cls, name, indexer):
"""Create an indexer like _name in the class."""
if getattr(cls, name, None) is None:
_indexer = functools.partial(indexer, name)
setattr(cls, name, property(_indexer, doc=indexer.__doc__)) | [
"Create",
"an",
"indexer",
"like",
"_name",
"in",
"the",
"class",
"."
] | pandas-dev/pandas | python | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L3059-L3063 | [
"def",
"_create_indexer",
"(",
"cls",
",",
"name",
",",
"indexer",
")",
":",
"if",
"getattr",
"(",
"cls",
",",
"name",
",",
"None",
")",
"is",
"None",
":",
"_indexer",
"=",
"functools",
".",
"partial",
"(",
"indexer",
",",
"name",
")",
"setattr",
"(",
"cls",
",",
"name",
",",
"property",
"(",
"_indexer",
",",
"doc",
"=",
"indexer",
".",
"__doc__",
")",
")"
] | 9feb3ad92cc0397a04b665803a49299ee7aa1037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.