pandas.Series.rdiv   Series.rdiv(other, level=None, fill_value=None, axis=0)[source]

Return Floating division of series and other, element-wise (binary operator rtruediv). Equivalent to other / series, but with support to substitute a fill_value for missing data in either one of the inputs.  Parameters

other:Series or scalar value

fill_value:None or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.    Returns
 Series

The result of the operation.      See also  Series.truediv

Element-wise Floating division, see Python documentation for more details.    Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.divide(b, fill_value=0)
a    1.0
b    inf
c    inf
d    0.0
e    NaN
dtype: float64


pandas.Series.rdivmod   Series.rdivmod(other, level=None, fill_value=None, axis=0)[source]

Return Integer division and modulo of series and other, element-wise (binary operator rdivmod). Equivalent to other divmod series, but with support to substitute a fill_value for missing data in either one of the inputs.  Parameters

other:Series or scalar value

fill_value:None or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.    Returns
 2-Tuple of Series

The result of the operation.      See also  Series.divmod

Element-wise Integer division and modulo, see Python documentation for more details.    Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.divmod(b, fill_value=0)
(a    1.0
 b    NaN
 c    NaN
 d    0.0
 e    NaN
 dtype: float64,
 a    0.0
 b    NaN
 c    NaN
 d    0.0
 e    NaN
 dtype: float64)


pandas.Series.reindex   Series.reindex(*args, **kwargs)[source]

Conform Series to new index with optional filling logic. Places NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False.  Parameters

index:array-like, optional

New labels / index to conform to, should be specified using keywords. Preferably an Index object to avoid duplicating data.
method:{None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}

Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index.  None (default): don’t fill gaps pad / ffill: Propagate last valid observation forward to next valid. backfill / bfill: Use next valid observation to fill gap. nearest: Use nearest valid observations to fill gap.
copy:bool, default True

Return a new object, even if the passed indexes are the same.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.
fill_value:scalar, default np.NaN

Value to use for missing values. Defaults to NaN, but can be any “compatible” value.
limit:int, default None

Maximum number of consecutive elements to forward or backward fill.
tolerance:optional

Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most 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
 Series with changed index.
    See also  DataFrame.set_index

Set row labels.  DataFrame.reset_index

Remove row labels or move them to new columns.  DataFrame.reindex_like

Change to same indices as other DataFrame.    Examples DataFrame.reindex supports two calling conventions  (index=index_labels, columns=column_labels, ...) (labels, axis={'index', 'columns'}, ...)  We highly recommend using keyword arguments to clarify your intent. Create a dataframe with some fictional data.
>>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']
>>> df = pd.DataFrame({'http_status': [200, 200, 404, 404, 301],
...                   'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]},
...                   index=index)
>>> df
           http_status  response_time
Firefox            200           0.04
Chrome             200           0.02
Safari             404           0.07
IE10               404           0.08
Konqueror          301           1.00
  Create a new index and reindex the dataframe. By default values in the new index that do not have corresponding records in the dataframe are assigned NaN.
>>> new_index = ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10',
...              'Chrome']
>>> df.reindex(new_index)
               http_status  response_time
Safari               404.0           0.07
Iceweasel              NaN            NaN
Comodo Dragon          NaN            NaN
IE10                 404.0           0.08
Chrome               200.0           0.02
  We can fill in the missing values by passing a value to the keyword fill_value. Because the index is not monotonically increasing or decreasing, we cannot use arguments to the keyword method to fill the NaN values.
>>> df.reindex(new_index, fill_value=0)
               http_status  response_time
Safari                 404           0.07
Iceweasel                0           0.00
Comodo Dragon            0           0.00
IE10                   404           0.08
Chrome                 200           0.02

>>> df.reindex(new_index, fill_value='missing')
              http_status response_time
Safari                404          0.07
Iceweasel         missing       missing
Comodo Dragon     missing       missing
IE10                  404          0.08
Chrome                200          0.02
  We can also reindex the columns.
>>> df.reindex(columns=['http_status', 'user_agent'])
           http_status  user_agent
Firefox            200         NaN
Chrome             200         NaN
Safari             404         NaN
IE10               404         NaN
Konqueror          301         NaN
  Or we can use “axis-style” keyword arguments
>>> df.reindex(['http_status', 'user_agent'], axis="columns")
           http_status  user_agent
Firefox            200         NaN
Chrome             200         NaN
Safari             404         NaN
IE10               404         NaN
Konqueror          301         NaN
  To further illustrate the filling functionality in reindex, we will create a dataframe with a monotonically increasing index (for example, a sequence of dates).
>>> date_index = pd.date_range('1/1/2010', periods=6, freq='D')
>>> df2 = pd.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]},
...                    index=date_index)
>>> df2
            prices
2010-01-01   100.0
2010-01-02   101.0
2010-01-03     NaN
2010-01-04   100.0
2010-01-05    89.0
2010-01-06    88.0
  Suppose we decide to expand the dataframe to cover a wider date range.
>>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D')
>>> df2.reindex(date_index2)
            prices
2009-12-29     NaN
2009-12-30     NaN
2009-12-31     NaN
2010-01-01   100.0
2010-01-02   101.0
2010-01-03     NaN
2010-01-04   100.0
2010-01-05    89.0
2010-01-06    88.0
2010-01-07     NaN
  The index entries that did not have a value in the original data frame (for example, ‘2009-12-29’) are by default filled with NaN. If desired, we can fill in the missing values using one of several options. For example, to back-propagate the last valid value to fill the NaN values, pass bfill as an argument to the method keyword.
>>> df2.reindex(date_index2, method='bfill')
            prices
2009-12-29   100.0
2009-12-30   100.0
2009-12-31   100.0
2010-01-01   100.0
2010-01-02   101.0
2010-01-03     NaN
2010-01-04   100.0
2010-01-05    89.0
2010-01-06    88.0
2010-01-07     NaN
  Please note that the NaN value present in the original dataframe (at index value 2010-01-03) will not be filled by any of the value propagation schemes. This is because filling while reindexing does not look at dataframe values, but only compares the original and desired indexes. If you do want to fill in the NaN values present in the original dataframe, use the fillna() method. See the user guide for more.


pandas.Series.reindex_like   Series.reindex_like(other, method=None, copy=True, limit=None, tolerance=None)[source]

Return an object with matching indices as other object. Conform the object to the same index on all axes. Optional filling logic, placing NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False.  Parameters

other:Object of the same data type

Its row and column indices are used to define the new indices of this object.
method:{None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}

Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index.  None (default): don’t fill gaps pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap nearest: use nearest valid observations to fill gap.
copy:bool, default True

Return a new object, even if the passed indexes are the same.
limit:int, default None

Maximum number of consecutive labels to fill 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
 Series or DataFrame

Same type as caller, but with changed indices on each axis.      See also  DataFrame.set_index

Set row labels.  DataFrame.reset_index

Remove row labels or move them to new columns.  DataFrame.reindex

Change to new indices or expand indices.    Notes Same as calling .reindex(index=other.index, columns=other.columns,...). Examples
>>> df1 = pd.DataFrame([[24.3, 75.7, 'high'],
...                     [31, 87.8, 'high'],
...                     [22, 71.6, 'medium'],
...                     [35, 95, 'medium']],
...                    columns=['temp_celsius', 'temp_fahrenheit',
...                             'windspeed'],
...                    index=pd.date_range(start='2014-02-12',
...                                        end='2014-02-15', freq='D'))

>>> df1
            temp_celsius  temp_fahrenheit windspeed
2014-02-12          24.3             75.7      high
2014-02-13          31.0             87.8      high
2014-02-14          22.0             71.6    medium
2014-02-15          35.0             95.0    medium

>>> df2 = pd.DataFrame([[28, 'low'],
...                     [30, 'low'],
...                     [35.1, 'medium']],
...                    columns=['temp_celsius', 'windspeed'],
...                    index=pd.DatetimeIndex(['2014-02-12', '2014-02-13',
...                                            '2014-02-15']))

>>> df2
            temp_celsius windspeed
2014-02-12          28.0       low
2014-02-13          30.0       low
2014-02-15          35.1    medium

>>> df2.reindex_like(df1)
            temp_celsius  temp_fahrenheit windspeed
2014-02-12          28.0              NaN       low
2014-02-13          30.0              NaN       low
2014-02-14           NaN              NaN       NaN
2014-02-15          35.1              NaN    medium


pandas.Series.rename   Series.rename(index=None, *, axis=None, copy=True, inplace=False, level=None, errors='ignore')[source]

Alter Series index labels or name. 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. See the user guide for more.  Parameters

axis:{0 or “index”}

Unused. Accepted for compatibility with DataFrame method only.
index:scalar, hashable sequence, dict-like or function, optional

Functions or dict-like are transformations to apply to the index. Scalar or hashable sequence-like will alter the Series.name attribute.  **kwargs

Additional keyword arguments passed to the function. Only the “inplace” keyword is used.    Returns
 Series or None

Series with index labels or name altered or None if inplace=True.      See also  DataFrame.rename

Corresponding DataFrame method.  Series.rename_axis

Set the name of the 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


pandas.Series.rename_axis   Series.rename_axis(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False)[source]

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. Note that the columns parameter is not allowed if the object is a Series. This parameter only apply for DataFrame type objects. Use either mapper and axis to specify the axis to target with mapper, or index and/or columns.
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=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 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 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.Series.reorder_levels   Series.reorder_levels(order)[source]

Rearrange index levels using input order. May not drop or duplicate levels.  Parameters

order:list of int representing new level order

Reference level by number or key.    Returns
 type of caller (new object)


pandas.Series.repeat   Series.repeat(repeats, axis=None)[source]

Repeat elements of a Series. Returns a new Series where each element of the current Series is repeated consecutively a given number of times.  Parameters

repeats:int or array of ints

The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty Series.
axis:None

Must be None. Has no effect but is accepted for compatibility with numpy.    Returns
 Series

Newly created Series with repeated elements.      See also  Index.repeat

Equivalent function for Index.  numpy.repeat

