doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
pandas.merge_ordered pandas.merge_ordered(left, right, on=None, left_on=None, right_on=None, left_by=None, right_by=None, fill_method=None, suffixes=('_x', '_y'), how='outer')[source] Perform a merge for ordered data with optional filling/interpolation. Designed for ordered data like time series data. Optionally perform group-wise merge (see examples). Parameters left:DataFrame right:DataFrame on:label or list Field names to join on. Must be found in both DataFrames. left_on:label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns. right_on:label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs. left_by:column name or list of column names Group left DataFrame by group columns and merge piece by piece with right DataFrame. right_by:column name or list of column names Group right DataFrame by group columns and merge piece by piece with left DataFrame. fill_method:{‘ffill’, None}, default None Interpolation method for data. suffixes:list-like, default is (“_x”, “_y”) A length-2 sequence where each element is optionally a string indicating the suffix to add to overlapping column names in left and right respectively. Pass a value of None instead of a string to indicate that the column name from left or right should be left as-is, with no suffix. At least one of the values must not be None. Changed in version 0.25.0. how:{‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘outer’ left: use only keys from left frame (SQL: left outer join) right: use only keys from right frame (SQL: right outer join) outer: use union of keys from both frames (SQL: full outer join) inner: use intersection of keys from both frames (SQL: inner join). Returns DataFrame The merged DataFrame output type will the be same as ‘left’, if it is a subclass of DataFrame. See also merge Merge with a database-style join. merge_asof Merge on nearest keys. Examples >>> df1 = pd.DataFrame( ... { ... "key": ["a", "c", "e", "a", "c", "e"], ... "lvalue": [1, 2, 3, 1, 2, 3], ... "group": ["a", "a", "a", "b", "b", "b"] ... } ... ) >>> df1 key lvalue group 0 a 1 a 1 c 2 a 2 e 3 a 3 a 1 b 4 c 2 b 5 e 3 b >>> df2 = pd.DataFrame({"key": ["b", "c", "d"], "rvalue": [1, 2, 3]}) >>> df2 key rvalue 0 b 1 1 c 2 2 d 3 >>> merge_ordered(df1, df2, fill_method="ffill", left_by="group") key lvalue group rvalue 0 a 1 a NaN 1 b 1 a 1.0 2 c 2 a 2.0 3 d 2 a 3.0 4 e 3 a 3.0 5 a 1 b NaN 6 b 1 b 1.0 7 c 2 b 2.0 8 d 2 b 3.0 9 e 3 b 3.0
pandas.reference.api.pandas.merge_ordered
pandas.MultiIndex classpandas.MultiIndex(levels=None, codes=None, sortorder=None, names=None, dtype=None, copy=False, name=None, verify_integrity=True)[source] A multi-level, or hierarchical, index object for pandas objects. Parameters levels:sequence of arrays The unique labels for each level. codes:sequence of arrays Integers for each level designating which label at each location. sortorder:optional int Level of sortedness (must be lexicographically sorted by that level). names:optional sequence of objects Names for each of the index levels. (name is accepted for compat). copy:bool, default False Copy the meta-data. verify_integrity:bool, default True Check that the levels/codes are consistent and valid. See also MultiIndex.from_arrays Convert list of arrays to MultiIndex. MultiIndex.from_product Create a MultiIndex from the cartesian product of iterables. MultiIndex.from_tuples Convert list of tuples to a MultiIndex. MultiIndex.from_frame Make a MultiIndex from a DataFrame. Index The base pandas Index type. Notes See the user guide for more. Examples A new MultiIndex is typically constructed using one of the helper methods MultiIndex.from_arrays(), MultiIndex.from_product() and MultiIndex.from_tuples(). For example (using .from_arrays): >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) MultiIndex([(1, 'red'), (1, 'blue'), (2, 'red'), (2, 'blue')], names=['number', 'color']) See further examples for how to construct a MultiIndex in the doc strings of the mentioned helper methods. Attributes names Names of levels in MultiIndex. nlevels Integer number of levels in this MultiIndex. levshape A tuple with the length of each level. levels codes Methods from_arrays(arrays[, sortorder, names]) Convert arrays to MultiIndex. from_tuples(tuples[, sortorder, names]) Convert list of tuples to MultiIndex. from_product(iterables[, sortorder, names]) Make a MultiIndex from the cartesian product of multiple iterables. from_frame(df[, sortorder, names]) Make a MultiIndex from a DataFrame. set_levels(levels[, level, inplace, ...]) Set new levels on MultiIndex. set_codes(codes[, level, inplace, ...]) Set new codes on MultiIndex. to_frame([index, name]) Create a DataFrame with the levels of the MultiIndex as columns. to_flat_index() Convert a MultiIndex to an Index of Tuples containing the level values. sortlevel([level, ascending, sort_remaining]) Sort MultiIndex at the requested level. droplevel([level]) Return index with requested level(s) removed. swaplevel([i, j]) Swap level i with level j. reorder_levels(order) Rearrange levels using input order. remove_unused_levels() Create new MultiIndex from current that removes unused levels. get_locs(seq) Get location for a sequence of labels.
pandas.reference.api.pandas.multiindex
pandas.MultiIndex.codes propertyMultiIndex.codes
pandas.reference.api.pandas.multiindex.codes
pandas.MultiIndex.droplevel MultiIndex.droplevel(level=0)[source] Return index with requested level(s) removed. If resulting index has only 1 level left, the result will be of Index type, not MultiIndex. Parameters level:int, str, or list-like, default 0 If a string is given, must be the name of a level If list-like, elements must be names or indexes of levels. Returns Index or MultiIndex Examples >>> mi = pd.MultiIndex.from_arrays( ... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z']) >>> mi MultiIndex([(1, 3, 5), (2, 4, 6)], names=['x', 'y', 'z']) >>> mi.droplevel() MultiIndex([(3, 5), (4, 6)], names=['y', 'z']) >>> mi.droplevel(2) MultiIndex([(1, 3), (2, 4)], names=['x', 'y']) >>> mi.droplevel('z') MultiIndex([(1, 3), (2, 4)], names=['x', 'y']) >>> mi.droplevel(['x', 'y']) Int64Index([5, 6], dtype='int64', name='z')
pandas.reference.api.pandas.multiindex.droplevel
pandas.MultiIndex.dtypes MultiIndex.dtypes Return the dtypes as a Series for the underlying MultiIndex.
pandas.reference.api.pandas.multiindex.dtypes
pandas.MultiIndex.from_arrays classmethodMultiIndex.from_arrays(arrays, sortorder=None, names=NoDefault.no_default)[source] Convert arrays to MultiIndex. Parameters arrays:list / sequence of array-likes Each array-like gives one level’s value for each data point. len(arrays) is the number of levels. sortorder:int or None Level of sortedness (must be lexicographically sorted by that level). names:list / sequence of str, optional Names for the levels in the index. Returns MultiIndex See also MultiIndex.from_tuples Convert list of tuples to MultiIndex. MultiIndex.from_product Make a MultiIndex from cartesian product of iterables. MultiIndex.from_frame Make a MultiIndex from a DataFrame. Examples >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) MultiIndex([(1, 'red'), (1, 'blue'), (2, 'red'), (2, 'blue')], names=['number', 'color'])
pandas.reference.api.pandas.multiindex.from_arrays
pandas.MultiIndex.from_frame classmethodMultiIndex.from_frame(df, sortorder=None, names=None)[source] Make a MultiIndex from a DataFrame. Parameters df:DataFrame DataFrame to be converted to MultiIndex. sortorder:int, optional Level of sortedness (must be lexicographically sorted by that level). names:list-like, optional If no names are provided, use the column names, or tuple of column names if the columns is a MultiIndex. If a sequence, overwrite names with the given sequence. Returns MultiIndex The MultiIndex representation of the given DataFrame. See also MultiIndex.from_arrays Convert list of arrays to MultiIndex. MultiIndex.from_tuples Convert list of tuples to MultiIndex. MultiIndex.from_product Make a MultiIndex from cartesian product of iterables. Examples >>> df = pd.DataFrame([['HI', 'Temp'], ['HI', 'Precip'], ... ['NJ', 'Temp'], ['NJ', 'Precip']], ... columns=['a', 'b']) >>> df a b 0 HI Temp 1 HI Precip 2 NJ Temp 3 NJ Precip >>> pd.MultiIndex.from_frame(df) MultiIndex([('HI', 'Temp'), ('HI', 'Precip'), ('NJ', 'Temp'), ('NJ', 'Precip')], names=['a', 'b']) Using explicit names, instead of the column names >>> pd.MultiIndex.from_frame(df, names=['state', 'observation']) MultiIndex([('HI', 'Temp'), ('HI', 'Precip'), ('NJ', 'Temp'), ('NJ', 'Precip')], names=['state', 'observation'])
pandas.reference.api.pandas.multiindex.from_frame
pandas.MultiIndex.from_product classmethodMultiIndex.from_product(iterables, sortorder=None, names=NoDefault.no_default)[source] Make a MultiIndex from the cartesian product of multiple iterables. Parameters iterables:list / sequence of iterables Each iterable has unique labels for each level of the index. sortorder:int or None Level of sortedness (must be lexicographically sorted by that level). names:list / sequence of str, optional Names for the levels in the index. Changed in version 1.0.0: If not explicitly provided, names will be inferred from the elements of iterables if an element has a name attribute Returns MultiIndex See also MultiIndex.from_arrays Convert list of arrays to MultiIndex. MultiIndex.from_tuples Convert list of tuples to MultiIndex. MultiIndex.from_frame Make a MultiIndex from a DataFrame. Examples >>> numbers = [0, 1, 2] >>> colors = ['green', 'purple'] >>> pd.MultiIndex.from_product([numbers, colors], ... names=['number', 'color']) MultiIndex([(0, 'green'), (0, 'purple'), (1, 'green'), (1, 'purple'), (2, 'green'), (2, 'purple')], names=['number', 'color'])
pandas.reference.api.pandas.multiindex.from_product
pandas.MultiIndex.from_tuples classmethodMultiIndex.from_tuples(tuples, sortorder=None, names=None)[source] Convert list of tuples to MultiIndex. Parameters tuples:list / sequence of tuple-likes Each tuple is the index of one row/column. sortorder:int or None Level of sortedness (must be lexicographically sorted by that level). names:list / sequence of str, optional Names for the levels in the index. Returns MultiIndex See also MultiIndex.from_arrays Convert list of arrays to MultiIndex. MultiIndex.from_product Make a MultiIndex from cartesian product of iterables. MultiIndex.from_frame Make a MultiIndex from a DataFrame. Examples >>> tuples = [(1, 'red'), (1, 'blue'), ... (2, 'red'), (2, 'blue')] >>> pd.MultiIndex.from_tuples(tuples, names=('number', 'color')) MultiIndex([(1, 'red'), (1, 'blue'), (2, 'red'), (2, 'blue')], names=['number', 'color'])
pandas.reference.api.pandas.multiindex.from_tuples
pandas.MultiIndex.get_indexer MultiIndex.get_indexer(target, method=None, limit=None, tolerance=None)[source] Compute indexer and mask for new index given the current index. The indexer should be then used as an input to ndarray.take to align the current data to the new index. Parameters target:Index method:{None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’}, optional default: exact matches only. pad / ffill: find the PREVIOUS index value if no exact match. backfill / bfill: use NEXT index value if no exact match nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value. limit:int, optional Maximum number of consecutive labels in target to match for inexact matches. tolerance:optional Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations must satisfy the equation abs(index[indexer] - target) <= tolerance. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index’s type. Returns indexer:np.ndarray[np.intp] Integers from 0 to n - 1 indicating that the index at these positions matches the corresponding target values. Missing values in the target are marked by -1. Notes Returns -1 for unmatched values, for further explanation see the example below. Examples >>> index = pd.Index(['c', 'a', 'b']) >>> index.get_indexer(['a', 'b', 'x']) array([ 1, 2, -1]) Notice that the return value is an array of locations in index and x is marked by -1, as it is not in index.
pandas.reference.api.pandas.multiindex.get_indexer
pandas.MultiIndex.get_level_values MultiIndex.get_level_values(level)[source] Return vector of label values for requested level. Length of returned vector is equal to the length of the index. Parameters level:int or str level is either the integer position of the level in the MultiIndex, or the name of the level. Returns values:Index Values is a level of this MultiIndex converted to a single Index (or subclass thereof). Notes If the level contains missing values, the result may be casted to float with missing values specified as NaN. This is because the level is converted to a regular Index. Examples Create a MultiIndex: >>> mi = pd.MultiIndex.from_arrays((list('abc'), list('def'))) >>> mi.names = ['level_1', 'level_2'] Get level values by supplying level as either integer or name: >>> mi.get_level_values(0) Index(['a', 'b', 'c'], dtype='object', name='level_1') >>> mi.get_level_values('level_2') Index(['d', 'e', 'f'], dtype='object', name='level_2') If a level contains missing values, the return type of the level maybe casted to float. >>> pd.MultiIndex.from_arrays([[1, None, 2], [3, 4, 5]]).dtypes level_0 int64 level_1 int64 dtype: object >>> pd.MultiIndex.from_arrays([[1, None, 2], [3, 4, 5]]).get_level_values(0) Float64Index([1.0, nan, 2.0], dtype='float64')
pandas.reference.api.pandas.multiindex.get_level_values
pandas.MultiIndex.get_loc MultiIndex.get_loc(key, method=None)[source] Get location for a label or a tuple of labels. The location is returned as an integer/slice or boolean mask. Parameters key:label or tuple of labels (one for each level) method:None Returns loc:int, slice object or boolean mask If the key is past the lexsort depth, the return may be a boolean mask array, otherwise it is always a slice or int. See also Index.get_loc The get_loc method for (single-level) index. MultiIndex.slice_locs Get slice location given start label(s) and end label(s). MultiIndex.get_locs Get location for a label/slice/list/mask or a sequence of such. Notes The key cannot be a slice, list of same-level labels, a boolean mask, or a sequence of such. If you want to use those, use MultiIndex.get_locs() instead. Examples >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')]) >>> mi.get_loc('b') slice(1, 3, None) >>> mi.get_loc(('b', 'e')) 1
pandas.reference.api.pandas.multiindex.get_loc
pandas.MultiIndex.get_loc_level MultiIndex.get_loc_level(key, level=0, drop_level=True)[source] Get location and sliced index for requested label(s)/level(s). Parameters key:label or sequence of labels level:int/level name or list thereof, optional drop_level:bool, default True If False, the resulting index will not drop any level. Returns loc:A 2-tuple where the elements are: Element 0: int, slice object or boolean array Element 1: The resulting sliced multiindex/index. If the key contains all levels, this will be None. See also MultiIndex.get_loc Get location for a label or a tuple of labels. MultiIndex.get_locs Get location for a label/slice/list/mask or a sequence of such. Examples >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')], ... names=['A', 'B']) >>> mi.get_loc_level('b') (slice(1, 3, None), Index(['e', 'f'], dtype='object', name='B')) >>> mi.get_loc_level('e', level='B') (array([False, True, False]), Index(['b'], dtype='object', name='A')) >>> mi.get_loc_level(['b', 'e']) (1, None)
pandas.reference.api.pandas.multiindex.get_loc_level
pandas.MultiIndex.get_locs MultiIndex.get_locs(seq)[source] Get location for a sequence of labels. Parameters seq:label, slice, list, mask or a sequence of such You should use one of the above for each level. If a level should not be used, set it to slice(None). Returns numpy.ndarray NumPy array of integers suitable for passing to iloc. See also MultiIndex.get_loc Get location for a label or a tuple of labels. MultiIndex.slice_locs Get slice location given start label(s) and end label(s). Examples >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')]) >>> mi.get_locs('b') array([1, 2], dtype=int64) >>> mi.get_locs([slice(None), ['e', 'f']]) array([1, 2], dtype=int64) >>> mi.get_locs([[True, False, True], slice('e', 'f')]) array([2], dtype=int64)
pandas.reference.api.pandas.multiindex.get_locs
pandas.MultiIndex.levels MultiIndex.levels
pandas.reference.api.pandas.multiindex.levels
pandas.MultiIndex.levshape propertyMultiIndex.levshape A tuple with the length of each level. Examples >>> mi = pd.MultiIndex.from_arrays([['a'], ['b'], ['c']]) >>> mi MultiIndex([('a', 'b', 'c')], ) >>> mi.levshape (1, 1, 1)
pandas.reference.api.pandas.multiindex.levshape
pandas.MultiIndex.names propertyMultiIndex.names Names of levels in MultiIndex. Examples >>> mi = pd.MultiIndex.from_arrays( ... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z']) >>> mi MultiIndex([(1, 3, 5), (2, 4, 6)], names=['x', 'y', 'z']) >>> mi.names FrozenList(['x', 'y', 'z'])
pandas.reference.api.pandas.multiindex.names
pandas.MultiIndex.nlevels propertyMultiIndex.nlevels Integer number of levels in this MultiIndex. Examples >>> mi = pd.MultiIndex.from_arrays([['a'], ['b'], ['c']]) >>> mi MultiIndex([('a', 'b', 'c')], ) >>> mi.nlevels 3
pandas.reference.api.pandas.multiindex.nlevels
pandas.MultiIndex.remove_unused_levels MultiIndex.remove_unused_levels()[source] Create new MultiIndex from current that removes unused levels. Unused level(s) means levels that are not expressed in the labels. The resulting MultiIndex will have the same outward appearance, meaning the same .values and ordering. It will also be .equals() to the original. Returns MultiIndex Examples >>> mi = pd.MultiIndex.from_product([range(2), list('ab')]) >>> mi MultiIndex([(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')], ) >>> mi[2:] MultiIndex([(1, 'a'), (1, 'b')], ) The 0 from the first level is not represented and can be removed >>> mi2 = mi[2:].remove_unused_levels() >>> mi2.levels FrozenList([[1], ['a', 'b']])
pandas.reference.api.pandas.multiindex.remove_unused_levels
pandas.MultiIndex.reorder_levels MultiIndex.reorder_levels(order)[source] Rearrange levels using input order. May not drop or duplicate levels. Parameters order:list of int or list of str List representing new level order. Reference level by number (position) or by key (label). Returns MultiIndex Examples >>> mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=['x', 'y']) >>> mi MultiIndex([(1, 3), (2, 4)], names=['x', 'y']) >>> mi.reorder_levels(order=[1, 0]) MultiIndex([(3, 1), (4, 2)], names=['y', 'x']) >>> mi.reorder_levels(order=['y', 'x']) MultiIndex([(3, 1), (4, 2)], names=['y', 'x'])
pandas.reference.api.pandas.multiindex.reorder_levels
pandas.MultiIndex.set_codes MultiIndex.set_codes(codes, level=None, inplace=None, verify_integrity=True)[source] Set new codes on MultiIndex. Defaults to returning new index. Parameters codes:sequence or list of sequence New codes to apply. level:int, level name, or sequence of int/level names (default None) Level(s) to set (None for all levels). inplace:bool If True, mutates in place. Deprecated since version 1.2.0. verify_integrity:bool, default True If True, checks that levels and codes are compatible. Returns new index (of same type and class…etc) or None The same type as the caller or None if inplace=True. Examples >>> idx = pd.MultiIndex.from_tuples( ... [(1, "one"), (1, "two"), (2, "one"), (2, "two")], names=["foo", "bar"] ... ) >>> idx MultiIndex([(1, 'one'), (1, 'two'), (2, 'one'), (2, 'two')], names=['foo', 'bar']) >>> idx.set_codes([[1, 0, 1, 0], [0, 0, 1, 1]]) MultiIndex([(2, 'one'), (1, 'one'), (2, 'two'), (1, 'two')], names=['foo', 'bar']) >>> idx.set_codes([1, 0, 1, 0], level=0) MultiIndex([(2, 'one'), (1, 'two'), (2, 'one'), (1, 'two')], names=['foo', 'bar']) >>> idx.set_codes([0, 0, 1, 1], level='bar') MultiIndex([(1, 'one'), (1, 'one'), (2, 'two'), (2, 'two')], names=['foo', 'bar']) >>> idx.set_codes([[1, 0, 1, 0], [0, 0, 1, 1]], level=[0, 1]) MultiIndex([(2, 'one'), (1, 'one'), (2, 'two'), (1, 'two')], names=['foo', 'bar'])
pandas.reference.api.pandas.multiindex.set_codes
pandas.MultiIndex.set_levels MultiIndex.set_levels(levels, level=None, inplace=None, verify_integrity=True)[source] Set new levels on MultiIndex. Defaults to returning new index. Parameters levels:sequence or list of sequence New level(s) to apply. level:int, level name, or sequence of int/level names (default None) Level(s) to set (None for all levels). inplace:bool If True, mutates in place. Deprecated since version 1.2.0. verify_integrity:bool, default True If True, checks that levels and codes are compatible. Returns new index (of same type and class…etc) or None The same type as the caller or None if inplace=True. Examples >>> idx = pd.MultiIndex.from_tuples( ... [ ... (1, "one"), ... (1, "two"), ... (2, "one"), ... (2, "two"), ... (3, "one"), ... (3, "two") ... ], ... names=["foo", "bar"] ... ) >>> idx MultiIndex([(1, 'one'), (1, 'two'), (2, 'one'), (2, 'two'), (3, 'one'), (3, 'two')], names=['foo', 'bar']) >>> idx.set_levels([['a', 'b', 'c'], [1, 2]]) MultiIndex([('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)], names=['foo', 'bar']) >>> idx.set_levels(['a', 'b', 'c'], level=0) MultiIndex([('a', 'one'), ('a', 'two'), ('b', 'one'), ('b', 'two'), ('c', 'one'), ('c', 'two')], names=['foo', 'bar']) >>> idx.set_levels(['a', 'b'], level='bar') MultiIndex([(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')], names=['foo', 'bar']) If any of the levels passed to set_levels() exceeds the existing length, all of the values from that argument will be stored in the MultiIndex levels, though the values will be truncated in the MultiIndex output. >>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1]) MultiIndex([('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)], names=['foo', 'bar']) >>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1]).levels FrozenList([['a', 'b', 'c'], [1, 2, 3, 4]])
pandas.reference.api.pandas.multiindex.set_levels
pandas.MultiIndex.sortlevel MultiIndex.sortlevel(level=0, ascending=True, sort_remaining=True)[source] Sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level. Parameters level:list-like, int or str, default 0 If a string is given, must be a name of the level. If list-like must be names or ints of levels. ascending:bool, default True False to sort in descending order. Can also be a list to specify a directed ordering. sort_remaining:sort by the remaining levels after level Returns sorted_index:pd.MultiIndex Resulting index. indexer:np.ndarray[np.intp] Indices of output values in original index. Examples >>> mi = pd.MultiIndex.from_arrays([[0, 0], [2, 1]]) >>> mi MultiIndex([(0, 2), (0, 1)], ) >>> mi.sortlevel() (MultiIndex([(0, 1), (0, 2)], ), array([1, 0])) >>> mi.sortlevel(sort_remaining=False) (MultiIndex([(0, 2), (0, 1)], ), array([0, 1])) >>> mi.sortlevel(1) (MultiIndex([(0, 1), (0, 2)], ), array([1, 0])) >>> mi.sortlevel(1, ascending=False) (MultiIndex([(0, 2), (0, 1)], ), array([0, 1]))
pandas.reference.api.pandas.multiindex.sortlevel
pandas.MultiIndex.swaplevel MultiIndex.swaplevel(i=- 2, j=- 1)[source] Swap level i with level j. Calling this method does not change the ordering of the values. Parameters i:int, str, default -2 First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed. j:int, str, default -1 Second level of index to be swapped. Can pass level name as string. Type of parameters can be mixed. Returns MultiIndex A new MultiIndex. See also Series.swaplevel Swap levels i and j in a MultiIndex. Dataframe.swaplevel Swap levels i and j in a MultiIndex on a particular axis. Examples >>> mi = pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']], ... codes=[[0, 0, 1, 1], [0, 1, 0, 1]]) >>> mi MultiIndex([('a', 'bb'), ('a', 'aa'), ('b', 'bb'), ('b', 'aa')], ) >>> mi.swaplevel(0, 1) MultiIndex([('bb', 'a'), ('aa', 'a'), ('bb', 'b'), ('aa', 'b')], )
pandas.reference.api.pandas.multiindex.swaplevel
pandas.MultiIndex.to_flat_index MultiIndex.to_flat_index()[source] Convert a MultiIndex to an Index of Tuples containing the level values. Returns pd.Index Index with the MultiIndex data represented in Tuples. See also MultiIndex.from_tuples Convert flat index back to MultiIndex. Notes This method will simply return the caller if called by anything other than a MultiIndex. Examples >>> index = pd.MultiIndex.from_product( ... [['foo', 'bar'], ['baz', 'qux']], ... names=['a', 'b']) >>> index.to_flat_index() Index([('foo', 'baz'), ('foo', 'qux'), ('bar', 'baz'), ('bar', 'qux')], dtype='object')
pandas.reference.api.pandas.multiindex.to_flat_index
pandas.MultiIndex.to_frame MultiIndex.to_frame(index=True, name=NoDefault.no_default)[source] Create a DataFrame with the levels of the MultiIndex as columns. Column ordering is determined by the DataFrame constructor with data as a dict. Parameters index:bool, default True Set the index of the returned DataFrame as the original MultiIndex. name:list / sequence of str, optional The passed names should substitute index level names. Returns DataFrame:a DataFrame containing the original MultiIndex data. See also DataFrame Two-dimensional, size-mutable, potentially heterogeneous tabular data. Examples >>> mi = pd.MultiIndex.from_arrays([['a', 'b'], ['c', 'd']]) >>> mi MultiIndex([('a', 'c'), ('b', 'd')], ) >>> df = mi.to_frame() >>> df 0 1 a c a c b d b d >>> df = mi.to_frame(index=False) >>> df 0 1 0 a c 1 b d >>> df = mi.to_frame(name=['x', 'y']) >>> df x y a c a c b d b d
pandas.reference.api.pandas.multiindex.to_frame
pandas.notna pandas.notna(obj)[source] Detect non-missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are valid (not missing, which is NaN in numeric arrays, None or NaN in object arrays, NaT in datetimelike). Parameters obj:array-like or object value Object to check for not null or non-missing values. Returns bool or array-like of bool For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is valid. See also isna Boolean inverse of pandas.notna. Series.notna Detect valid values in a Series. DataFrame.notna Detect valid values in a DataFrame. Index.notna Detect valid values in an Index. Examples Scalar arguments (including strings) result in a scalar boolean. >>> pd.notna('dog') True >>> pd.notna(pd.NA) False >>> pd.notna(np.nan) False ndarrays result in an ndarray of booleans. >>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]]) >>> array array([[ 1., nan, 3.], [ 4., 5., nan]]) >>> pd.notna(array) array([[ True, False, True], [ True, True, False]]) For indexes, an ndarray of booleans is returned. >>> index = pd.DatetimeIndex(["2017-07-05", "2017-07-06", None, ... "2017-07-08"]) >>> index DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'], dtype='datetime64[ns]', freq=None) >>> pd.notna(index) array([ True, True, False, True]) For Series and DataFrame, the same type is returned, containing booleans. >>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']]) >>> df 0 1 2 0 ant bee cat 1 dog None fly >>> pd.notna(df) 0 1 2 0 True True True 1 True False True >>> pd.notna(df[1]) 0 True 1 False Name: 1, dtype: bool
pandas.reference.api.pandas.notna
pandas.notnull pandas.notnull(obj)[source] Detect non-missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are valid (not missing, which is NaN in numeric arrays, None or NaN in object arrays, NaT in datetimelike). Parameters obj:array-like or object value Object to check for not null or non-missing values. Returns bool or array-like of bool For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is valid. See also isna Boolean inverse of pandas.notna. Series.notna Detect valid values in a Series. DataFrame.notna Detect valid values in a DataFrame. Index.notna Detect valid values in an Index. Examples Scalar arguments (including strings) result in a scalar boolean. >>> pd.notna('dog') True >>> pd.notna(pd.NA) False >>> pd.notna(np.nan) False ndarrays result in an ndarray of booleans. >>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]]) >>> array array([[ 1., nan, 3.], [ 4., 5., nan]]) >>> pd.notna(array) array([[ True, False, True], [ True, True, False]]) For indexes, an ndarray of booleans is returned. >>> index = pd.DatetimeIndex(["2017-07-05", "2017-07-06", None, ... "2017-07-08"]) >>> index DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'], dtype='datetime64[ns]', freq=None) >>> pd.notna(index) array([ True, True, False, True]) For Series and DataFrame, the same type is returned, containing booleans. >>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']]) >>> df 0 1 2 0 ant bee cat 1 dog None fly >>> pd.notna(df) 0 1 2 0 True True True 1 True False True >>> pd.notna(df[1]) 0 True 1 False Name: 1, dtype: bool
pandas.reference.api.pandas.notnull
pandas.option_context classpandas.option_context(*args)[source] Context manager to temporarily set options in the with statement context. You need to invoke as option_context(pat, val, [(pat, val), ...]). Examples >>> with option_context('display.max_rows', 10, 'display.max_columns', 5): ... pass Methods __call__(func) Call self as a function.
pandas.reference.api.pandas.option_context
pandas.option_context.__call__ option_context.__call__(func)[source] Call self as a function.
pandas.reference.api.pandas.option_context.__call__
pandas.Period classpandas.Period(value=None, freq=None, ordinal=None, year=None, month=None, quarter=None, day=None, hour=None, minute=None, second=None) Represents a period of time. Parameters value:Period or str, default None The time period represented (e.g., ‘4Q2005’). freq:str, default None One of pandas period strings or corresponding objects. ordinal:int, default None The period offset from the proleptic Gregorian epoch. year:int, default None Year value of the period. month:int, default 1 Month value of the period. quarter:int, default None Quarter value of the period. day:int, default 1 Day value of the period. hour:int, default 0 Hour value of the period. minute:int, default 0 Minute value of the period. second:int, default 0 Second value of the period. Attributes day Get day of the month that a Period falls on. day_of_week Day of the week the period lies in, with Monday=0 and Sunday=6. day_of_year Return the day of the year. dayofweek Day of the week the period lies in, with Monday=0 and Sunday=6. dayofyear Return the day of the year. days_in_month Get the total number of days in the month that this period falls on. daysinmonth Get the total number of days of the month that the Period falls in. end_time Get the Timestamp for the end of the period. freqstr Return a string representation of the frequency. hour Get the hour of the day component of the Period. is_leap_year Return True if the period's year is in a leap year. minute Get minute of the hour component of the Period. month Return the month this Period falls on. quarter Return the quarter this Period falls on. qyear Fiscal year the Period lies in according to its starting-quarter. second Get the second component of the Period. start_time Get the Timestamp for the start of the period. week Get the week of the year on the given Period. weekday Day of the week the period lies in, with Monday=0 and Sunday=6. weekofyear Get the week of the year on the given Period. year Return the year this Period falls on. freq ordinal Methods asfreq Convert Period to desired frequency, at the start or end of the interval. now Return the period of now's date. strftime Returns the string representation of the Period, depending on the selected fmt. to_timestamp Return the Timestamp representation of the Period.
pandas.reference.api.pandas.period
pandas.Period.asfreq Period.asfreq() Convert Period to desired frequency, at the start or end of the interval. Parameters freq:str The desired frequency. how:{‘E’, ‘S’, ‘end’, ‘start’}, default ‘end’ Start or end of the timespan. Returns resampled:Period
pandas.reference.api.pandas.period.asfreq
pandas.Period.day Period.day Get day of the month that a Period falls on. Returns int See also Period.dayofweek Get the day of the week. Period.dayofyear Get the day of the year. Examples >>> p = pd.Period("2018-03-11", freq='H') >>> p.day 11
pandas.reference.api.pandas.period.day
pandas.Period.day_of_week Period.day_of_week Day of the week the period lies in, with Monday=0 and Sunday=6. If the period frequency is lower than daily (e.g. hourly), and the period spans over multiple days, the day at the start of the period is used. If the frequency is higher than daily (e.g. monthly), the last day of the period is used. Returns int Day of the week. See also Period.day_of_week Day of the week the period lies in. Period.weekday Alias of Period.day_of_week. Period.day Day of the month. Period.dayofyear Day of the year. Examples >>> per = pd.Period('2017-12-31 22:00', 'H') >>> per.day_of_week 6 For periods that span over multiple days, the day at the beginning of the period is returned. >>> per = pd.Period('2017-12-31 22:00', '4H') >>> per.day_of_week 6 >>> per.start_time.day_of_week 6 For periods with a frequency higher than days, the last day of the period is returned. >>> per = pd.Period('2018-01', 'M') >>> per.day_of_week 2 >>> per.end_time.day_of_week 2
pandas.reference.api.pandas.period.day_of_week
pandas.Period.day_of_year Period.day_of_year Return the day of the year. This attribute returns the day of the year on which the particular date occurs. The return value ranges between 1 to 365 for regular years and 1 to 366 for leap years. Returns int The day of year. See also Period.day Return the day of the month. Period.day_of_week Return the day of week. PeriodIndex.day_of_year Return the day of year of all indexes. Examples >>> period = pd.Period("2015-10-23", freq='H') >>> period.day_of_year 296 >>> period = pd.Period("2012-12-31", freq='D') >>> period.day_of_year 366 >>> period = pd.Period("2013-01-01", freq='D') >>> period.day_of_year 1
pandas.reference.api.pandas.period.day_of_year
pandas.Period.dayofweek Period.dayofweek Day of the week the period lies in, with Monday=0 and Sunday=6. If the period frequency is lower than daily (e.g. hourly), and the period spans over multiple days, the day at the start of the period is used. If the frequency is higher than daily (e.g. monthly), the last day of the period is used. Returns int Day of the week. See also Period.day_of_week Day of the week the period lies in. Period.weekday Alias of Period.day_of_week. Period.day Day of the month. Period.dayofyear Day of the year. Examples >>> per = pd.Period('2017-12-31 22:00', 'H') >>> per.day_of_week 6 For periods that span over multiple days, the day at the beginning of the period is returned. >>> per = pd.Period('2017-12-31 22:00', '4H') >>> per.day_of_week 6 >>> per.start_time.day_of_week 6 For periods with a frequency higher than days, the last day of the period is returned. >>> per = pd.Period('2018-01', 'M') >>> per.day_of_week 2 >>> per.end_time.day_of_week 2
pandas.reference.api.pandas.period.dayofweek
pandas.Period.dayofyear Period.dayofyear Return the day of the year. This attribute returns the day of the year on which the particular date occurs. The return value ranges between 1 to 365 for regular years and 1 to 366 for leap years. Returns int The day of year. See also Period.day Return the day of the month. Period.day_of_week Return the day of week. PeriodIndex.day_of_year Return the day of year of all indexes. Examples >>> period = pd.Period("2015-10-23", freq='H') >>> period.day_of_year 296 >>> period = pd.Period("2012-12-31", freq='D') >>> period.day_of_year 366 >>> period = pd.Period("2013-01-01", freq='D') >>> period.day_of_year 1
pandas.reference.api.pandas.period.dayofyear
pandas.Period.days_in_month Period.days_in_month Get the total number of days in the month that this period falls on. Returns int See also Period.daysinmonth Gets the number of days in the month. DatetimeIndex.daysinmonth Gets the number of days in the month. calendar.monthrange Returns a tuple containing weekday (0-6 ~ Mon-Sun) and number of days (28-31). Examples >>> p = pd.Period('2018-2-17') >>> p.days_in_month 28 >>> pd.Period('2018-03-01').days_in_month 31 Handles the leap year case as well: >>> p = pd.Period('2016-2-17') >>> p.days_in_month 29
pandas.reference.api.pandas.period.days_in_month
pandas.Period.daysinmonth Period.daysinmonth Get the total number of days of the month that the Period falls in. Returns int See also Period.days_in_month Return the days of the month. Period.dayofyear Return the day of the year. Examples >>> p = pd.Period("2018-03-11", freq='H') >>> p.daysinmonth 31
pandas.reference.api.pandas.period.daysinmonth
pandas.Period.end_time Period.end_time Get the Timestamp for the end of the period. Returns Timestamp See also Period.start_time Return the start Timestamp. Period.dayofyear Return the day of year. Period.daysinmonth Return the days in that month. Period.dayofweek Return the day of the week.
pandas.reference.api.pandas.period.end_time
pandas.Period.freq Period.freq
pandas.reference.api.pandas.period.freq
pandas.Period.freqstr Period.freqstr Return a string representation of the frequency.
pandas.reference.api.pandas.period.freqstr
pandas.Period.hour Period.hour Get the hour of the day component of the Period. Returns int The hour as an integer, between 0 and 23. See also Period.second Get the second component of the Period. Period.minute Get the minute component of the Period. Examples >>> p = pd.Period("2018-03-11 13:03:12.050000") >>> p.hour 13 Period longer than a day >>> p = pd.Period("2018-03-11", freq="M") >>> p.hour 0
pandas.reference.api.pandas.period.hour
pandas.Period.is_leap_year Period.is_leap_year Return True if the period’s year is in a leap year.
pandas.reference.api.pandas.period.is_leap_year
pandas.Period.minute Period.minute Get minute of the hour component of the Period. Returns int The minute as an integer, between 0 and 59. See also Period.hour Get the hour component of the Period. Period.second Get the second component of the Period. Examples >>> p = pd.Period("2018-03-11 13:03:12.050000") >>> p.minute 3
pandas.reference.api.pandas.period.minute
pandas.Period.month Period.month Return the month this Period falls on.
pandas.reference.api.pandas.period.month
pandas.Period.now Period.now() Return the period of now’s date.
pandas.reference.api.pandas.period.now
pandas.Period.ordinal Period.ordinal
pandas.reference.api.pandas.period.ordinal
pandas.Period.quarter Period.quarter Return the quarter this Period falls on.
pandas.reference.api.pandas.period.quarter
pandas.Period.qyear Period.qyear Fiscal year the Period lies in according to its starting-quarter. The year and the qyear of the period will be the same if the fiscal and calendar years are the same. When they are not, the fiscal year can be different from the calendar year of the period. Returns int The fiscal year of the period. See also Period.year Return the calendar year of the period. Examples If the natural and fiscal year are the same, qyear and year will be the same. >>> per = pd.Period('2018Q1', freq='Q') >>> per.qyear 2018 >>> per.year 2018 If the fiscal year starts in April (Q-MAR), the first quarter of 2018 will start in April 2017. year will then be 2018, but qyear will be the fiscal year, 2018. >>> per = pd.Period('2018Q1', freq='Q-MAR') >>> per.start_time Timestamp('2017-04-01 00:00:00') >>> per.qyear 2018 >>> per.year 2017
pandas.reference.api.pandas.period.qyear
pandas.Period.second Period.second Get the second component of the Period. Returns int The second of the Period (ranges from 0 to 59). See also Period.hour Get the hour component of the Period. Period.minute Get the minute component of the Period. Examples >>> p = pd.Period("2018-03-11 13:03:12.050000") >>> p.second 12
pandas.reference.api.pandas.period.second
pandas.Period.start_time Period.start_time Get the Timestamp for the start of the period. Returns Timestamp See also Period.end_time Return the end Timestamp. Period.dayofyear Return the day of year. Period.daysinmonth Return the days in that month. Period.dayofweek Return the day of the week. Examples >>> period = pd.Period('2012-1-1', freq='D') >>> period Period('2012-01-01', 'D') >>> period.start_time Timestamp('2012-01-01 00:00:00') >>> period.end_time Timestamp('2012-01-01 23:59:59.999999999')
pandas.reference.api.pandas.period.start_time
pandas.Period.strftime Period.strftime() Returns the string representation of the Period, depending on the selected fmt. fmt must be a string containing one or several directives. The method recognizes the same directives as the time.strftime() function of the standard Python distribution, as well as the specific additional directives %f, %F, %q. (formatting & docs originally from scikits.timeries). Directive Meaning Notes %a Locale’s abbreviated weekday name. %A Locale’s full weekday name. %b Locale’s abbreviated month name. %B Locale’s full month name. %c Locale’s appropriate date and time representation. %d Day of the month as a decimal number [01,31]. %f ‘Fiscal’ year without a century as a decimal number [00,99] (1) %F ‘Fiscal’ year with a century as a decimal number (2) %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale’s equivalent of either AM or PM. (3) %q Quarter as a decimal number [01,04] %S Second as a decimal number [00,61]. (4) %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (5) %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (5) %x Locale’s appropriate date representation. %X Locale’s appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character. Notes The %f directive is the same as %y if the frequency is not quarterly. Otherwise, it corresponds to the ‘fiscal’ year, as defined by the qyear attribute. The %F directive is the same as %Y if the frequency is not quarterly. Otherwise, it corresponds to the ‘fiscal’ year, as defined by the qyear attribute. The %p directive only affects the output hour field if the %I directive is used to parse the hour. The range really is 0 to 61; this accounts for leap seconds and the (very rare) double leap seconds. The %U and %W directives are only used in calculations when the day of the week and the year are specified. Examples >>> a = Period(freq='Q-JUL', year=2006, quarter=1) >>> a.strftime('%F-Q%q') '2006-Q1' >>> # Output the last month in the quarter of this date >>> a.strftime('%b-%Y') 'Oct-2005' >>> >>> a = Period(freq='D', year=2001, month=1, day=1) >>> a.strftime('%d-%b-%Y') '01-Jan-2001' >>> a.strftime('%b. %d, %Y was a %A') 'Jan. 01, 2001 was a Monday'
pandas.reference.api.pandas.period.strftime
pandas.Period.to_timestamp Period.to_timestamp() Return the Timestamp representation of the Period. Uses the target frequency specified at the part of the period specified by how, which is either Start or Finish. Parameters freq:str or DateOffset Target frequency. Default is ‘D’ if self.freq is week or longer and ‘S’ otherwise. how:str, default ‘S’ (start) One of ‘S’, ‘E’. Can be aliased as case insensitive ‘Start’, ‘Finish’, ‘Begin’, ‘End’. Returns Timestamp
pandas.reference.api.pandas.period.to_timestamp
pandas.Period.week Period.week Get the week of the year on the given Period. Returns int See also Period.dayofweek Get the day component of the Period. Period.weekday Get the day component of the Period. Examples >>> p = pd.Period("2018-03-11", "H") >>> p.week 10 >>> p = pd.Period("2018-02-01", "D") >>> p.week 5 >>> p = pd.Period("2018-01-06", "D") >>> p.week 1
pandas.reference.api.pandas.period.week
pandas.Period.weekday Period.weekday Day of the week the period lies in, with Monday=0 and Sunday=6. If the period frequency is lower than daily (e.g. hourly), and the period spans over multiple days, the day at the start of the period is used. If the frequency is higher than daily (e.g. monthly), the last day of the period is used. Returns int Day of the week. See also Period.dayofweek Day of the week the period lies in. Period.weekday Alias of Period.dayofweek. Period.day Day of the month. Period.dayofyear Day of the year. Examples >>> per = pd.Period('2017-12-31 22:00', 'H') >>> per.dayofweek 6 For periods that span over multiple days, the day at the beginning of the period is returned. >>> per = pd.Period('2017-12-31 22:00', '4H') >>> per.dayofweek 6 >>> per.start_time.dayofweek 6 For periods with a frequency higher than days, the last day of the period is returned. >>> per = pd.Period('2018-01', 'M') >>> per.dayofweek 2 >>> per.end_time.dayofweek 2
pandas.reference.api.pandas.period.weekday
pandas.Period.weekofyear Period.weekofyear Get the week of the year on the given Period. Returns int See also Period.dayofweek Get the day component of the Period. Period.weekday Get the day component of the Period. Examples >>> p = pd.Period("2018-03-11", "H") >>> p.weekofyear 10 >>> p = pd.Period("2018-02-01", "D") >>> p.weekofyear 5 >>> p = pd.Period("2018-01-06", "D") >>> p.weekofyear 1
pandas.reference.api.pandas.period.weekofyear
pandas.Period.year Period.year Return the year this Period falls on.
pandas.reference.api.pandas.period.year
pandas.period_range pandas.period_range(start=None, end=None, periods=None, freq=None, name=None)[source] Return a fixed frequency PeriodIndex. The day (calendar) is the default frequency. Parameters start:str or period-like, default None Left bound for generating periods. end:str or period-like, default None Right bound for generating periods. periods:int, default None Number of periods to generate. freq:str or DateOffset, optional Frequency alias. By default the freq is taken from start or end if those are Period objects. Otherwise, the default is "D" for daily frequency. name:str, default None Name of the resulting PeriodIndex. Returns PeriodIndex Notes Of the three parameters: start, end, and periods, exactly two must be specified. To learn more about the frequency strings, please see this link. Examples >>> pd.period_range(start='2017-01-01', end='2018-01-01', freq='M') PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06', '2017-07', '2017-08', '2017-09', '2017-10', '2017-11', '2017-12', '2018-01'], dtype='period[M]') If start or end are Period objects, they will be used as anchor endpoints for a PeriodIndex with frequency matching that of the period_range constructor. >>> pd.period_range(start=pd.Period('2017Q1', freq='Q'), ... end=pd.Period('2017Q2', freq='Q'), freq='M') PeriodIndex(['2017-03', '2017-04', '2017-05', '2017-06'], dtype='period[M]')
pandas.reference.api.pandas.period_range
pandas.PeriodDtype classpandas.PeriodDtype(freq=None)[source] An ExtensionDtype for Period data. This is not an actual numpy dtype, but a duck type. Parameters freq:str or DateOffset The frequency of this PeriodDtype. Examples >>> pd.PeriodDtype(freq='D') period[D] >>> pd.PeriodDtype(freq=pd.offsets.MonthEnd()) period[M] Attributes freq The frequency object of this PeriodDtype. Methods None
pandas.reference.api.pandas.perioddtype
pandas.PeriodDtype.freq propertyPeriodDtype.freq The frequency object of this PeriodDtype.
pandas.reference.api.pandas.perioddtype.freq
pandas.PeriodIndex classpandas.PeriodIndex(data=None, ordinal=None, freq=None, dtype=None, copy=False, name=None, **fields)[source] Immutable ndarray holding ordinal values indicating regular periods in time. Index keys are boxed to Period objects which carries the metadata (eg, frequency information). Parameters data:array-like (1d int np.ndarray or PeriodArray), optional Optional period-like data to construct index with. copy:bool Make a copy of input ndarray. freq:str or period object, optional One of pandas period strings or corresponding objects. year:int, array, or Series, default None month:int, array, or Series, default None quarter:int, array, or Series, default None day:int, array, or Series, default None hour:int, array, or Series, default None minute:int, array, or Series, default None second:int, array, or Series, default None dtype:str or PeriodDtype, default None See also Index The base pandas Index type. Period Represents a period of time. DatetimeIndex Index with datetime64 data. TimedeltaIndex Index of timedelta64 data. period_range Create a fixed-frequency PeriodIndex. Examples >>> idx = pd.PeriodIndex(year=[2000, 2002], quarter=[1, 3]) >>> idx PeriodIndex(['2000Q1', '2002Q3'], dtype='period[Q-DEC]') Attributes day The days of the period. dayofweek The day of the week with Monday=0, Sunday=6. day_of_week The day of the week with Monday=0, Sunday=6. dayofyear The ordinal day of the year. day_of_year The ordinal day of the year. days_in_month The number of days in the month. daysinmonth The number of days in the month. freq Return the frequency object if it is set, otherwise None. freqstr Return the frequency object as a string if its set, otherwise None. hour The hour of the period. is_leap_year Logical indicating if the date belongs to a leap year. minute The minute of the period. month The month as January=1, December=12. quarter The quarter of the date. second The second of the period. week The week ordinal of the year. weekday The day of the week with Monday=0, Sunday=6. weekofyear The week ordinal of the year. year The year of the period. end_time qyear start_time Methods asfreq([freq, how]) Convert the PeriodArray to the specified frequency freq. strftime(*args, **kwargs) Convert to Index using specified date_format. to_timestamp([freq, how]) Cast to DatetimeArray/Index.
pandas.reference.api.pandas.periodindex
pandas.PeriodIndex.asfreq PeriodIndex.asfreq(freq=None, how='E')[source] Convert the PeriodArray to the specified frequency freq. Equivalent to applying pandas.Period.asfreq() with the given arguments to each Period in this PeriodArray. Parameters freq:str A frequency. how:str {‘E’, ‘S’}, default ‘E’ Whether the elements should be aligned to the end or start within pa period. ‘E’, ‘END’, or ‘FINISH’ for end, ‘S’, ‘START’, or ‘BEGIN’ for start. January 31st (‘END’) vs. January 1st (‘START’) for example. Returns PeriodArray The transformed PeriodArray with the new frequency. See also pandas.arrays.PeriodArray.asfreq Convert each Period in a PeriodArray to the given frequency. Period.asfreq Convert a Period object to the given frequency. Examples >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A') >>> pidx PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'], dtype='period[A-DEC]') >>> pidx.asfreq('M') PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12', '2015-12'], dtype='period[M]') >>> pidx.asfreq('M', how='S') PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01', '2015-01'], dtype='period[M]')
pandas.reference.api.pandas.periodindex.asfreq
pandas.PeriodIndex.day propertyPeriodIndex.day The days of the period.
pandas.reference.api.pandas.periodindex.day
pandas.PeriodIndex.day_of_week propertyPeriodIndex.day_of_week The day of the week with Monday=0, Sunday=6.
pandas.reference.api.pandas.periodindex.day_of_week
pandas.PeriodIndex.day_of_year propertyPeriodIndex.day_of_year The ordinal day of the year.
pandas.reference.api.pandas.periodindex.day_of_year
pandas.PeriodIndex.dayofweek propertyPeriodIndex.dayofweek The day of the week with Monday=0, Sunday=6.
pandas.reference.api.pandas.periodindex.dayofweek
pandas.PeriodIndex.dayofyear propertyPeriodIndex.dayofyear The ordinal day of the year.
pandas.reference.api.pandas.periodindex.dayofyear
pandas.PeriodIndex.days_in_month propertyPeriodIndex.days_in_month The number of days in the month.
pandas.reference.api.pandas.periodindex.days_in_month
pandas.PeriodIndex.daysinmonth propertyPeriodIndex.daysinmonth The number of days in the month.
pandas.reference.api.pandas.periodindex.daysinmonth
pandas.PeriodIndex.end_time propertyPeriodIndex.end_time
pandas.reference.api.pandas.periodindex.end_time
pandas.PeriodIndex.freq propertyPeriodIndex.freq Return the frequency object if it is set, otherwise None.
pandas.reference.api.pandas.periodindex.freq
pandas.PeriodIndex.freqstr propertyPeriodIndex.freqstr Return the frequency object as a string if its set, otherwise None.
pandas.reference.api.pandas.periodindex.freqstr
pandas.PeriodIndex.hour propertyPeriodIndex.hour The hour of the period.
pandas.reference.api.pandas.periodindex.hour
pandas.PeriodIndex.is_leap_year propertyPeriodIndex.is_leap_year Logical indicating if the date belongs to a leap year.
pandas.reference.api.pandas.periodindex.is_leap_year
pandas.PeriodIndex.minute propertyPeriodIndex.minute The minute of the period.
pandas.reference.api.pandas.periodindex.minute
pandas.PeriodIndex.month propertyPeriodIndex.month The month as January=1, December=12.
pandas.reference.api.pandas.periodindex.month
pandas.PeriodIndex.quarter propertyPeriodIndex.quarter The quarter of the date.
pandas.reference.api.pandas.periodindex.quarter
pandas.PeriodIndex.qyear propertyPeriodIndex.qyear
pandas.reference.api.pandas.periodindex.qyear
pandas.PeriodIndex.second propertyPeriodIndex.second The second of the period.
pandas.reference.api.pandas.periodindex.second
pandas.PeriodIndex.start_time propertyPeriodIndex.start_time
pandas.reference.api.pandas.periodindex.start_time
pandas.PeriodIndex.strftime PeriodIndex.strftime(*args, **kwargs)[source] Convert to Index using specified date_format. Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in python string format doc. Parameters date_format:str Date format string (e.g. “%Y-%m-%d”). Returns ndarray[object] NumPy ndarray of formatted strings. See also to_datetime Convert the given argument to datetime. DatetimeIndex.normalize Return DatetimeIndex with times to midnight. DatetimeIndex.round Round the DatetimeIndex to the specified freq. DatetimeIndex.floor Floor the DatetimeIndex to the specified freq. Examples >>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"), ... periods=3, freq='s') >>> rng.strftime('%B %d, %Y, %r') Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM', 'March 10, 2018, 09:00:02 AM'], dtype='object')
pandas.reference.api.pandas.periodindex.strftime
pandas.PeriodIndex.to_timestamp PeriodIndex.to_timestamp(freq=None, how='start')[source] Cast to DatetimeArray/Index. Parameters freq:str or DateOffset, optional Target frequency. The default is ‘D’ for week or longer, ‘S’ otherwise. how:{‘s’, ‘e’, ‘start’, ‘end’} Whether to use the start or end of the time period being converted. Returns DatetimeArray/Index
pandas.reference.api.pandas.periodindex.to_timestamp
pandas.PeriodIndex.week propertyPeriodIndex.week The week ordinal of the year.
pandas.reference.api.pandas.periodindex.week
pandas.PeriodIndex.weekday propertyPeriodIndex.weekday The day of the week with Monday=0, Sunday=6.
pandas.reference.api.pandas.periodindex.weekday
pandas.PeriodIndex.weekofyear propertyPeriodIndex.weekofyear The week ordinal of the year.
pandas.reference.api.pandas.periodindex.weekofyear
pandas.PeriodIndex.year propertyPeriodIndex.year The year of the period.
pandas.reference.api.pandas.periodindex.year
pandas.pivot pandas.pivot(data, index=None, columns=None, values=None)[source] Return reshaped DataFrame organized by given index / column values. Reshape data (produce a “pivot” table) based on column values. Uses unique values from specified index / columns to form axes of the resulting DataFrame. This function does not support data aggregation, multiple values will result in a MultiIndex in the columns. See the User Guide for more on reshaping. Parameters data:DataFrame index:str or object or a list of str, optional Column to use to make new frame’s index. If None, uses existing index. Changed in version 1.1.0: Also accept list of index names. columns:str or object or a list of str Column to use to make new frame’s columns. Changed in version 1.1.0: Also accept list of columns names. values:str, object or a list of the previous, optional Column(s) to use for populating new frame’s values. If not specified, all remaining columns will be used and the result will have hierarchically indexed columns. Returns DataFrame Returns reshaped DataFrame. Raises ValueError: When there are any index, columns combinations with multiple values. DataFrame.pivot_table when you need to aggregate. See also DataFrame.pivot_table Generalization of pivot that can handle duplicate values for one index/column pair. DataFrame.unstack Pivot based on the index values instead of a column. wide_to_long Wide panel to long format. Less flexible but more user-friendly than melt. Notes For finer-tuned control, see hierarchical indexing documentation along with the related stack/unstack methods. Examples >>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two', ... 'two'], ... 'bar': ['A', 'B', 'C', 'A', 'B', 'C'], ... 'baz': [1, 2, 3, 4, 5, 6], ... 'zoo': ['x', 'y', 'z', 'q', 'w', 't']}) >>> df foo bar baz zoo 0 one A 1 x 1 one B 2 y 2 one C 3 z 3 two A 4 q 4 two B 5 w 5 two C 6 t >>> df.pivot(index='foo', columns='bar', values='baz') bar A B C foo one 1 2 3 two 4 5 6 >>> df.pivot(index='foo', columns='bar')['baz'] bar A B C foo one 1 2 3 two 4 5 6 >>> df.pivot(index='foo', columns='bar', values=['baz', 'zoo']) baz zoo bar A B C A B C foo one 1 2 3 x y z two 4 5 6 q w t You could also assign a list of column names or a list of index names. >>> df = pd.DataFrame({ ... "lev1": [1, 1, 1, 2, 2, 2], ... "lev2": [1, 1, 2, 1, 1, 2], ... "lev3": [1, 2, 1, 2, 1, 2], ... "lev4": [1, 2, 3, 4, 5, 6], ... "values": [0, 1, 2, 3, 4, 5]}) >>> df lev1 lev2 lev3 lev4 values 0 1 1 1 1 0 1 1 1 2 2 1 2 1 2 1 3 2 3 2 1 2 4 3 4 2 1 1 5 4 5 2 2 2 6 5 >>> df.pivot(index="lev1", columns=["lev2", "lev3"],values="values") lev2 1 2 lev3 1 2 1 2 lev1 1 0.0 1.0 2.0 NaN 2 4.0 3.0 NaN 5.0 >>> df.pivot(index=["lev1", "lev2"], columns=["lev3"],values="values") lev3 1 2 lev1 lev2 1 1 0.0 1.0 2 2.0 NaN 2 1 4.0 3.0 2 NaN 5.0 A ValueError is raised if there are any duplicates. >>> df = pd.DataFrame({"foo": ['one', 'one', 'two', 'two'], ... "bar": ['A', 'A', 'B', 'C'], ... "baz": [1, 2, 3, 4]}) >>> df foo bar baz 0 one A 1 1 one A 2 2 two B 3 3 two C 4 Notice that the first two rows are the same for our index and columns arguments. >>> df.pivot(index='foo', columns='bar', values='baz') Traceback (most recent call last): ... ValueError: Index contains duplicate entries, cannot reshape
pandas.reference.api.pandas.pivot
pandas.pivot_table pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All', observed=False, sort=True)[source] Create a spreadsheet-style pivot table as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame. Parameters data:DataFrame values:column to aggregate, optional index:column, Grouper, array, or list of the previous If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values. columns:column, Grouper, array, or list of the previous If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values. aggfunc:function, list of functions, dict, default numpy.mean If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) If dict is passed, the key is column to aggregate and value is function or list of functions. fill_value:scalar, default None Value to replace missing values with (in the resulting pivot table, after aggregation). margins:bool, default False Add all row / columns (e.g. for subtotal / grand totals). dropna:bool, default True Do not include columns whose entries are all NaN. margins_name:str, default ‘All’ Name of the row / column that will contain the totals when margins is True. observed:bool, default False This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. Changed in version 0.25.0. sort:bool, default True Specifies if the result should be sorted. New in version 1.3.0. Returns DataFrame An Excel style pivot table. See also DataFrame.pivot Pivot without aggregation that can handle non-numeric data. DataFrame.melt Unpivot a DataFrame from wide to long format, optionally leaving identifiers set. wide_to_long Wide panel to long format. Less flexible but more user-friendly than melt. Examples >>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", ... "bar", "bar", "bar", "bar"], ... "B": ["one", "one", "one", "two", "two", ... "one", "one", "two", "two"], ... "C": ["small", "large", "large", "small", ... "small", "large", "small", "small", ... "large"], ... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7], ... "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]}) >>> df A B C D E 0 foo one small 1 2 1 foo one large 2 4 2 foo one large 2 5 3 foo two small 3 5 4 foo two small 3 6 5 bar one large 4 6 6 bar one small 5 8 7 bar two small 6 9 8 bar two large 7 9 This first example aggregates values by taking the sum. >>> table = pd.pivot_table(df, values='D', index=['A', 'B'], ... columns=['C'], aggfunc=np.sum) >>> table C large small A B bar one 4.0 5.0 two 7.0 6.0 foo one 4.0 1.0 two NaN 6.0 We can also fill missing values using the fill_value parameter. >>> table = pd.pivot_table(df, values='D', index=['A', 'B'], ... columns=['C'], aggfunc=np.sum, fill_value=0) >>> table C large small A B bar one 4 5 two 7 6 foo one 4 1 two 0 6 The next example aggregates by taking the mean across multiple columns. >>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], ... aggfunc={'D': np.mean, ... 'E': np.mean}) >>> table D E A C bar large 5.500000 7.500000 small 5.500000 8.500000 foo large 2.000000 4.500000 small 2.333333 4.333333 We can also calculate multiple types of aggregations for any given value column. >>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], ... aggfunc={'D': np.mean, ... 'E': [min, max, np.mean]}) >>> table D E mean max mean min A C bar large 5.500000 9 7.500000 6 small 5.500000 9 8.500000 8 foo large 2.000000 5 4.500000 4 small 2.333333 6 4.333333 2
pandas.reference.api.pandas.pivot_table
pandas.plotting.andrews_curves pandas.plotting.andrews_curves(frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwargs)[source] Generate a matplotlib plot of Andrews curves, for visualising clusters of multivariate data. Andrews curves have the functional form: f(t) = x_1/sqrt(2) + x_2 sin(t) + x_3 cos(t) + x_4 sin(2t) + x_5 cos(2t) + … Where x coefficients correspond to the values of each dimension and t is linearly spaced between -pi and +pi. Each row of frame then corresponds to a single curve. Parameters frame:DataFrame Data to be plotted, preferably normalized to (0.0, 1.0). class_column:Name of the column containing class names ax:matplotlib axes object, default None samples:Number of points to plot in each curve color:list or tuple, optional Colors to use for the different classes. colormap:str or matplotlib colormap object, default None Colormap to select colors from. If string, load colormap with that name from matplotlib. **kwargs Options to pass to matplotlib plotting method. Returns class:matplotlip.axis.Axes Examples >>> df = pd.read_csv( ... 'https://raw.github.com/pandas-dev/' ... 'pandas/main/pandas/tests/io/data/csv/iris.csv' ... ) >>> pd.plotting.andrews_curves(df, 'Name') <AxesSubplot:title={'center':'width'}>
pandas.reference.api.pandas.plotting.andrews_curves
pandas.plotting.autocorrelation_plot pandas.plotting.autocorrelation_plot(series, ax=None, **kwargs)[source] Autocorrelation plot for time series. Parameters series:Time series ax:Matplotlib axis object, optional **kwargs Options to pass to matplotlib plotting method. Returns class:matplotlib.axis.Axes Examples The horizontal lines in the plot correspond to 95% and 99% confidence bands. The dashed line is 99% confidence band. >>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000) >>> s = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing)) >>> pd.plotting.autocorrelation_plot(s) <AxesSubplot:title={'center':'width'}, xlabel='Lag', ylabel='Autocorrelation'>
pandas.reference.api.pandas.plotting.autocorrelation_plot
pandas.plotting.bootstrap_plot pandas.plotting.bootstrap_plot(series, fig=None, size=50, samples=500, **kwds)[source] Bootstrap plot on mean, median and mid-range statistics. The bootstrap plot is used to estimate the uncertainty of a statistic by relaying on random sampling with replacement [1]. This function will generate bootstrapping plots for mean, median and mid-range statistics for the given number of samples of the given size. 1 “Bootstrapping (statistics)” in https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29 Parameters series:pandas.Series Series from where to get the samplings for the bootstrapping. fig:matplotlib.figure.Figure, default None If given, it will use the fig reference for plotting instead of creating a new one with default parameters. size:int, default 50 Number of data points to consider during each sampling. It must be less than or equal to the length of the series. samples:int, default 500 Number of times the bootstrap procedure is performed. **kwds Options to pass to matplotlib plotting method. Returns matplotlib.figure.Figure Matplotlib figure. See also DataFrame.plot Basic plotting for DataFrame objects. Series.plot Basic plotting for Series objects. Examples This example draws a basic bootstrap plot for a Series. >>> s = pd.Series(np.random.uniform(size=100)) >>> pd.plotting.bootstrap_plot(s) <Figure size 640x480 with 6 Axes>
pandas.reference.api.pandas.plotting.bootstrap_plot
pandas.plotting.boxplot pandas.plotting.boxplot(data, column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, layout=None, return_type=None, **kwargs)[source] Make a box plot from DataFrame columns. Make a box-and-whisker plot from DataFrame columns, optionally grouped by some other columns. A box plot is a method for graphically depicting groups of numerical data through their quartiles. The box extends from the Q1 to Q3 quartile values of the data, with a line at the median (Q2). The whiskers extend from the edges of box to show the range of the data. By default, they extend no more than 1.5 * IQR (IQR = Q3 - Q1) from the edges of the box, ending at the farthest data point within that interval. Outliers are plotted as separate dots. For further details see Wikipedia’s entry for boxplot. Parameters column:str or list of str, optional Column name or list of names, or vector. Can be any valid input to pandas.DataFrame.groupby(). by:str or array-like, optional Column in the DataFrame to pandas.DataFrame.groupby(). One box-plot will be done per value of columns in by. ax:object of class matplotlib.axes.Axes, optional The matplotlib axes to be used by boxplot. fontsize:float or str Tick label font size in points or as a string (e.g., large). rot:int or float, default 0 The rotation angle of labels (in degrees) with respect to the screen coordinate system. grid:bool, default True Setting this to True will show the grid. figsize:A tuple (width, height) in inches The size of the figure to create in matplotlib. layout:tuple (rows, columns), optional For example, (3, 5) will display the subplots using 3 columns and 5 rows, starting from the top-left. return_type:{‘axes’, ‘dict’, ‘both’} or None, default ‘axes’ The kind of object to return. The default is axes. ‘axes’ returns the matplotlib axes the boxplot is drawn on. ‘dict’ returns a dictionary whose values are the matplotlib Lines of the boxplot. ‘both’ returns a namedtuple with the axes and dict. when grouping with by, a Series mapping columns to return_type is returned. If return_type is None, a NumPy array of axes with the same shape as layout is returned. **kwargs All other plotting keyword arguments to be passed to matplotlib.pyplot.boxplot(). Returns result See Notes. See also Series.plot.hist Make a histogram. matplotlib.pyplot.boxplot Matplotlib equivalent plot. Notes The return type depends on the return_type parameter: ‘axes’ : object of class matplotlib.axes.Axes ‘dict’ : dict of matplotlib.lines.Line2D objects ‘both’ : a namedtuple with structure (ax, lines) For data grouped with by, return a Series of the above or a numpy array: Series array (for return_type = None) Use return_type='dict' when you want to tweak the appearance of the lines after plotting. In this case a dict containing the Lines making up the boxes, caps, fliers, medians, and whiskers is returned. Examples Boxplots can be created for every column in the dataframe by df.boxplot() or indicating the columns to be used: >>> np.random.seed(1234) >>> df = pd.DataFrame(np.random.randn(10, 4), ... columns=['Col1', 'Col2', 'Col3', 'Col4']) >>> boxplot = df.boxplot(column=['Col1', 'Col2', 'Col3']) Boxplots of variables distributions grouped by the values of a third variable can be created using the option by. For instance: >>> df = pd.DataFrame(np.random.randn(10, 2), ... columns=['Col1', 'Col2']) >>> df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A', ... 'B', 'B', 'B', 'B', 'B']) >>> boxplot = df.boxplot(by='X') A list of strings (i.e. ['X', 'Y']) can be passed to boxplot in order to group the data by combination of the variables in the x-axis: >>> df = pd.DataFrame(np.random.randn(10, 3), ... columns=['Col1', 'Col2', 'Col3']) >>> df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A', ... 'B', 'B', 'B', 'B', 'B']) >>> df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A', ... 'B', 'A', 'B', 'A', 'B']) >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y']) The layout of boxplot can be adjusted giving a tuple to layout: >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X', ... layout=(2, 1)) Additional formatting can be done to the boxplot, like suppressing the grid (grid=False), rotating the labels in the x-axis (i.e. rot=45) or changing the fontsize (i.e. fontsize=15): >>> boxplot = df.boxplot(grid=False, rot=45, fontsize=15) The parameter return_type can be used to select the type of element returned by boxplot. When return_type='axes' is selected, the matplotlib axes on which the boxplot is drawn are returned: >>> boxplot = df.boxplot(column=['Col1', 'Col2'], return_type='axes') >>> type(boxplot) <class 'matplotlib.axes._subplots.AxesSubplot'> When grouping with by, a Series mapping columns to return_type is returned: >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X', ... return_type='axes') >>> type(boxplot) <class 'pandas.core.series.Series'> If return_type is None, a NumPy array of axes with the same shape as layout is returned: >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X', ... return_type=None) >>> type(boxplot) <class 'numpy.ndarray'>
pandas.reference.api.pandas.plotting.boxplot
pandas.plotting.deregister_matplotlib_converters pandas.plotting.deregister_matplotlib_converters()[source] Remove pandas formatters and converters. Removes the custom converters added by register(). This attempts to set the state of the registry back to the state before pandas registered its own units. Converters for pandas’ own types like Timestamp and Period are removed completely. Converters for types pandas overwrites, like datetime.datetime, are restored to their original value. See also register_matplotlib_converters Register pandas formatters and converters with matplotlib.
pandas.reference.api.pandas.plotting.deregister_matplotlib_converters
pandas.plotting.lag_plot pandas.plotting.lag_plot(series, lag=1, ax=None, **kwds)[source] Lag plot for time series. Parameters series:Time series lag:lag of the scatter plot, default 1 ax:Matplotlib axis object, optional **kwds Matplotlib scatter method keyword arguments. Returns class:matplotlib.axis.Axes Examples Lag plots are most commonly used to look for patterns in time series data. Given the following time series >>> np.random.seed(5) >>> x = np.cumsum(np.random.normal(loc=1, scale=5, size=50)) >>> s = pd.Series(x) >>> s.plot() <AxesSubplot:xlabel='Midrange'> A lag plot with lag=1 returns >>> pd.plotting.lag_plot(s, lag=1) <AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
pandas.reference.api.pandas.plotting.lag_plot
pandas.plotting.parallel_coordinates pandas.plotting.parallel_coordinates(frame, class_column, cols=None, ax=None, color=None, use_columns=False, xticks=None, colormap=None, axvlines=True, axvlines_kwds=None, sort_labels=False, **kwargs)[source] Parallel coordinates plotting. Parameters frame:DataFrame class_column:str Column name containing class names. cols:list, optional A list of column names to use. ax:matplotlib.axis, optional Matplotlib axis object. color:list or tuple, optional Colors to use for the different classes. use_columns:bool, optional If true, columns will be used as xticks. xticks:list or tuple, optional A list of values to use for xticks. colormap:str or matplotlib colormap, default None Colormap to use for line colors. axvlines:bool, optional If true, vertical lines will be added at each xtick. axvlines_kwds:keywords, optional Options to be passed to axvline method for vertical lines. sort_labels:bool, default False Sort class_column labels, useful when assigning colors. **kwargs Options to pass to matplotlib plotting method. Returns class:matplotlib.axis.Axes Examples >>> df = pd.read_csv( ... 'https://raw.github.com/pandas-dev/' ... 'pandas/main/pandas/tests/io/data/csv/iris.csv' ... ) >>> pd.plotting.parallel_coordinates( ... df, 'Name', color=('#556270', '#4ECDC4', '#C7F464') ... ) <AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
pandas.reference.api.pandas.plotting.parallel_coordinates
pandas.plotting.plot_params pandas.plotting.plot_params={'xaxis.compat': False} Stores pandas plotting options. Allows for parameter aliasing so you can just use parameter names that are the same as the plot function parameters, but is stored in a canonical format that makes it easy to breakdown into groups later.
pandas.reference.api.pandas.plotting.plot_params
pandas.plotting.radviz pandas.plotting.radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds)[source] Plot a multidimensional dataset in 2D. Each Series in the DataFrame is represented as a evenly distributed slice on a circle. Each data point is rendered in the circle according to the value on each Series. Highly correlated Series in the DataFrame are placed closer on the unit circle. RadViz allow to project a N-dimensional data set into a 2D space where the influence of each dimension can be interpreted as a balance between the influence of all dimensions. More info available at the original article describing RadViz. Parameters frame:DataFrame Object holding the data. class_column:str Column name containing the name of the data point category. ax:matplotlib.axes.Axes, optional A plot instance to which to add the information. color:list[str] or tuple[str], optional Assign a color to each category. Example: [‘blue’, ‘green’]. colormap:str or matplotlib.colors.Colormap, default None Colormap to select colors from. If string, load colormap with that name from matplotlib. **kwds Options to pass to matplotlib scatter plotting method. Returns class:matplotlib.axes.Axes See also plotting.andrews_curves Plot clustering visualization. Examples >>> df = pd.DataFrame( ... { ... 'SepalLength': [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6], ... 'SepalWidth': [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6], ... 'PetalLength': [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0], ... 'PetalWidth': [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2], ... 'Category': [ ... 'virginica', ... 'virginica', ... 'setosa', ... 'virginica', ... 'virginica', ... 'versicolor', ... 'versicolor', ... 'setosa', ... 'virginica', ... 'setosa' ... ] ... } ... ) >>> pd.plotting.radviz(df, 'Category') <AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
pandas.reference.api.pandas.plotting.radviz
pandas.plotting.register_matplotlib_converters pandas.plotting.register_matplotlib_converters()[source] Register pandas formatters and converters with matplotlib. This function modifies the global matplotlib.units.registry dictionary. pandas adds custom converters for pd.Timestamp pd.Period np.datetime64 datetime.datetime datetime.date datetime.time See also deregister_matplotlib_converters Remove pandas formatters and converters.
pandas.reference.api.pandas.plotting.register_matplotlib_converters
pandas.plotting.scatter_matrix pandas.plotting.scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, grid=False, diagonal='hist', marker='.', density_kwds=None, hist_kwds=None, range_padding=0.05, **kwargs)[source] Draw a matrix of scatter plots. Parameters frame:DataFrame alpha:float, optional Amount of transparency applied. figsize:(float,float), optional A tuple (width, height) in inches. ax:Matplotlib axis object, optional grid:bool, optional Setting this to True will show the grid. diagonal:{‘hist’, ‘kde’} Pick between ‘kde’ and ‘hist’ for either Kernel Density Estimation or Histogram plot in the diagonal. marker:str, optional Matplotlib marker type, default ‘.’. density_kwds:keywords Keyword arguments to be passed to kernel density estimate plot. hist_kwds:keywords Keyword arguments to be passed to hist function. range_padding:float, default 0.05 Relative extension of axis range in x and y with respect to (x_max - x_min) or (y_max - y_min). **kwargs Keyword arguments to be passed to scatter function. Returns numpy.ndarray A matrix of scatter plots. Examples >>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D']) >>> pd.plotting.scatter_matrix(df, alpha=0.2) array([[<AxesSubplot:xlabel='A', ylabel='A'>, <AxesSubplot:xlabel='B', ylabel='A'>, <AxesSubplot:xlabel='C', ylabel='A'>, <AxesSubplot:xlabel='D', ylabel='A'>], [<AxesSubplot:xlabel='A', ylabel='B'>, <AxesSubplot:xlabel='B', ylabel='B'>, <AxesSubplot:xlabel='C', ylabel='B'>, <AxesSubplot:xlabel='D', ylabel='B'>], [<AxesSubplot:xlabel='A', ylabel='C'>, <AxesSubplot:xlabel='B', ylabel='C'>, <AxesSubplot:xlabel='C', ylabel='C'>, <AxesSubplot:xlabel='D', ylabel='C'>], [<AxesSubplot:xlabel='A', ylabel='D'>, <AxesSubplot:xlabel='B', ylabel='D'>, <AxesSubplot:xlabel='C', ylabel='D'>, <AxesSubplot:xlabel='D', ylabel='D'>]], dtype=object)
pandas.reference.api.pandas.plotting.scatter_matrix