Similar method for numpy.ndarray.    Examples
>>> s = pd.Series(['a', 'b', 'c'])
>>> s
0    a
1    b
2    c
dtype: object
>>> s.repeat(2)
0    a
0    a
1    b
1    b
2    c
2    c
dtype: object
>>> s.repeat([1, 2, 3])
0    a
1    b
1    b
2    c
2    c
2    c
dtype: object


pandas.Series.replace   Series.replace(to_replace=None, value=NoDefault.no_default, inplace=False, limit=None, regex=False, method=NoDefault.no_default)[source]

Replace values given in to_replace with value. Values of the Series are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value.  Parameters

to_replace:str, regex, list, dict, Series, int, float, or None

How to find the values that will be replaced.
numeric, str or regex:
 numeric: numeric values equal to to_replace will be replaced with value str: string exactly matching to_replace will be replaced with value regex: regexs matching to_replace will be replaced with value

list of str, regex, or numeric:
 First, if to_replace and value are both lists, they must be the same length. Second, if regex=True then all of the strings in both lists will be interpreted as regexs otherwise they will match directly. This doesn’t matter much for value since there are only a few possible substitution regexes you can use. str, regex and numeric rules apply as above.

dict:
 Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’ with ‘z’. To use a dict in this way the value parameter should be None. For a DataFrame a dict can specify that different values should be replaced in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1 in column ‘a’ and the value ‘z’ in column ‘b’ and replaces these values with whatever is specified in value. The value parameter should not be None in this case. You can treat this as a special case of passing two lists except that you are specifying the column to search in. For a DataFrame nested dictionaries, e.g., {'a': {'b': np.nan}}, are read as follows: look in column ‘a’ for the value ‘b’ and replace it with NaN. The value parameter should be None to use a nested dict in this way. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested dictionary) cannot be regular expressions.

None:
 This means that the regex argument must be a string, compiled regular expression, or list, dict, ndarray or Series of such elements. If value is also None then this must be a nested dictionary or Series.
   See the examples section for examples of each of these.
value:scalar, dict, list, str, regex, default None

Value to replace any values matching to_replace with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed.
inplace:bool, default False

If True, performs operation inplace and returns None.
limit:int, default None

Maximum size gap to forward or backward fill.
regex:bool or same types as to_replace, default False

Whether to interpret to_replace and/or value as regular expressions. If this is True then to_replace must be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case to_replace must be None.
method:{‘pad’, ‘ffill’, ‘bfill’, None}

The method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.  Changed in version 0.23.0: Added to DataFrame.     Returns
 Series

Object after replacement.    Raises
 AssertionError

 If regex is not a bool and to_replace is not None.   TypeError

 If to_replace is not a scalar, array-like, dict, or None If to_replace is a dict and value is not a list, dict, ndarray, or Series If to_replace is None and regex is not compilable into a regular expression or is a list, dict, ndarray, or Series. When replacing multiple bool or datetime64 objects and the arguments to to_replace does not match the type of the value being replaced   ValueError

 If a list or an ndarray is passed to to_replace and value but they are not the same length.       See also  Series.fillna

Fill NA values.  Series.where

Replace values based on boolean condition.  Series.str.replace

Simple string replacement.    Notes  Regex substitution is performed under the hood with re.sub. The rules for substitution for re.sub are the same. Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched. However, if those floating point numbers are strings, then you can do this. This method has a lot of options. You are encouraged to experiment and play with this method to gain intuition about how it works. When dict is used as the to_replace value, it is like key(s) in the dict are the to_replace part and value(s) in the dict are the value parameter.  Examples Scalar `to_replace` and `value`
>>> s = pd.Series([1, 2, 3, 4, 5])
>>> s.replace(1, 5)
0    5
1    2
2    3
3    4
4    5
dtype: int64

>>> df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
...                    'B': [5, 6, 7, 8, 9],
...                    'C': ['a', 'b', 'c', 'd', 'e']})
>>> df.replace(0, 5)
    A  B  C
0  5  5  a
1  1  6  b
2  2  7  c
3  3  8  d
4  4  9  e
  List-like `to_replace`
>>> df.replace([0, 1, 2, 3], 4)
    A  B  C
0  4  5  a
1  4  6  b
2  4  7  c
3  4  8  d
4  4  9  e

>>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
    A  B  C
0  4  5  a
1  3  6  b
2  2  7  c
3  1  8  d
4  4  9  e

>>> s.replace([1, 2], method='bfill')
0    3
1    3
2    3
3    4
4    5
dtype: int64
  dict-like `to_replace`
>>> df.replace({0: 10, 1: 100})
        A  B  C
0   10  5  a
1  100  6  b
2    2  7  c
3    3  8  d
4    4  9  e

>>> df.replace({'A': 0, 'B': 5}, 100)
        A    B  C
0  100  100  a
1    1    6  b
2    2    7  c
3    3    8  d
4    4    9  e

>>> df.replace({'A': {0: 100, 4: 400}})
        A  B  C
0  100  5  a
1    1  6  b
2    2  7  c
3    3  8  d
4  400  9  e
  Regular expression `to_replace`
>>> df = pd.DataFrame({'A': ['bat', 'foo', 'bait'],
...                    'B': ['abc', 'bar', 'xyz']})
>>> df.replace(to_replace=r'^ba.$', value='new', regex=True)
        A    B
0   new  abc
1   foo  new
2  bait  xyz

>>> df.replace({'A': r'^ba.$'}, {'A': 'new'}, regex=True)
        A    B
0   new  abc
1   foo  bar
2  bait  xyz

>>> df.replace(regex=r'^ba.$', value='new')
        A    B
0   new  abc
1   foo  new
2  bait  xyz

>>> df.replace(regex={r'^ba.$': 'new', 'foo': 'xyz'})
        A    B
0   new  abc
1   xyz  new
2  bait  xyz

>>> df.replace(regex=[r'^ba.$', 'foo'], value='new')
        A    B
0   new  abc
1   new  new
2  bait  xyz
  Compare the behavior of s.replace({'a': None}) and s.replace('a', None) to understand the peculiarities of the to_replace parameter:
>>> s = pd.Series([10, 'a', 'a', 'b', 'a'])
  When one uses a dict as the to_replace value, it is like the value(s) in the dict are equal to the value parameter. s.replace({'a': None}) is equivalent to s.replace(to_replace={'a': None}, value=None, method=None):
>>> s.replace({'a': None})
0      10
1    None
2    None
3       b
4    None
dtype: object
  When value is not explicitly passed and to_replace is a scalar, list or tuple, replace uses the method parameter (default ‘pad’) to do the replacement. So this is why the ‘a’ values are being replaced by 10 in rows 1 and 2 and ‘b’ in row 4 in this case.
>>> s.replace('a')
0    10
1    10
2    10
3     b
4     b
dtype: object
  On the other hand, if None is explicitly passed for value, it will be respected:
>>> s.replace('a', None)
0      10
1    None
2    None
3       b
4    None
dtype: object

 Changed in version 1.4.0: Previously the explicit None was silently ignored.


pandas.Series.resample   Series.resample(rule, axis=0, closed=None, label=None, convention='start', kind=None, loffset=None, base=None, on=None, level=None, origin='start_day', offset=None)[source]

Resample time-series data. Convenience method for frequency conversion and resampling of time series. The object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or the caller must pass the label of a datetime-like series/index to the on/level keyword parameter.  Parameters

rule:DateOffset, Timedelta or str

The offset string or object representing target conversion.
axis:{0 or ‘index’, 1 or ‘columns’}, default 0

Which axis to use for up- or down-sampling. For Series this will default to 0, i.e. along the rows. Must be DatetimeIndex, TimedeltaIndex or PeriodIndex.
closed:{‘right’, ‘left’}, default None

Which side of bin interval is closed. The default is ‘left’ for all frequency offsets except for ‘M’, ‘A’, ‘Q’, ‘BM’, ‘BA’, ‘BQ’, and ‘W’ which all have a default of ‘right’.
label:{‘right’, ‘left’}, default None

Which bin edge label to label bucket with. The default is ‘left’ for all frequency offsets except for ‘M’, ‘A’, ‘Q’, ‘BM’, ‘BA’, ‘BQ’, and ‘W’ which all have a default of ‘right’.
convention:{‘start’, ‘end’, ‘s’, ‘e’}, default ‘start’

For PeriodIndex only, controls whether to use the start or end of rule.
kind:{‘timestamp’, ‘period’}, optional, default None

Pass ‘timestamp’ to convert the resulting index to a DateTimeIndex or ‘period’ to convert it to a PeriodIndex. By default the input representation is retained.
loffset:timedelta, default None

Adjust the resampled time labels.  Deprecated since version 1.1.0: You should add the loffset to the df.index after the resample. See below.
base:int, default 0

For frequencies that evenly subdivide 1 day, the “origin” of the aggregated intervals. For example, for ‘5min’ frequency, base could range from 0 through 4. Defaults to 0.  Deprecated since version 1.1.0: The new arguments that you should use are ‘offset’ or ‘origin’.
on:str, optional

For a DataFrame, column to use instead of index for resampling. Column must be datetime-like.
level:str or int, optional

For a MultiIndex, level (name or number) to use for resampling. level must be datetime-like.
origin:Timestamp or str, default ‘start_day’

The timestamp on which to adjust the grouping. The timezone of origin must match the timezone of the index. If string, must be one of the following:  ‘epoch’: origin is 1970-01-01 ‘start’: origin is the first value of the timeseries ‘start_day’: origin is the first day at midnight of the timeseries   New in version 1.1.0.   ‘end’: origin is the last value of the timeseries ‘end_day’: origin is the ceiling midnight of the last day   New in version 1.3.0.
offset:Timedelta or str, default is None

An offset timedelta added to the origin.  New in version 1.1.0.     Returns
 pandas.core.Resampler

Resampler object.      See also  Series.resample

Resample a Series.  DataFrame.resample

Resample a DataFrame.  groupby

Group Series by mapping, function, label, or list of labels.  asfreq

Reindex a Series with the given frequency without grouping.    Notes See the user guide for more. To learn more about the offset strings, please see this link. Examples Start by creating a series with 9 one minute timestamps.
>>> index = pd.date_range('1/1/2000', periods=9, freq='T')
>>> series = pd.Series(range(9), index=index)
>>> series
2000-01-01 00:00:00    0
2000-01-01 00:01:00    1
2000-01-01 00:02:00    2
2000-01-01 00:03:00    3
2000-01-01 00:04:00    4
2000-01-01 00:05:00    5
2000-01-01 00:06:00    6
2000-01-01 00:07:00    7
2000-01-01 00:08:00    8
Freq: T, dtype: int64
  Downsample the series into 3 minute bins and sum the values of the timestamps falling into a bin.
>>> series.resample('3T').sum()
2000-01-01 00:00:00     3
2000-01-01 00:03:00    12
2000-01-01 00:06:00    21
Freq: 3T, dtype: int64
  Downsample the series into 3 minute bins as above, but label each bin using the right edge instead of the left. Please note that the value in the bucket used as the label is not included in the bucket, which it labels. For example, in the original series the bucket 2000-01-01 00:03:00 contains the value 3, but the summed value in the resampled bucket with the label 2000-01-01 00:03:00 does not include 3 (if it did, the summed value would be 6, not 3). To include this value close the right side of the bin interval as illustrated in the example below this one.
>>> series.resample('3T', label='right').sum()
2000-01-01 00:03:00     3
2000-01-01 00:06:00    12
2000-01-01 00:09:00    21
Freq: 3T, dtype: int64
  Downsample the series into 3 minute bins as above, but close the right side of the bin interval.
>>> series.resample('3T', label='right', closed='right').sum()
2000-01-01 00:00:00     0
2000-01-01 00:03:00     6
2000-01-01 00:06:00    15
2000-01-01 00:09:00    15
Freq: 3T, dtype: int64
  Upsample the series into 30 second bins.
>>> series.resample('30S').asfreq()[0:5]   # Select first 5 rows
2000-01-01 00:00:00   0.0
2000-01-01 00:00:30   NaN
2000-01-01 00:01:00   1.0
2000-01-01 00:01:30   NaN
2000-01-01 00:02:00   2.0
Freq: 30S, dtype: float64
  Upsample the series into 30 second bins and fill the NaN values using the pad method.
>>> series.resample('30S').pad()[0:5]
2000-01-01 00:00:00    0
2000-01-01 00:00:30    0
2000-01-01 00:01:00    1
2000-01-01 00:01:30    1
2000-01-01 00:02:00    2
Freq: 30S, dtype: int64
  Upsample the series into 30 second bins and fill the NaN values using the bfill method.
>>> series.resample('30S').bfill()[0:5]
2000-01-01 00:00:00    0
2000-01-01 00:00:30    1
2000-01-01 00:01:00    1
2000-01-01 00:01:30    2
2000-01-01 00:02:00    2
Freq: 30S, dtype: int64
  Pass a custom function via apply
>>> def custom_resampler(arraylike):
...     return np.sum(arraylike) + 5
...
>>> series.resample('3T').apply(custom_resampler)
2000-01-01 00:00:00     8
2000-01-01 00:03:00    17
2000-01-01 00:06:00    26
Freq: 3T, dtype: int64
  For a Series with a PeriodIndex, the keyword convention can be used to control whether to use the start or end of rule. Resample a year by quarter using ‘start’ convention. Values are assigned to the first quarter of the period.
>>> s = pd.Series([1, 2], index=pd.period_range('2012-01-01',
...                                             freq='A',
...                                             periods=2))
>>> s
2012    1
2013    2
Freq: A-DEC, dtype: int64
>>> s.resample('Q', convention='start').asfreq()
2012Q1    1.0
2012Q2    NaN
2012Q3    NaN
2012Q4    NaN
2013Q1    2.0
2013Q2    NaN
2013Q3    NaN
2013Q4    NaN
Freq: Q-DEC, dtype: float64
  Resample quarters by month using ‘end’ convention. Values are assigned to the last month of the period.
>>> q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018-01-01',
...                                                   freq='Q',
...                                                   periods=4))
>>> q
2018Q1    1
2018Q2    2
2018Q3    3
2018Q4    4
Freq: Q-DEC, dtype: int64
>>> q.resample('M', convention='end').asfreq()
2018-03    1.0
2018-04    NaN
2018-05    NaN
2018-06    2.0
2018-07    NaN
2018-08    NaN
2018-09    3.0
2018-10    NaN
2018-11    NaN
2018-12    4.0
Freq: M, dtype: float64
  For DataFrame objects, the keyword on can be used to specify the column instead of the index for resampling.
>>> d = {'price': [10, 11, 9, 13, 14, 18, 17, 19],
...      'volume': [50, 60, 40, 100, 50, 100, 40, 50]}
>>> df = pd.DataFrame(d)
>>> df['week_starting'] = pd.date_range('01/01/2018',
...                                     periods=8,
...                                     freq='W')
>>> df
   price  volume week_starting
0     10      50    2018-01-07
1     11      60    2018-01-14
2      9      40    2018-01-21
3     13     100    2018-01-28
4     14      50    2018-02-04
5     18     100    2018-02-11
6     17      40    2018-02-18
7     19      50    2018-02-25
>>> df.resample('M', on='week_starting').mean()
               price  volume
week_starting
2018-01-31     10.75    62.5
2018-02-28     17.00    60.0
  For a DataFrame with MultiIndex, the keyword level can be used to specify on which level the resampling needs to take place.
>>> days = pd.date_range('1/1/2000', periods=4, freq='D')
>>> d2 = {'price': [10, 11, 9, 13, 14, 18, 17, 19],
...       'volume': [50, 60, 40, 100, 50, 100, 40, 50]}
>>> df2 = pd.DataFrame(
...     d2,
...     index=pd.MultiIndex.from_product(
...         [days, ['morning', 'afternoon']]
...     )
... )
>>> df2
                      price  volume
2000-01-01 morning       10      50
           afternoon     11      60
2000-01-02 morning        9      40
           afternoon     13     100
2000-01-03 morning       14      50
           afternoon     18     100
2000-01-04 morning       17      40
           afternoon     19      50
>>> df2.resample('D', level=0).sum()
            price  volume
2000-01-01     21     110
2000-01-02     22     140
2000-01-03     32     150
2000-01-04     36      90
  If you want to adjust the start of the bins based on a fixed timestamp:
>>> start, end = '2000-10-01 23:30:00', '2000-10-02 00:30:00'
>>> rng = pd.date_range(start, end, freq='7min')
>>> ts = pd.Series(np.arange(len(rng)) * 3, index=rng)
>>> ts
2000-10-01 23:30:00     0
2000-10-01 23:37:00     3
2000-10-01 23:44:00     6
2000-10-01 23:51:00     9
2000-10-01 23:58:00    12
2000-10-02 00:05:00    15
2000-10-02 00:12:00    18
2000-10-02 00:19:00    21
2000-10-02 00:26:00    24
Freq: 7T, dtype: int64

>>> ts.resample('17min').sum()
2000-10-01 23:14:00     0
2000-10-01 23:31:00     9
2000-10-01 23:48:00    21
2000-10-02 00:05:00    54
2000-10-02 00:22:00    24
Freq: 17T, dtype: int64

>>> ts.resample('17min', origin='epoch').sum()
2000-10-01 23:18:00     0
2000-10-01 23:35:00    18
2000-10-01 23:52:00    27
2000-10-02 00:09:00    39
2000-10-02 00:26:00    24
Freq: 17T, dtype: int64

>>> ts.resample('17min', origin='2000-01-01').sum()
2000-10-01 23:24:00     3
2000-10-01 23:41:00    15
2000-10-01 23:58:00    45
2000-10-02 00:15:00    45
Freq: 17T, dtype: int64
  If you want to adjust the start of the bins with an offset Timedelta, the two following lines are equivalent:
>>> ts.resample('17min', origin='start').sum()
2000-10-01 23:30:00     9
2000-10-01 23:47:00    21
2000-10-02 00:04:00    54
2000-10-02 00:21:00    24
Freq: 17T, dtype: int64

>>> ts.resample('17min', offset='23h30min').sum()
2000-10-01 23:30:00     9
2000-10-01 23:47:00    21
2000-10-02 00:04:00    54
2000-10-02 00:21:00    24
Freq: 17T, dtype: int64
  If you want to take the largest Timestamp as the end of the bins:
>>> ts.resample('17min', origin='end').sum()
2000-10-01 23:35:00     0
2000-10-01 23:52:00    18
2000-10-02 00:09:00    27
2000-10-02 00:26:00    63
Freq: 17T, dtype: int64
  In contrast with the start_day, you can use end_day to take the ceiling midnight of the largest Timestamp as the end of the bins and drop the bins not containing data:
>>> ts.resample('17min', origin='end_day').sum()
2000-10-01 23:38:00     3
2000-10-01 23:55:00    15
2000-10-02 00:12:00    45
2000-10-02 00:29:00    45
Freq: 17T, dtype: int64
  To replace the use of the deprecated base argument, you can now use offset, in this example it is equivalent to have base=2:
>>> ts.resample('17min', offset='2min').sum()
2000-10-01 23:16:00     0
2000-10-01 23:33:00     9
2000-10-01 23:50:00    36
2000-10-02 00:07:00    39
2000-10-02 00:24:00    24
Freq: 17T, dtype: int64
  To replace the use of the deprecated loffset argument:
>>> from pandas.tseries.frequencies import to_offset
>>> loffset = '19min'
>>> ts_out = ts.resample('17min').sum()
>>> ts_out.index = ts_out.index + to_offset(loffset)
>>> ts_out
2000-10-01 23:33:00     0
2000-10-01 23:50:00     9
2000-10-02 00:07:00    21
2000-10-02 00:24:00    54
2000-10-02 00:41:00    24
Freq: 17T, dtype: int64


pandas.Series.reset_index   Series.reset_index(level=None, drop=False, name=NoDefault.no_default, inplace=False)[source]

Generate a new DataFrame or Series with the index reset. This is useful when the index needs to be treated as a column, or when the index is meaningless and needs to be reset to the default before another operation.  Parameters

level:int, str, tuple, or list, default optional

For a Series with a MultiIndex, only remove the specified levels from the index. Removes all levels by default.
drop:bool, default False

Just reset the index, without inserting it as a column in the new DataFrame.
name:object, optional

The name to use for the column containing the original Series values. Uses self.name by default. This argument is ignored when drop is True.
inplace:bool, default False

Modify the Series in place (do not create a new object).    Returns
 Series or DataFrame or None

When drop is False (the default), a DataFrame is returned. The newly created columns will come first in the DataFrame, followed by the original Series values. When drop is True, a Series is returned. In either case, if inplace=True, no value is returned.      See also  DataFrame.reset_index

Analogous function for DataFrame.    Examples
>>> s = pd.Series([1, 2, 3, 4], name='foo',
...               index=pd.Index(['a', 'b', 'c', 'd'], name='idx'))
  Generate a DataFrame with default index.
>>> s.reset_index()
  idx  foo
0   a    1
1   b    2
2   c    3
3   d    4
  To specify the name of the new column use name.
>>> s.reset_index(name='values')
  idx  values
0   a       1
1   b       2
2   c       3
3   d       4
  To generate a new Series with the default set drop to True.
>>> s.reset_index(drop=True)
0    1
1    2
2    3
3    4
Name: foo, dtype: int64
  To update the Series in place, without generating a new one set inplace to True. Note that it also requires drop=True.
>>> s.reset_index(inplace=True, drop=True)
>>> s
0    1
1    2
2    3
3    4
Name: foo, dtype: int64
  The level parameter is interesting for Series with a multi-level index.
>>> arrays = [np.array(['bar', 'bar', 'baz', 'baz']),
...           np.array(['one', 'two', 'one', 'two'])]
>>> s2 = pd.Series(
...     range(4), name='foo',
...     index=pd.MultiIndex.from_arrays(arrays,
...                                     names=['a', 'b']))
  To remove a specific level from the Index, use level.
>>> s2.reset_index(level='a')
       a  foo
b
one  bar    0
two  bar    1
one  baz    2
two  baz    3
  If level is not set, all levels are removed from the Index.
>>> s2.reset_index()
     a    b  foo
0  bar  one    0
1  bar  two    1
2  baz  one    2
3  baz  two    3


pandas.Series.rfloordiv   Series.rfloordiv(other, level=None, fill_value=None, axis=0)[source]

Return Integer division of series and other, element-wise (binary operator rfloordiv). Equivalent to other // series, but with support to substitute a fill_value for missing data in either one of the inputs.  Parameters

other:Series or scalar value

fill_value:None or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.    Returns
 Series

The result of the operation.      See also  Series.floordiv

Element-wise Integer division, see Python documentation for more details.    Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.floordiv(b, fill_value=0)
a    1.0
b    NaN
c    NaN
d    0.0
e    NaN
dtype: float64


pandas.Series.rmod   Series.rmod(other, level=None, fill_value=None, axis=0)[source]

Return Modulo of series and other, element-wise (binary operator rmod). Equivalent to other % series, but with support to substitute a fill_value for missing data in either one of the inputs.  Parameters

other:Series or scalar value

fill_value:None or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.    Returns
 Series

The result of the operation.      See also  Series.mod

Element-wise Modulo, see Python documentation for more details.    Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.mod(b, fill_value=0)
a    0.0
b    NaN
c    NaN
d    0.0
e    NaN
dtype: float64


pandas.Series.rmul   Series.rmul(other, level=None, fill_value=None, axis=0)[source]

Return Multiplication of series and other, element-wise (binary operator rmul). Equivalent to other * series, but with support to substitute a fill_value for missing data in either one of the inputs.  Parameters

other:Series or scalar value

fill_value:None or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.    Returns
 Series

The result of the operation.      See also  Series.mul

Element-wise Multiplication, see Python documentation for more details.    Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.multiply(b, fill_value=0)
a    1.0
b    0.0
c    0.0
d    0.0
e    NaN
dtype: float64


pandas.Series.rolling   Series.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None, method='single')[source]

Provide rolling window calculations.  Parameters

window:int, offset, or BaseIndexer subclass

Size of the moving window. If an integer, the fixed number of observations used for each window. If an offset, the time period of each window. Each window will be a variable sized based on the observations included in the time-period. This is only valid for datetimelike indexes. To learn more about the offsets & frequency strings, please see this link. If a BaseIndexer subclass, the window boundaries based on the defined get_window_bounds method. Additional rolling keyword arguments, namely min_periods, center, and closed will be passed to get_window_bounds.
min_periods:int, default None

Minimum number of observations in window required to have a value; otherwise, result is np.nan. For a window that is specified by an offset, min_periods will default to 1. For a window that is specified by an integer, min_periods will default to the size of the window.
center:bool, default False

If False, set the window labels as the right edge of the window index. If True, set the window labels as the center of the window index.
win_type:str, default None

If None, all points are evenly weighted. If a string, it must be a valid scipy.signal window function. Certain Scipy window types require additional parameters to be passed in the aggregation function. The additional parameters must match the keywords specified in the Scipy window type method signature.
on:str, optional

For a DataFrame, a column label or Index level on which to calculate the rolling window, rather than the DataFrame’s index. Provided integer column is ignored and excluded from result since an integer index is not used to calculate the rolling window.
axis:int or str, default 0

If 0 or 'index', roll across the rows. If 1 or 'columns', roll across the columns.
closed:str, default None

If 'right', the first point in the window is excluded from calculations. If 'left', the last point in the window is excluded from calculations. If 'both', the no points in the window are excluded from calculations. If 'neither', the first and last points in the window are excluded from calculations. Default None ('right').  Changed in version 1.2.0: The closed parameter with fixed windows is now supported.
method:str {‘single’, ‘table’}, default ‘single’

 New in version 1.3.0.  Execute the rolling operation per single column or row ('single') or over the entire object ('table'). This argument is only implemented when specifying engine='numba' in the method call.    Returns

Window subclass if a win_type is passed

Rolling subclass if win_type is not passed
    See also  expanding

Provides expanding transformations.  ewm

Provides exponential weighted functions.    Notes See Windowing Operations for further usage details and examples. Examples
>>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})
>>> df
     B
0  0.0
1  1.0
2  2.0
3  NaN
4  4.0
  window Rolling sum with a window length of 2 observations.
>>> df.rolling(2).sum()
     B
0  NaN
1  1.0
2  3.0
3  NaN
4  NaN
  Rolling sum with a window span of 2 seconds.
>>> df_time = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]},
...                        index = [pd.Timestamp('20130101 09:00:00'),
...                                 pd.Timestamp('20130101 09:00:02'),
...                                 pd.Timestamp('20130101 09:00:03'),
...                                 pd.Timestamp('20130101 09:00:05'),
...                                 pd.Timestamp('20130101 09:00:06')])

>>> df_time
                       B
2013-01-01 09:00:00  0.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0

>>> df_time.rolling('2s').sum()
                       B
2013-01-01 09:00:00  0.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  3.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0
  Rolling sum with forward looking windows with 2 observations.
>>> indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
>>> df.rolling(window=indexer, min_periods=1).sum()
     B
0  1.0
1  3.0
2  2.0
3  4.0
4  4.0
  min_periods Rolling sum with a window length of 2 observations, but only needs a minimum of 1 observation to calculate a value.
>>> df.rolling(2, min_periods=1).sum()
     B
0  0.0
1  1.0
2  3.0
3  2.0
4  4.0
  center Rolling sum with the result assigned to the center of the window index.
>>> df.rolling(3, min_periods=1, center=True).sum()
     B
0  1.0
1  3.0
2  3.0
3  6.0
4  4.0

>>> df.rolling(3, min_periods=1, center=False).sum()
     B
0  0.0
1  1.0
2  3.0
3  3.0
4  6.0
  win_type Rolling sum with a window length of 2, using the Scipy 'gaussian' window type. std is required in the aggregation function.
>>> df.rolling(2, win_type='gaussian').sum(std=3)
          B
0       NaN
1  0.986207
2  2.958621
3       NaN
4       NaN


pandas.Series.round   Series.round(decimals=0, *args, **kwargs)[source]

Round each value in a Series to the given number of decimals.  Parameters

decimals:int, default 0

Number of decimal places to round to. If decimals is negative, it specifies the number of positions to the left of the decimal point.  *args, **kwargs

Additional arguments and keywords have no effect but might be accepted for compatibility with NumPy.    Returns
 Series

Rounded values of the Series.      See also  numpy.around

Round values of an np.array.  DataFrame.round

Round values of a DataFrame.    Examples
>>> s = pd.Series([0.1, 1.3, 2.7])
>>> s.round()
0    0.0
1    1.0
2    3.0
dtype: float64


pandas.Series.rpow   Series.rpow(other, level=None, fill_value=None, axis=0)[source]

Return Exponential power of series and other, element-wise (binary operator rpow). Equivalent to other ** series, but with support to substitute a fill_value for missing data in either one of the inputs.  Parameters

other:Series or scalar value

fill_value:None or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.    Returns
 Series

The result of the operation.      See also  Series.pow

Element-wise Exponential power, see Python documentation for more details.    Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.pow(b, fill_value=0)
a    1.0
b    1.0
c    1.0
d    0.0
e    NaN
dtype: float64


pandas.Series.rsub   Series.rsub(other, level=None, fill_value=None, axis=0)[source]

Return Subtraction of series and other, element-wise (binary operator rsub). Equivalent to other - series, but with support to substitute a fill_value for missing data in either one of the inputs.  Parameters

other:Series or scalar value

fill_value:None or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.    Returns
 Series

The result of the operation.      See also  Series.sub

Element-wise Subtraction, see Python documentation for more details.    Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.subtract(b, fill_value=0)
a    0.0
b    1.0
c    1.0
d   -1.0
e    NaN
dtype: float64


pandas.Series.rtruediv   Series.rtruediv(other, level=None, fill_value=None, axis=0)[source]

Return Floating division of series and other, element-wise (binary operator rtruediv). Equivalent to other / series, but with support to substitute a fill_value for missing data in either one of the inputs.  Parameters

other:Series or scalar value

fill_value:None or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.
level:int or name

Broadcast across a level, matching Index values on the passed MultiIndex level.    Returns
 Series

The result of the operation.      See also  Series.truediv

Element-wise Floating division, see Python documentation for more details.    Examples
>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.divide(b, fill_value=0)
a    1.0
b    inf
c    inf
d    0.0
e    NaN
dtype: float64


pandas.Series.sample   Series.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, ignore_index=False)[source]

Return a random sample of items from an axis of object. You can use random_state for reproducibility.  Parameters

n:int, optional

Number of items from axis to return. Cannot be used with frac. Default = 1 if frac = None.
frac:float, optional

Fraction of axis items to return. Cannot be used with n.
replace:bool, default False

Allow or disallow sampling of the same row more than once.
weights:str or ndarray-like, optional

Default ‘None’ results in equal probability weighting. If passed a Series, will align with target object on index. Index values in weights not found in sampled object will be ignored and index values in sampled object not in weights will be assigned weights of zero. If called on a DataFrame, will accept the name of a column when axis = 0. Unless weights are a Series, weights must be same length as axis being sampled. If weights do not sum to 1, they will be normalized to sum to 1. Missing values in the weights column will be treated as zero. Infinite values not allowed.
random_state:int, array-like, BitGenerator, np.random.RandomState, np.random.Generator, optional

If int, array-like, or BitGenerator, seed for random number generator. If np.random.RandomState or np.random.Generator, use as given.  Changed in version 1.1.0: array-like and BitGenerator object now passed to np.random.RandomState() as seed   Changed in version 1.4.0: np.random.Generator objects now accepted
axis:{0 or ‘index’, 1 or ‘columns’, None}, default None

Axis to sample. Accepts axis number or name. Default is stat axis for given data type (0 for Series and DataFrames).
ignore_index:bool, default False

If True, the resulting index will be labeled 0, 1, …, n - 1.  New in version 1.3.0.     Returns
 Series or DataFrame

A new object of same type as caller containing n items randomly sampled from the caller object.      See also  DataFrameGroupBy.sample

Generates random samples from each group of a DataFrame object.  SeriesGroupBy.sample

Generates random samples from each group of a Series object.  numpy.random.choice

Generates a random sample from a given 1-D numpy array.    Notes If frac > 1, replacement should be set to True. Examples
>>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
...                    'num_wings': [2, 0, 0, 0],
...                    'num_specimen_seen': [10, 2, 1, 8]},
...                   index=['falcon', 'dog', 'spider', 'fish'])
>>> df
        num_legs  num_wings  num_specimen_seen
falcon         2          2                 10
dog            4          0                  2
spider         8          0                  1
fish           0          0                  8
  Extract 3 random elements from the Series df['num_legs']: Note that we use random_state to ensure the reproducibility of the examples.
>>> df['num_legs'].sample(n=3, random_state=1)
fish      0
spider    8
falcon    2
Name: num_legs, dtype: int64
  A random 50% sample of the DataFrame with replacement:
>>> df.sample(frac=0.5, replace=True, random_state=1)
      num_legs  num_wings  num_specimen_seen
dog          4          0                  2
fish         0          0                  8
  An upsample sample of the DataFrame with replacement: Note that replace parameter has to be True for frac parameter > 1.
>>> df.sample(frac=2, replace=True, random_state=1)
        num_legs  num_wings  num_specimen_seen
dog            4          0                  2
fish           0          0                  8
falcon         2          2                 10
falcon         2          2                 10
fish           0          0                  8
dog            4          0                  2
fish           0          0                  8
dog            4          0                  2
  Using a DataFrame column as weights. Rows with larger value in the num_specimen_seen column are more likely to be sampled.
>>> df.sample(n=2, weights='num_specimen_seen', random_state=1)
        num_legs  num_wings  num_specimen_seen
falcon         2          2                 10
fish           0          0                  8


pandas.Series.searchsorted   Series.searchsorted(value, side='left', sorter=None)[source]

Find indices where elements should be inserted to maintain order. Find the indices into a sorted Series self such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved.  Note The Series must be monotonically sorted, otherwise wrong locations will likely be returned. Pandas does not check this for you.   Parameters

value:array-like or scalar

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 self into ascending order. They are typically the result of np.argsort.    Returns
 int or array of int

A scalar or array of insertion points with the same shape as value.      See also  sort_values

Sort by the values along either axis.  numpy.searchsorted

Similar method from NumPy.    Notes Binary search is used to find the required insertion points. Examples
>>> ser = pd.Series([1, 2, 3])
>>> ser
0    1
1    2
2    3
dtype: int64

>>> ser.searchsorted(4)
3

>>> ser.searchsorted([0, 4])
array([0, 3])

>>> ser.searchsorted([1, 3], side='left')
array([0, 2])

>>> ser.searchsorted([1, 3], side='right')
array([1, 3])

>>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000']))
>>> ser
0   2000-03-11
1   2000-03-12
2   2000-03-13
dtype: datetime64[ns]

>>> ser.searchsorted('3/14/2000')
3

>>> ser = pd.Categorical(
...     ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True
... )
>>> ser
['apple', 'bread', 'bread', 'cheese', 'milk']
Categories (4, object): ['apple' < 'bread' < 'cheese' < 'milk']

>>> ser.searchsorted('bread')
1

>>> ser.searchsorted(['bread'], side='right')
array([3])
  If the values are not monotonically sorted, wrong locations may be returned:
>>> ser = pd.Series([2, 1, 3])
>>> ser
0    2
1    1
2    3
dtype: int64

>>> ser.searchsorted(1)
0  # wrong result, correct would be 1


pandas.Series.sem   Series.sem(axis=None, skipna=True, level=None, ddof=1, numeric_only=None, **kwargs)[source]

Return unbiased standard error of the mean over requested axis. Normalized by N-1 by default. This can be changed using the ddof argument  Parameters

axis:{index (0)}

skipna:bool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.
level:int or level name, default None

If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.
ddof:int, default 1

Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.
numeric_only:bool, default None

Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.    Returns
 scalar or Series (if level specified)


pandas.Series.set_axis   Series.set_axis(labels, axis=0, inplace=False)[source]

Assign desired index to given axis. Indexes for row labels can be changed by assigning a list-like or Index.  Parameters

labels:list-like, Index

The values for the new index.
axis:{0 or ‘index’}, default 0

The axis to update. The value 0 identifies the rows.
inplace:bool, default False

Whether to return a new Series instance.    Returns

renamed:Series or None

An object of type Series or None if inplace=True.      See also  Series.rename_axis

Alter the name of the index.    Examples
>>> s = pd.Series([1, 2, 3])
>>> s
0    1
1    2
2    3
dtype: int64

>>> s.set_axis(['a', 'b', 'c'], axis=0)
a    1
b    2
c    3
dtype: int64


pandas.Series.set_flags   Series.set_flags(*, copy=False, allows_duplicate_labels=None)[source]

Return a new object with updated flags.  Parameters

allows_duplicate_labels:bool, optional

Whether the returned object allows duplicate labels.    Returns
 Series or DataFrame

The same type as the caller.      See also  DataFrame.attrs

Global metadata applying to this dataset.  DataFrame.flags

Global flags applying to this object.    Notes This method returns a new object that’s a view on the same data as the input. Mutating the input or the output values will be reflected in the other. This method is intended to be used in method chains. “Flags” differ from “metadata”. Flags reflect properties of the pandas object (the Series or DataFrame). Metadata refer to properties of the dataset, and should be stored in DataFrame.attrs. Examples
>>> df = pd.DataFrame({"A": [1, 2]})
>>> df.flags.allows_duplicate_labels
True
>>> df2 = df.set_flags(allows_duplicate_labels=False)
>>> df2.flags.allows_duplicate_labels
False


pandas.Series.shape   propertySeries.shape

Return a tuple of the shape of the underlying data.


pandas.Series.shift   Series.shift(periods=1, freq=None, axis=0, fill_value=None)[source]

Shift index by desired number of periods with an optional time freq. When freq is not passed, shift the index without realigning the data. If freq is passed (in this case, the index must be date or datetime, or it will raise a NotImplementedError), the index will be increased using the periods and the freq. freq can be inferred when specified as “infer” as long as either freq or inferred_freq attribute is set in the index.  Parameters

periods:int

Number of periods to shift. Can be positive or negative.
freq:DateOffset, tseries.offsets, timedelta, or str, optional

Offset to use from the tseries module or time rule (e.g. ‘EOM’). If freq is specified then the index values are shifted but the data is not realigned. That is, use freq if you would like to extend the index when shifting and preserve the original data. If freq is specified as “infer” then it will be inferred from the freq or inferred_freq attributes of the index. If neither of those attributes exist, a ValueError is thrown.
axis:{0 or ‘index’, 1 or ‘columns’, None}, default None

Shift direction.
fill_value:object, optional

The scalar value to use for newly introduced missing values. the default depends on the dtype of self. For numeric data, np.nan is used. For datetime, timedelta, or period data, etc. NaT is used. For extension dtypes, self.dtype.na_value is used.  Changed in version 1.1.0.     Returns
 Series

Copy of input object, shifted.      See also  Index.shift

Shift values of Index.  DatetimeIndex.shift

Shift values of DatetimeIndex.  PeriodIndex.shift

Shift values of PeriodIndex.  tshift

Shift the time index, using the index’s frequency if available.    Examples
>>> df = pd.DataFrame({"Col1": [10, 20, 15, 30, 45],
...                    "Col2": [13, 23, 18, 33, 48],
...                    "Col3": [17, 27, 22, 37, 52]},
...                   index=pd.date_range("2020-01-01", "2020-01-05"))
>>> df
            Col1  Col2  Col3
2020-01-01    10    13    17
2020-01-02    20    23    27
2020-01-03    15    18    22
2020-01-04    30    33    37
2020-01-05    45    48    52

>>> df.shift(periods=3)
            Col1  Col2  Col3
2020-01-01   NaN   NaN   NaN
2020-01-02   NaN   NaN   NaN
2020-01-03   NaN   NaN   NaN
2020-01-04  10.0  13.0  17.0
2020-01-05  20.0  23.0  27.0

>>> df.shift(periods=1, axis="columns")
            Col1  Col2  Col3
2020-01-01   NaN    10    13
2020-01-02   NaN    20    23
2020-01-03   NaN    15    18
2020-01-04   NaN    30    33
2020-01-05   NaN    45    48

>>> df.shift(periods=3, fill_value=0)
            Col1  Col2  Col3
2020-01-01     0     0     0
2020-01-02     0     0     0
2020-01-03     0     0     0
2020-01-04    10    13    17
2020-01-05    20    23    27

>>> df.shift(periods=3, freq="D")
            Col1  Col2  Col3
2020-01-04    10    13    17
2020-01-05    20    23    27
2020-01-06    15    18    22
2020-01-07    30    33    37
2020-01-08    45    48    52

>>> df.shift(periods=3, freq="infer")
            Col1  Col2  Col3
2020-01-04    10    13    17
2020-01-05    20    23    27
2020-01-06    15    18    22
2020-01-07    30    33    37
2020-01-08    45    48    52


pandas.Series.size   propertySeries.size

Return the number of elements in the underlying data.


pandas.Series.skew   Series.skew(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source]

Return unbiased skew over requested axis. Normalized by N-1.  Parameters

axis:{index (0)}

Axis for the function to be applied on.
skipna:bool, default True

Exclude NA/null values when computing the result.
level:int or level name, default None

If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.
numeric_only:bool, default None

Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.  **kwargs

Additional keyword arguments to be passed to the function.    Returns
 scalar or Series (if level specified)


pandas.Series.slice_shift   Series.slice_shift(periods=1, axis=0)[source]

Equivalent to shift without copying data. The shifted data will not include the dropped periods and the shifted axis will be smaller than the original.  Deprecated since version 1.2.0: slice_shift is deprecated, use DataFrame/Series.shift instead.   Parameters

periods:int

Number of periods to move, can be positive or negative.    Returns

shifted:same type as caller

   Notes While the slice_shift is faster than shift, you may pay for it later during alignment.


pandas.Series.sort_index   Series.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, ignore_index=False, key=None)[source]

Sort Series by index labels. Returns a new Series sorted by label if inplace argument is False, otherwise updates the original series and returns None.  Parameters

axis:int, default 0

Axis to direct sorting. This can only be 0 for Series.
level:int, optional

If not None, sort on values in specified index level(s).
ascending:bool or list-like of bools, default True

Sort ascending vs. descending. When the index is a MultiIndex the sort direction can be controlled for each level individually.
inplace:bool, default False

If True, perform operation in-place.
kind:{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, default ‘quicksort’

Choice of sorting algorithm. See also numpy.sort() for more information. ‘mergesort’ and ‘stable’ are the only stable algorithms. For DataFrames, this option is only applied when sorting on a single column or label.
na_position:{‘first’, ‘last’}, default ‘last’

If ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end. Not implemented for MultiIndex.
sort_remaining:bool, default True

If True and sorting by level and index is multilevel, sort by other levels too (in order) after sorting by specified level.
ignore_index:bool, default False

If True, the resulting axis will be labeled 0, 1, …, n - 1.  New in version 1.0.0.
key:callable, optional

If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape.  New in version 1.1.0.     Returns
 Series or None

The original Series sorted by the labels or None if inplace=True.      See also  DataFrame.sort_index

Sort DataFrame by the index.  DataFrame.sort_values

Sort DataFrame by the value.  Series.sort_values

Sort Series by the value.    Examples
>>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, 4])
>>> s.sort_index()
1    c
2    b
3    a
4    d
dtype: object
  Sort Descending
>>> s.sort_index(ascending=False)
4    d
3    a
2    b
1    c
dtype: object
  Sort Inplace
>>> s.sort_index(inplace=True)
>>> s
1    c
2    b
3    a
4    d
dtype: object
  By default NaNs are put at the end, but use na_position to place them at the beginning
>>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, np.nan])
>>> s.sort_index(na_position='first')
NaN     d
 1.0    c
 2.0    b
 3.0    a
dtype: object
  Specify index level to sort
>>> arrays = [np.array(['qux', 'qux', 'foo', 'foo',
...                     'baz', 'baz', 'bar', 'bar']),
...           np.array(['two', 'one', 'two', 'one',
...                     'two', 'one', 'two', 'one'])]
>>> s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=arrays)
>>> s.sort_index(level=1)
bar  one    8
baz  one    6
foo  one    4
qux  one    2
bar  two    7
baz  two    5
foo  two    3
qux  two    1
dtype: int64
  Does not sort by remaining levels when sorting by levels
>>> s.sort_index(level=1, sort_remaining=False)
qux  one    2
foo  one    4
baz  one    6
bar  one    8
qux  two    1
foo  two    3
baz  two    5
bar  two    7
dtype: int64
  Apply a key function before sorting
>>> s = pd.Series([1, 2, 3, 4], index=['A', 'b', 'C', 'd'])
>>> s.sort_index(key=lambda x : x.str.lower())
A    1
b    2
C    3
d    4
dtype: int64


pandas.Series.sort_values   Series.sort_values(axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)[source]

Sort by the values. Sort a Series in ascending or descending order by some criterion.  Parameters

axis:{0 or ‘index’}, default 0

Axis to direct sorting. The value ‘index’ is accepted for compatibility with DataFrame.sort_values.
ascending:bool or list of bools, default True

If True, sort values in ascending order, otherwise descending.
inplace:bool, default False

If True, perform operation in-place.
kind:{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, default ‘quicksort’

Choice of sorting algorithm. See also numpy.sort() for more information. ‘mergesort’ and ‘stable’ are the only stable algorithms.
na_position:{‘first’ or ‘last’}, default ‘last’

Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.
ignore_index:bool, default False

If True, the resulting axis will be labeled 0, 1, …, n - 1.  New in version 1.0.0.
key:callable, optional

If not None, apply the key function to the series values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect a Series and return an array-like.  New in version 1.1.0.     Returns
 Series or None

Series ordered by values or None if inplace=True.      See also  Series.sort_index

Sort by the Series indices.  DataFrame.sort_values

Sort DataFrame by the values along either axis.  DataFrame.sort_index

Sort DataFrame by indices.    Examples
>>> s = pd.Series([np.nan, 1, 3, 10, 5])
>>> s
0     NaN
1     1.0
2     3.0
3     10.0
4     5.0
dtype: float64
  Sort values ascending order (default behaviour)
>>> s.sort_values(ascending=True)
1     1.0
2     3.0
4     5.0
3    10.0
0     NaN
dtype: float64
  Sort values descending order
>>> s.sort_values(ascending=False)
3    10.0
4     5.0
2     3.0
1     1.0
0     NaN
dtype: float64
  Sort values inplace
>>> s.sort_values(ascending=False, inplace=True)
>>> s
3    10.0
4     5.0
2     3.0
1     1.0
0     NaN
dtype: float64
  Sort values putting NAs first
>>> s.sort_values(na_position='first')
0     NaN
1     1.0
2     3.0
4     5.0
3    10.0
dtype: float64
  Sort a series of strings
>>> s = pd.Series(['z', 'b', 'd', 'a', 'c'])
>>> s
0    z
1    b
2    d
3    a
4    c
dtype: object

>>> s.sort_values()
3    a
1    b
4    c
2    d
0    z
dtype: object
  Sort using a key function. Your key function will be given the Series of values and should return an array-like.
>>> s = pd.Series(['a', 'B', 'c', 'D', 'e'])
>>> s.sort_values()
1    B
3    D
0    a
2    c
4    e
dtype: object
>>> s.sort_values(key=lambda x: x.str.lower())
0    a
1    B
2    c
3    D
4    e
dtype: object
  NumPy ufuncs work well here. For example, we can sort by the sin of the value
>>> s = pd.Series([-4, -2, 0, 2, 4])
>>> s.sort_values(key=np.sin)
1   -2
4    4
2    0
0   -4
3    2
dtype: int64
  More complicated user-defined functions can be used, as long as they expect a Series and return an array-like
>>> s.sort_values(key=lambda x: (np.tan(x.cumsum())))
0   -4
3    2
4    4
1   -2
2    0
dtype: int64


pandas.Series.sparse   Series.sparse()[source]

Accessor for SparseSparse from other sparse matrix data types.


pandas.Series.sparse.density   Series.sparse.density

The percent of non- fill_value points, as decimal. Examples
>>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0)
>>> s.density
0.6


pandas.Series.sparse.fill_value   Series.sparse.fill_value

Elements in data that are fill_value are not stored. For memory savings, this should be the most common value in the array.


pandas.Series.sparse.from_coo   classmethodSeries.sparse.from_coo(A, dense_index=False)[source]

Create a Series with sparse values from a scipy.sparse.coo_matrix.  Parameters

A:scipy.sparse.coo_matrix

dense_index:bool, default False

If False (default), the SparseSeries index consists of only the coords of the non-null entries of the original coo_matrix. If True, the SparseSeries index consists of the full sorted (row, col) coordinates of the coo_matrix.    Returns

s:Series

A Series with sparse values.     Examples
>>> from scipy import sparse

>>> A = sparse.coo_matrix(
...     ([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), shape=(3, 4)
... )
>>> A
<3x4 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in COOrdinate format>

>>> A.todense()
matrix([[0., 0., 1., 2.],
[3., 0., 0., 0.],
[0., 0., 0., 0.]])

>>> ss = pd.Series.sparse.from_coo(A)
>>> ss
0  2    1.0
   3    2.0
1  0    3.0
dtype: Sparse[float64, nan]


pandas.Series.sparse.npoints   Series.sparse.npoints

The number of non- fill_value points. Examples
>>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0)
>>> s.npoints
3


pandas.Series.sparse.sp_values   Series.sparse.sp_values

An ndarray containing the non- fill_value values. Examples
>>> s = SparseArray([0, 0, 1, 0, 2], fill_value=0)
>>> s.sp_values
array([1, 2])


pandas.Series.sparse.to_coo   Series.sparse.to_coo(row_levels=(0,), column_levels=(1,), sort_labels=False)[source]

Create a scipy.sparse.coo_matrix from a Series with MultiIndex. Use row_levels and column_levels to determine the row and column coordinates respectively. row_levels and column_levels are the names (labels) or numbers of the levels. {row_levels, column_levels} must be a partition of the MultiIndex level names (or numbers).  Parameters

row_levels:tuple/list

column_levels:tuple/list

sort_labels:bool, default False

Sort the row and column labels before forming the sparse matrix. When row_levels and/or column_levels refer to a single level, set to True for a faster execution.    Returns

y:scipy.sparse.coo_matrix

rows:list (row labels)

columns:list (column labels)

   Examples
>>> s = pd.Series([3.0, np.nan, 1.0, 3.0, np.nan, np.nan])
>>> s.index = pd.MultiIndex.from_tuples(
...     [
...         (1, 2, "a", 0),
...         (1, 2, "a", 1),
...         (1, 1, "b", 0),
...         (1, 1, "b", 1),
...         (2, 1, "b", 0),
...         (2, 1, "b", 1)
...     ],
...     names=["A", "B", "C", "D"],
... )
>>> s
A  B  C  D
1  2  a  0    3.0
         1    NaN
   1  b  0    1.0
         1    3.0
2  1  b  0    NaN
         1    NaN
dtype: float64

>>> ss = s.astype("Sparse")
>>> ss
A  B  C  D
1  2  a  0    3.0
         1    NaN
   1  b  0    1.0
         1    3.0
2  1  b  0    NaN
         1    NaN
dtype: Sparse[float64, nan]

>>> A, rows, columns = ss.sparse.to_coo(
...     row_levels=["A", "B"], column_levels=["C", "D"], sort_labels=True
... )
>>> A
<3x4 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in COOrdinate format>
>>> A.todense()
matrix([[0., 0., 1., 3.],
[3., 0., 0., 0.],
[0., 0., 0., 0.]])

>>> rows
[(1, 1), (1, 2), (2, 1)]
>>> columns
[('a', 0), ('a', 1), ('b', 0), ('b', 1)]


pandas.Series.squeeze   Series.squeeze(axis=None)[source]

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.    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 will project directly into a scalar:
>>> df_0a.squeeze()
1


pandas.Series.std   Series.std(axis=None, skipna=True, level=None, ddof=1, numeric_only=None, **kwargs)[source]

Return sample standard deviation over requested axis. Normalized by N-1 by default. This can be changed using the ddof argument.  Parameters

axis:{index (0)}

skipna:bool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.
level:int or level name, default None

If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.
ddof:int, default 1

Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.
numeric_only:bool, default None

Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.    Returns
 scalar or Series (if level specified)
   Notes To have the same behaviour as numpy.std, use ddof=0 (instead of the default ddof=1) Examples
>>> df = pd.DataFrame({'person_id': [0, 1, 2, 3],
...                   'age': [21, 25, 62, 43],
...                   'height': [1.61, 1.87, 1.49, 2.01]}
...                  ).set_index('person_id')
>>> df
           age  height
person_id
0           21    1.61
1           25    1.87
2           62    1.49
3           43    2.01
  The standard deviation of the columns can be found as follows:
>>> df.std()
age       18.786076
height     0.237417
  Alternatively, ddof=0 can be set to normalize by N instead of N-1:
>>> df.std(ddof=0)
age       16.269219
height     0.205609


pandas.Series.str   Series.str()[source]

Vectorized string functions for Series and Index. NAs stay NA unless handled otherwise by a particular method. Patterned after Python’s string methods, with some inspiration from R’s stringr package. Examples
>>> s = pd.Series(["A_Str_Series"])
>>> s
0    A_Str_Series
dtype: object

>>> s.str.split("_")
0    [A, Str, Series]
dtype: object

>>> s.str.replace("_", "")
0    AStrSeries
dtype: object


pandas.Series.str.capitalize   Series.str.capitalize()[source]

Convert strings in the Series/Index to be capitalized. Equivalent to str.capitalize().  Returns
 Series or Index of object
    See also  Series.str.lower

Converts all characters to lowercase.  Series.str.upper

Converts all characters to uppercase.  Series.str.title

Converts first character of each word to uppercase and remaining to lowercase.  Series.str.capitalize

Converts first character to uppercase and remaining to lowercase.  Series.str.swapcase

Converts uppercase to lowercase and lowercase to uppercase.  Series.str.casefold

Removes all case distinctions in the string.    Examples
>>> s = pd.Series(['lower', 'CAPITALS', 'this is a sentence', 'SwApCaSe'])
>>> s
0                 lower
1              CAPITALS
2    this is a sentence
3              SwApCaSe
dtype: object

>>> s.str.lower()
0                 lower
1              capitals
2    this is a sentence
3              swapcase
dtype: object

>>> s.str.upper()
0                 LOWER
1              CAPITALS
2    THIS IS A SENTENCE
3              SWAPCASE
dtype: object

>>> s.str.title()
0                 Lower
1              Capitals
2    This Is A Sentence
3              Swapcase
dtype: object

>>> s.str.capitalize()
0                 Lower
1              Capitals
2    This is a sentence
3              Swapcase
dtype: object

>>> s.str.swapcase()
0                 LOWER
1              capitals
2    THIS IS A SENTENCE
3              sWaPcAsE
dtype: object


pandas.Series.str.casefold   Series.str.casefold()[source]

Convert strings in the Series/Index to be casefolded.  New in version 0.25.0.  Equivalent to str.casefold().  Returns
 Series or Index of object
    See also  Series.str.lower

Converts all characters to lowercase.  Series.str.upper

Converts all characters to uppercase.  Series.str.title

Converts first character of each word to uppercase and remaining to lowercase.  Series.str.capitalize

Converts first character to uppercase and remaining to lowercase.  Series.str.swapcase

Converts uppercase to lowercase and lowercase to uppercase.  Series.str.casefold

Removes all case distinctions in the string.    Examples
>>> s = pd.Series(['lower', 'CAPITALS', 'this is a sentence', 'SwApCaSe'])
>>> s
0                 lower
1              CAPITALS
2    this is a sentence
3              SwApCaSe
dtype: object

>>> s.str.lower()
0                 lower
1              capitals
2    this is a sentence
3              swapcase
dtype: object

>>> s.str.upper()
0                 LOWER
1              CAPITALS
2    THIS IS A SENTENCE
3              SWAPCASE
dtype: object

>>> s.str.title()
0                 Lower
1              Capitals
2    This Is A Sentence
3              Swapcase
dtype: object

>>> s.str.capitalize()
0                 Lower
1              Capitals
2    This is a sentence
3              Swapcase
dtype: object

>>> s.str.swapcase()
0                 LOWER
1              capitals
2    THIS IS A SENTENCE
3              sWaPcAsE
dtype: object


pandas.Series.str.cat   Series.str.cat(others=None, sep=None, na_rep=None, join='left')[source]

Concatenate strings in the Series/Index with given separator. If others is specified, this function concatenates the Series/Index and elements of others element-wise. If others is not passed, then all values in the Series/Index are concatenated into a single string with a given sep.  Parameters

others:Series, Index, DataFrame, np.ndarray or list-like

Series, Index, DataFrame, np.ndarray (one- or two-dimensional) and other list-likes of strings must have the same length as the calling Series/Index, with the exception of indexed objects (i.e. Series/Index/DataFrame) if join is not None. If others is a list-like that contains a combination of Series, Index or np.ndarray (1-dim), then all elements will be unpacked and must satisfy the above criteria individually. If others is None, the method returns the concatenation of all strings in the calling Series/Index.
sep:str, default ‘’

The separator between the different elements/columns. By default the empty string ‘’ is used.
na_rep:str or None, default None

Representation that is inserted for all missing values:  If na_rep is None, and others is None, missing values in the Series/Index are omitted from the result. If na_rep is None, and others is not None, a row containing a missing value in any of the columns (before concatenation) will have a missing value in the result.
join:{‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘left’

Determines the join-style between the calling Series/Index and any Series/Index/DataFrame in others (objects without an index need to match the length of the calling Series/Index). To disable alignment, use .values on any Series/Index/DataFrame in others.  New in version 0.23.0.   Changed in version 1.0.0: Changed default of join from None to ‘left’.     Returns
 str, Series or Index

If others is None, str is returned, otherwise a Series/Index (same type as caller) of objects is returned.      See also  split

Split each string in the Series/Index.  join

Join lists contained as elements in the Series/Index.    Examples When not passing others, all values are concatenated into a single string:
>>> s = pd.Series(['a', 'b', np.nan, 'd'])
>>> s.str.cat(sep=' ')
'a b d'
  By default, NA values in the Series are ignored. Using na_rep, they can be given a representation:
>>> s.str.cat(sep=' ', na_rep='?')
'a b ? d'
  If others is specified, corresponding values are concatenated with the separator. Result will be a Series of strings.
>>> s.str.cat(['A', 'B', 'C', 'D'], sep=',')
0    a,A
1    b,B
2    NaN
3    d,D
dtype: object
  Missing values will remain missing in the result, but can again be represented using na_rep
>>> s.str.cat(['A', 'B', 'C', 'D'], sep=',', na_rep='-')
0    a,A
1    b,B
2    -,C
3    d,D
dtype: object
  If sep is not specified, the values are concatenated without separation.
>>> s.str.cat(['A', 'B', 'C', 'D'], na_rep='-')
0    aA
1    bB
2    -C
3    dD
dtype: object
  Series with different indexes can be aligned before concatenation. The join-keyword works as in other methods.
>>> t = pd.Series(['d', 'a', 'e', 'c'], index=[3, 0, 4, 2])
>>> s.str.cat(t, join='left', na_rep='-')
0    aa
1    b-
2    -c
3    dd
dtype: object
>>>
>>> s.str.cat(t, join='outer', na_rep='-')
0    aa
1    b-
2    -c
3    dd
4    -e
dtype: object
>>>
>>> s.str.cat(t, join='inner', na_rep='-')
0    aa
2    -c
3    dd
dtype: object
>>>
>>> s.str.cat(t, join='right', na_rep='-')
3    dd
0    aa
4    -e
2    -c
dtype: object
  For more examples, see here.


pandas.Series.str.center   Series.str.center(width, fillchar=' ')[source]

Pad left and right side of strings in the Series/Index. Equivalent to str.center().  Parameters

width:int

Minimum width of resulting string; additional characters will be filled with fillchar.
fillchar:str

Additional character for filling, default is whitespace.    Returns

filled:Series/Index of objects.


pandas.Series.str.contains   Series.str.contains(pat, case=True, flags=0, na=None, regex=True)[source]

Test if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index.  Parameters

pat:str

Character sequence or regular expression.
case:bool, default True

If True, case sensitive.
flags:int, default 0 (no flags)

Flags to pass through to the re module, e.g. re.IGNORECASE.
na:scalar, optional

Fill value for missing values. The default depends on dtype of the array. For object-dtype, numpy.nan is used. For StringDtype, pandas.NA is used.
regex:bool, default True

If True, assumes the pat is a regular expression. If False, treats the pat as a literal string.    Returns
 Series or Index of boolean values

A Series or Index of boolean values indicating whether the given pattern is contained within the string of each element of the Series or Index.      See also  match

Analogous, but stricter, relying on re.match instead of re.search.  Series.str.startswith

Test if the start of each string element matches a pattern.  Series.str.endswith

Same as startswith, but tests the end of string.    Examples Returning a Series of booleans using only a literal pattern.
>>> s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23', np.NaN])
>>> s1.str.contains('og', regex=False)
0    False
1     True
2    False
3    False
4      NaN
dtype: object
  Returning an Index of booleans using only a literal pattern.
>>> ind = pd.Index(['Mouse', 'dog', 'house and parrot', '23.0', np.NaN])
>>> ind.str.contains('23', regex=False)
Index([False, False, False, True, nan], dtype='object')
  Specifying case sensitivity using case.
>>> s1.str.contains('oG', case=True, regex=True)
0    False
1    False
2    False
3    False
4      NaN
dtype: object
  Specifying na to be False instead of NaN replaces NaN values with False. If Series or Index does not contain NaN values the resultant dtype will be bool, otherwise, an object dtype.
>>> s1.str.contains('og', na=False, regex=True)
0    False
1     True
2    False
3    False
4    False
dtype: bool
  Returning ‘house’ or ‘dog’ when either expression occurs in a string.
>>> s1.str.contains('house|dog', regex=True)
0    False
1     True
2     True
3    False
4      NaN
dtype: object
  Ignoring case sensitivity using flags with regex.
>>> import re
>>> s1.str.contains('PARROT', flags=re.IGNORECASE, regex=True)
0    False
1    False
2     True
3    False
4      NaN
dtype: object
  Returning any digit using regular expression.
>>> s1.str.contains('\\d', regex=True)
0    False
1    False
2    False
3     True
4      NaN
dtype: object
  Ensure pat is a not a literal pattern when regex is set to True. Note in the following example one might expect only s2[1] and s2[3] to return True. However, ‘.0’ as a regex matches any character followed by a 0.
>>> s2 = pd.Series(['40', '40.0', '41', '41.0', '35'])
>>> s2.str.contains('.0', regex=True)
0     True
1     True
2    False
3     True
4    False
dtype: bool


pandas.Series.str.count   Series.str.count(pat, flags=0)[source]

Count occurrences of pattern in each string of the Series/Index. This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the Series.  Parameters

pat:str

Valid regular expression.
flags:int, default 0, meaning no flags

Flags for the re module. For a complete list, see here.  **kwargs

For compatibility with other string methods. Not used.    Returns
 Series or Index

Same type as the calling object containing the integer counts.      See also  re

Standard library module for regular expressions.  str.count

Standard library version, without regular expression support.    Notes Some characters need to be escaped when passing in pat. eg. '$' has a special meaning in regex and must be escaped when finding this literal character. Examples
>>> s = pd.Series(['A', 'B', 'Aaba', 'Baca', np.nan, 'CABA', 'cat'])
>>> s.str.count('a')
0    0.0
1    0.0
2    2.0
3    2.0
4    NaN
5    0.0
6    1.0
dtype: float64
  Escape '$' to find the literal dollar sign.
>>> s = pd.Series(['$', 'B', 'Aab$', '$$ca', 'C$B$', 'cat'])
>>> s.str.count('\\$')
0    1
1    0
2    1
3    2
4    2
5    0
dtype: int64
  This is also available on Index
>>> pd.Index(['A', 'A', 'Aaba', 'cat']).str.count('a')
Int64Index([0, 0, 2, 1], dtype='int64')


pandas.Series.str.decode   Series.str.decode(encoding, errors='strict')[source]

Decode character string in the Series/Index using indicated encoding. Equivalent to str.decode() in python2 and bytes.decode() in python3.  Parameters

encoding:str

errors:str, optional

  Returns
 Series or Index


pandas.Series.str.encode   Series.str.encode(encoding, errors='strict')[source]

Encode character string in the Series/Index using indicated encoding. Equivalent to str.encode().  Parameters

encoding:str

errors:str, optional

  Returns

encoded:Series/Index of objects


pandas.Series.str.endswith   Series.str.endswith(pat, na=None)[source]

Test if the end of each string element matches a pattern. Equivalent to str.endswith().  Parameters

pat:str

Character sequence. Regular expressions are not accepted.
na:object, default NaN

Object shown if element tested is not a string. The default depends on dtype of the array. For object-dtype, numpy.nan is used. For StringDtype, pandas.NA is used.    Returns
 Series or Index of bool

A Series of booleans indicating whether the given pattern matches the end of each string element.      See also  str.endswith

Python standard library string method.  Series.str.startswith

Same as endswith, but tests the start of string.  Series.str.contains

Tests if string element contains a pattern.    Examples
>>> s = pd.Series(['bat', 'bear', 'caT', np.nan])
>>> s
0     bat
1    bear
2     caT
3     NaN
dtype: object

>>> s.str.endswith('t')
0     True
1    False
2    False
3      NaN
dtype: object
  Specifying na to be False instead of NaN.
>>> s.str.endswith('t', na=False)
0     True
1    False
2    False
3    False
dtype: bool


pandas.Series.str.extract   Series.str.extract(pat, flags=0, expand=True)[source]

Extract capture groups in the regex pat as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression pat.  Parameters

pat:str

Regular expression pattern with capturing groups.
flags:int, default 0 (no flags)

Flags from the re module, e.g. re.IGNORECASE, that modify regular expression matching for things like case, spaces, etc. For more details, see re.
expand:bool, default True

If True, return DataFrame with one column per capture group. If False, return a Series/Index if there is one capture group or DataFrame if there are multiple capture groups.    Returns
 DataFrame or Series or Index

A DataFrame with one row for each subject string, and one column for each group. Any capture group names in regular expression pat will be used for column names; otherwise capture group numbers will be used. The dtype of each result column is always object, even when no match is found. If expand=False and pat has only one capture group, then return a Series (if subject is a Series) or Index (if subject is an Index).      See also  extractall

Returns all matches (not just the first match).    Examples A pattern with two groups will return a DataFrame with two columns. Non-matches will be NaN.
>>> s = pd.Series(['a1', 'b2', 'c3'])
>>> s.str.extract(r'([ab])(\d)')
    0    1
0    a    1
1    b    2
2  NaN  NaN
  A pattern may contain optional groups.
>>> s.str.extract(r'([ab])?(\d)')
    0  1
0    a  1
1    b  2
2  NaN  3
  Named groups will become column names in the result.
>>> s.str.extract(r'(?P<letter>[ab])(?P<digit>\d)')
letter digit
0      a     1
1      b     2
2    NaN   NaN
  A pattern with one group will return a DataFrame with one column if expand=True.
>>> s.str.extract(r'[ab](\d)', expand=True)
    0
0    1
1    2
2  NaN
  A pattern with one group will return a Series if expand=False.
>>> s.str.extract(r'[ab](\d)', expand=False)
0      1
1      2
2    NaN
dtype: object


pandas.Series.str.extractall   Series.str.extractall(pat, flags=0)[source]

Extract capture groups in the regex pat as columns in DataFrame. For each subject string in the Series, extract groups from all matches of regular expression pat. When each subject string in the Series has exactly one match, extractall(pat).xs(0, level=’match’) is the same as extract(pat).  Parameters

pat:str

Regular expression pattern with capturing groups.
flags:int, default 0 (no flags)

A re module flag, for example re.IGNORECASE. These allow to modify regular expression matching for things like case, spaces, etc. Multiple flags can be combined with the bitwise OR operator, for example re.IGNORECASE | re.MULTILINE.    Returns
 DataFrame

A DataFrame with one row for each match, and one column for each group. Its rows have a MultiIndex with first levels that come from the subject Series. The last level is named ‘match’ and indexes the matches in each item of the Series. Any capture group names in regular expression pat will be used for column names; otherwise capture group numbers will be used.      See also  extract

Returns first match only (not all matches).    Examples A pattern with one group will return a DataFrame with one column. Indices with no matches will not appear in the result.
>>> s = pd.Series(["a1a2", "b1", "c1"], index=["A", "B", "C"])
>>> s.str.extractall(r"[ab](\d)")
        0
match
A 0      1
  1      2
B 0      1
  Capture group names are used for column names of the result.
>>> s.str.extractall(r"[ab](?P<digit>\d)")
        digit
match
A 0         1
  1         2
B 0         1
  A pattern with two groups will return a DataFrame with two columns.
>>> s.str.extractall(r"(?P<letter>[ab])(?P<digit>\d)")
        letter digit
match
A 0          a     1
  1          a     2
B 0          b     1
  Optional groups that do not match are NaN in the result.
>>> s.str.extractall(r"(?P<letter>[ab])?(?P<digit>\d)")
        letter digit
match
A 0          a     1
  1          a     2
B 0          b     1
C 0        NaN     1


pandas.Series.str.find   Series.str.find(sub, start=0, end=None)[source]

Return lowest indexes in each strings in the Series/Index. Each of returned indexes corresponds to the position where the substring is fully contained between [start:end]. Return -1 on failure. Equivalent to standard str.find().  Parameters

sub:str

Substring being searched.
start:int

Left edge index.
end:int

Right edge index.    Returns
 Series or Index of int.
    See also  rfind

Return highest indexes in each strings.