doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
pandas.Series.mean Series.mean(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source]
Return the mean of the values over the requested axis. 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.reference.api.pandas.series.mean |
pandas.Series.median Series.median(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source]
Return the median of the values over the requested axis. 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.reference.api.pandas.series.median |
pandas.Series.memory_usage Series.memory_usage(index=True, deep=False)[source]
Return the memory usage of the Series. The memory usage can optionally include the contribution of the index and of elements of object dtype. Parameters
index:bool, default True
Specifies whether to include the memory usage of the Series index.
deep:bool, default False
If True, introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned value. Returns
int
Bytes of memory consumed. See also numpy.ndarray.nbytes
Total bytes consumed by the elements of the array. DataFrame.memory_usage
Bytes consumed by a DataFrame. Examples
>>> s = pd.Series(range(3))
>>> s.memory_usage()
152
Not including the index gives the size of the rest of the data, which is necessarily smaller:
>>> s.memory_usage(index=False)
24
The memory footprint of object values is ignored by default:
>>> s = pd.Series(["a", "b"])
>>> s.values
array(['a', 'b'], dtype=object)
>>> s.memory_usage()
144
>>> s.memory_usage(deep=True)
244 | pandas.reference.api.pandas.series.memory_usage |
pandas.Series.min Series.min(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source]
Return the minimum of the values over the requested axis. If you want the index of the minimum, use idxmin. This is the equivalent of the numpy.ndarray method argmin. 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)
See also Series.sum
Return the sum. Series.min
Return the minimum. Series.max
Return the maximum. Series.idxmin
Return the index of the minimum. Series.idxmax
Return the index of the maximum. DataFrame.sum
Return the sum over the requested axis. DataFrame.min
Return the minimum over the requested axis. DataFrame.max
Return the maximum over the requested axis. DataFrame.idxmin
Return the index of the minimum over the requested axis. DataFrame.idxmax
Return the index of the maximum over the requested axis. Examples
>>> idx = pd.MultiIndex.from_arrays([
... ['warm', 'warm', 'cold', 'cold'],
... ['dog', 'falcon', 'fish', 'spider']],
... names=['blooded', 'animal'])
>>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx)
>>> s
blooded animal
warm dog 4
falcon 2
cold fish 0
spider 8
Name: legs, dtype: int64
>>> s.min()
0 | pandas.reference.api.pandas.series.min |
pandas.Series.mod Series.mod(other, level=None, fill_value=None, axis=0)[source]
Return Modulo of series and other, element-wise (binary operator mod). Equivalent to series % other, 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.rmod
Reverse of the Modulo operator, 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.reference.api.pandas.series.mod |
pandas.Series.mode Series.mode(dropna=True)[source]
Return the mode(s) of the Series. The mode is the value that appears most often. There can be multiple modes. Always returns Series even if only one value is returned. Parameters
dropna:bool, default True
Don’t consider counts of NaN/NaT. Returns
Series
Modes of the Series in sorted order. | pandas.reference.api.pandas.series.mode |
pandas.Series.mul Series.mul(other, level=None, fill_value=None, axis=0)[source]
Return Multiplication of series and other, element-wise (binary operator mul). Equivalent to series * other, 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.rmul
Reverse of the Multiplication operator, 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.reference.api.pandas.series.mul |
pandas.Series.multiply Series.multiply(other, level=None, fill_value=None, axis=0)[source]
Return Multiplication of series and other, element-wise (binary operator mul). Equivalent to series * other, 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.rmul
Reverse of the Multiplication operator, 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.reference.api.pandas.series.multiply |
pandas.Series.name propertySeries.name
Return the name of the Series. The name of a Series becomes its index or column name if it is used to form a DataFrame. It is also used whenever displaying the Series using the interpreter. Returns
label (hashable object)
The name of the Series, also the column name if part of a DataFrame. See also Series.rename
Sets the Series name when given a scalar input. Index.name
Corresponding Index property. Examples The Series name can be set initially when calling the constructor.
>>> s = pd.Series([1, 2, 3], dtype=np.int64, name='Numbers')
>>> s
0 1
1 2
2 3
Name: Numbers, dtype: int64
>>> s.name = "Integers"
>>> s
0 1
1 2
2 3
Name: Integers, dtype: int64
The name of a Series within a DataFrame is its column name.
>>> df = pd.DataFrame([[1, 2], [3, 4], [5, 6]],
... columns=["Odd Numbers", "Even Numbers"])
>>> df
Odd Numbers Even Numbers
0 1 2
1 3 4
2 5 6
>>> df["Even Numbers"].name
'Even Numbers' | pandas.reference.api.pandas.series.name |
pandas.Series.nbytes propertySeries.nbytes
Return the number of bytes in the underlying data. | pandas.reference.api.pandas.series.nbytes |
pandas.Series.ndim propertySeries.ndim
Number of dimensions of the underlying data, by definition 1. | pandas.reference.api.pandas.series.ndim |
pandas.Series.ne Series.ne(other, level=None, fill_value=None, axis=0)[source]
Return Not equal to of series and other, element-wise (binary operator ne). Equivalent to series != other, 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. 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.ne(b, fill_value=0)
a False
b True
c True
d True
e True
dtype: bool | pandas.reference.api.pandas.series.ne |
pandas.Series.nlargest Series.nlargest(n=5, keep='first')[source]
Return the largest n elements. Parameters
n:int, default 5
Return this many descending sorted values.
keep:{‘first’, ‘last’, ‘all’}, default ‘first’
When there are duplicate values that cannot all fit in a Series of n elements: first : return the first n occurrences in order of appearance. last : return the last n occurrences in reverse order of appearance. all : keep all occurrences. This can result in a Series of size larger than n. Returns
Series
The n largest values in the Series, sorted in decreasing order. See also Series.nsmallest
Get the n smallest elements. Series.sort_values
Sort Series by values. Series.head
Return the first n rows. Notes Faster than .sort_values(ascending=False).head(n) for small n relative to the size of the Series object. Examples
>>> countries_population = {"Italy": 59000000, "France": 65000000,
... "Malta": 434000, "Maldives": 434000,
... "Brunei": 434000, "Iceland": 337000,
... "Nauru": 11300, "Tuvalu": 11300,
... "Anguilla": 11300, "Montserrat": 5200}
>>> s = pd.Series(countries_population)
>>> s
Italy 59000000
France 65000000
Malta 434000
Maldives 434000
Brunei 434000
Iceland 337000
Nauru 11300
Tuvalu 11300
Anguilla 11300
Montserrat 5200
dtype: int64
The n largest elements where n=5 by default.
>>> s.nlargest()
France 65000000
Italy 59000000
Malta 434000
Maldives 434000
Brunei 434000
dtype: int64
The n largest elements where n=3. Default keep value is ‘first’ so Malta will be kept.
>>> s.nlargest(3)
France 65000000
Italy 59000000
Malta 434000
dtype: int64
The n largest elements where n=3 and keeping the last duplicates. Brunei will be kept since it is the last with value 434000 based on the index order.
>>> s.nlargest(3, keep='last')
France 65000000
Italy 59000000
Brunei 434000
dtype: int64
The n largest elements where n=3 with all duplicates kept. Note that the returned Series has five elements due to the three duplicates.
>>> s.nlargest(3, keep='all')
France 65000000
Italy 59000000
Malta 434000
Maldives 434000
Brunei 434000
dtype: int64 | pandas.reference.api.pandas.series.nlargest |
pandas.Series.notna Series.notna()[source]
Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). NA values, such as None or numpy.NaN, get mapped to False values. Returns
Series
Mask of bool values for each element in Series that indicates whether an element is not an NA value. See also Series.notnull
Alias of notna. Series.isna
Boolean inverse of notna. Series.dropna
Omit axes labels with missing values. notna
Top-level notna. Examples Show which entries in a DataFrame are not NA.
>>> df = pd.DataFrame(dict(age=[5, 6, np.NaN],
... born=[pd.NaT, pd.Timestamp('1939-05-27'),
... pd.Timestamp('1940-04-25')],
... name=['Alfred', 'Batman', ''],
... toy=[None, 'Batmobile', 'Joker']))
>>> df
age born name toy
0 5.0 NaT Alfred None
1 6.0 1939-05-27 Batman Batmobile
2 NaN 1940-04-25 Joker
>>> df.notna()
age born name toy
0 True False True False
1 True True True True
2 False True True True
Show which entries in a Series are not NA.
>>> ser = pd.Series([5, 6, np.NaN])
>>> ser
0 5.0
1 6.0
2 NaN
dtype: float64
>>> ser.notna()
0 True
1 True
2 False
dtype: bool | pandas.reference.api.pandas.series.notna |
pandas.Series.notnull Series.notnull()[source]
Series.notnull is an alias for Series.notna. Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). NA values, such as None or numpy.NaN, get mapped to False values. Returns
Series
Mask of bool values for each element in Series that indicates whether an element is not an NA value. See also Series.notnull
Alias of notna. Series.isna
Boolean inverse of notna. Series.dropna
Omit axes labels with missing values. notna
Top-level notna. Examples Show which entries in a DataFrame are not NA.
>>> df = pd.DataFrame(dict(age=[5, 6, np.NaN],
... born=[pd.NaT, pd.Timestamp('1939-05-27'),
... pd.Timestamp('1940-04-25')],
... name=['Alfred', 'Batman', ''],
... toy=[None, 'Batmobile', 'Joker']))
>>> df
age born name toy
0 5.0 NaT Alfred None
1 6.0 1939-05-27 Batman Batmobile
2 NaN 1940-04-25 Joker
>>> df.notna()
age born name toy
0 True False True False
1 True True True True
2 False True True True
Show which entries in a Series are not NA.
>>> ser = pd.Series([5, 6, np.NaN])
>>> ser
0 5.0
1 6.0
2 NaN
dtype: float64
>>> ser.notna()
0 True
1 True
2 False
dtype: bool | pandas.reference.api.pandas.series.notnull |
pandas.Series.nsmallest Series.nsmallest(n=5, keep='first')[source]
Return the smallest n elements. Parameters
n:int, default 5
Return this many ascending sorted values.
keep:{‘first’, ‘last’, ‘all’}, default ‘first’
When there are duplicate values that cannot all fit in a Series of n elements: first : return the first n occurrences in order of appearance. last : return the last n occurrences in reverse order of appearance. all : keep all occurrences. This can result in a Series of size larger than n. Returns
Series
The n smallest values in the Series, sorted in increasing order. See also Series.nlargest
Get the n largest elements. Series.sort_values
Sort Series by values. Series.head
Return the first n rows. Notes Faster than .sort_values().head(n) for small n relative to the size of the Series object. Examples
>>> countries_population = {"Italy": 59000000, "France": 65000000,
... "Brunei": 434000, "Malta": 434000,
... "Maldives": 434000, "Iceland": 337000,
... "Nauru": 11300, "Tuvalu": 11300,
... "Anguilla": 11300, "Montserrat": 5200}
>>> s = pd.Series(countries_population)
>>> s
Italy 59000000
France 65000000
Brunei 434000
Malta 434000
Maldives 434000
Iceland 337000
Nauru 11300
Tuvalu 11300
Anguilla 11300
Montserrat 5200
dtype: int64
The n smallest elements where n=5 by default.
>>> s.nsmallest()
Montserrat 5200
Nauru 11300
Tuvalu 11300
Anguilla 11300
Iceland 337000
dtype: int64
The n smallest elements where n=3. Default keep value is ‘first’ so Nauru and Tuvalu will be kept.
>>> s.nsmallest(3)
Montserrat 5200
Nauru 11300
Tuvalu 11300
dtype: int64
The n smallest elements where n=3 and keeping the last duplicates. Anguilla and Tuvalu will be kept since they are the last with value 11300 based on the index order.
>>> s.nsmallest(3, keep='last')
Montserrat 5200
Anguilla 11300
Tuvalu 11300
dtype: int64
The n smallest elements where n=3 with all duplicates kept. Note that the returned Series has four elements due to the three duplicates.
>>> s.nsmallest(3, keep='all')
Montserrat 5200
Nauru 11300
Tuvalu 11300
Anguilla 11300
dtype: int64 | pandas.reference.api.pandas.series.nsmallest |
pandas.Series.nunique Series.nunique(dropna=True)[source]
Return number of unique elements in the object. Excludes NA values by default. Parameters
dropna:bool, default True
Don’t include NaN in the count. Returns
int
See also DataFrame.nunique
Method nunique for DataFrame. Series.count
Count non-NA/null observations in the Series. Examples
>>> s = pd.Series([1, 3, 5, 7, 7])
>>> s
0 1
1 3
2 5
3 7
4 7
dtype: int64
>>> s.nunique()
4 | pandas.reference.api.pandas.series.nunique |
pandas.Series.pad Series.pad(axis=None, inplace=False, limit=None, downcast=None)[source]
Synonym for DataFrame.fillna() with method='ffill'. Returns
Series/DataFrame or None
Object with missing values filled or None if inplace=True. | pandas.reference.api.pandas.series.pad |
pandas.Series.pct_change Series.pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs)[source]
Percentage change between the current and a prior element. Computes the percentage change from the immediately previous row by default. This is useful in comparing the percentage of change in a time series of elements. Parameters
periods:int, default 1
Periods to shift for forming percent change.
fill_method:str, default ‘pad’
How to handle NAs before computing percent changes.
limit:int, default None
The number of consecutive NAs to fill before stopping.
freq:DateOffset, timedelta, or str, optional
Increment to use from time series API (e.g. ‘M’ or BDay()). **kwargs
Additional keyword arguments are passed into DataFrame.shift or Series.shift. Returns
chg:Series or DataFrame
The same type as the calling object. See also Series.diff
Compute the difference of two elements in a Series. DataFrame.diff
Compute the difference of two elements in a DataFrame. Series.shift
Shift the index by some number of periods. DataFrame.shift
Shift the index by some number of periods. Examples Series
>>> s = pd.Series([90, 91, 85])
>>> s
0 90
1 91
2 85
dtype: int64
>>> s.pct_change()
0 NaN
1 0.011111
2 -0.065934
dtype: float64
>>> s.pct_change(periods=2)
0 NaN
1 NaN
2 -0.055556
dtype: float64
See the percentage change in a Series where filling NAs with last valid observation forward to next valid.
>>> s = pd.Series([90, 91, None, 85])
>>> s
0 90.0
1 91.0
2 NaN
3 85.0
dtype: float64
>>> s.pct_change(fill_method='ffill')
0 NaN
1 0.011111
2 0.000000
3 -0.065934
dtype: float64
DataFrame Percentage change in French franc, Deutsche Mark, and Italian lira from 1980-01-01 to 1980-03-01.
>>> df = pd.DataFrame({
... 'FR': [4.0405, 4.0963, 4.3149],
... 'GR': [1.7246, 1.7482, 1.8519],
... 'IT': [804.74, 810.01, 860.13]},
... index=['1980-01-01', '1980-02-01', '1980-03-01'])
>>> df
FR GR IT
1980-01-01 4.0405 1.7246 804.74
1980-02-01 4.0963 1.7482 810.01
1980-03-01 4.3149 1.8519 860.13
>>> df.pct_change()
FR GR IT
1980-01-01 NaN NaN NaN
1980-02-01 0.013810 0.013684 0.006549
1980-03-01 0.053365 0.059318 0.061876
Percentage of change in GOOG and APPL stock volume. Shows computing the percentage change between columns.
>>> df = pd.DataFrame({
... '2016': [1769950, 30586265],
... '2015': [1500923, 40912316],
... '2014': [1371819, 41403351]},
... index=['GOOG', 'APPL'])
>>> df
2016 2015 2014
GOOG 1769950 1500923 1371819
APPL 30586265 40912316 41403351
>>> df.pct_change(axis='columns', periods=-1)
2016 2015 2014
GOOG 0.179241 0.094112 NaN
APPL -0.252395 -0.011860 NaN | pandas.reference.api.pandas.series.pct_change |
pandas.Series.pipe Series.pipe(func, *args, **kwargs)[source]
Apply chainable functions that expect Series or DataFrames. Parameters
func:function
Function to apply to the Series/DataFrame. args, and kwargs are passed into func. Alternatively a (callable, data_keyword) tuple where data_keyword is a string indicating the keyword of callable that expects the Series/DataFrame.
args:iterable, optional
Positional arguments passed into func.
kwargs:mapping, optional
A dictionary of keyword arguments passed into func. Returns
object:the return type of func.
See also DataFrame.apply
Apply a function along input axis of DataFrame. DataFrame.applymap
Apply a function elementwise on a whole DataFrame. Series.map
Apply a mapping correspondence on a Series. Notes Use .pipe when chaining together functions that expect Series, DataFrames or GroupBy objects. Instead of writing
>>> func(g(h(df), arg1=a), arg2=b, arg3=c)
You can write
>>> (df.pipe(h)
... .pipe(g, arg1=a)
... .pipe(func, arg2=b, arg3=c)
... )
If you have a function that takes the data as (say) the second argument, pass a tuple indicating which keyword expects the data. For example, suppose f takes its data as arg2:
>>> (df.pipe(h)
... .pipe(g, arg1=a)
... .pipe((func, 'arg2'), arg1=a, arg3=c)
... ) | pandas.reference.api.pandas.series.pipe |
pandas.Series.plot Series.plot(*args, **kwargs)[source]
Make plots of Series or DataFrame. Uses the backend specified by the option plotting.backend. By default, matplotlib is used. Parameters
data:Series or DataFrame
The object for which the method is called.
x:label or position, default None
Only used if data is a DataFrame.
y:label, position or list of label, positions, default None
Allows plotting of one column versus another. Only used if data is a DataFrame.
kind:str
The kind of plot to produce: ‘line’ : line plot (default) ‘bar’ : vertical bar plot ‘barh’ : horizontal bar plot ‘hist’ : histogram ‘box’ : boxplot ‘kde’ : Kernel Density Estimation plot ‘density’ : same as ‘kde’ ‘area’ : area plot ‘pie’ : pie plot ‘scatter’ : scatter plot (DataFrame only) ‘hexbin’ : hexbin plot (DataFrame only)
ax:matplotlib axes object, default None
An axes of the current figure.
subplots:bool, default False
Make separate subplots for each column.
sharex:bool, default True if ax is None else False
In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in; Be aware, that passing in both an ax and sharex=True will alter all x axis labels for all axis in a figure.
sharey:bool, default False
In case subplots=True, share y axis and set some y axis labels to invisible.
layout:tuple, optional
(rows, columns) for the layout of subplots.
figsize:a tuple (width, height) in inches
Size of a figure object.
use_index:bool, default True
Use index as ticks for x axis.
title:str or list
Title to use for the plot. If a string is passed, print the string at the top of the figure. If a list is passed and subplots is True, print each item in the list above the corresponding subplot.
grid:bool, default None (matlab style default)
Axis grid lines.
legend:bool or {‘reverse’}
Place legend on axis subplots.
style:list or dict
The matplotlib line style per column.
logx:bool or ‘sym’, default False
Use log scaling or symlog scaling on x axis. .. versionchanged:: 0.25.0
logy:bool or ‘sym’ default False
Use log scaling or symlog scaling on y axis. .. versionchanged:: 0.25.0
loglog:bool or ‘sym’, default False
Use log scaling or symlog scaling on both x and y axes. .. versionchanged:: 0.25.0
xticks:sequence
Values to use for the xticks.
yticks:sequence
Values to use for the yticks.
xlim:2-tuple/list
Set the x limits of the current axes.
ylim:2-tuple/list
Set the y limits of the current axes.
xlabel:label, optional
Name to use for the xlabel on x-axis. Default uses index name as xlabel, or the x-column name for planar plots. New in version 1.1.0. Changed in version 1.2.0: Now applicable to planar plots (scatter, hexbin).
ylabel:label, optional
Name to use for the ylabel on y-axis. Default will show no ylabel, or the y-column name for planar plots. New in version 1.1.0. Changed in version 1.2.0: Now applicable to planar plots (scatter, hexbin).
rot:int, default None
Rotation for ticks (xticks for vertical, yticks for horizontal plots).
fontsize:int, default None
Font size for xticks and yticks.
colormap:str or matplotlib colormap object, default None
Colormap to select colors from. If string, load colormap with that name from matplotlib.
colorbar:bool, optional
If True, plot colorbar (only relevant for ‘scatter’ and ‘hexbin’ plots).
position:float
Specify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center).
table:bool, Series or DataFrame, default False
If True, draw a table using the data in the DataFrame and the data will be transposed to meet matplotlib’s default layout. If a Series or DataFrame is passed, use passed data to draw a table.
yerr:DataFrame, Series, array-like, dict and str
See Plotting with Error Bars for detail.
xerr:DataFrame, Series, array-like, dict and str
Equivalent to yerr.
stacked:bool, default False in line and bar plots, and True in area plot
If True, create stacked plot.
sort_columns:bool, default False
Sort column names to determine plot ordering.
secondary_y:bool or sequence, default False
Whether to plot on the secondary y-axis if a list/tuple, which columns to plot on secondary y-axis.
mark_right:bool, default True
When using a secondary_y axis, automatically mark the column labels with “(right)” in the legend.
include_bool:bool, default is False
If True, boolean values can be plotted.
backend:str, default None
Backend to use instead of the backend specified in the option plotting.backend. For instance, ‘matplotlib’. Alternatively, to specify the plotting.backend for the whole session, set pd.options.plotting.backend. New in version 1.0.0. **kwargs
Options to pass to matplotlib plotting method. Returns
matplotlib.axes.Axes or numpy.ndarray of them
If the backend is not the default matplotlib one, the return value will be the object returned by the backend. Notes See matplotlib documentation online for more on this subject If kind = ‘bar’ or ‘barh’, you can specify relative alignments for bar plot layout by position keyword. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center) | pandas.reference.api.pandas.series.plot |
pandas.Series.plot.area Series.plot.area(x=None, y=None, **kwargs)[source]
Draw a stacked area plot. An area plot displays quantitative data visually. This function wraps the matplotlib area function. Parameters
x:label or position, optional
Coordinates for the X axis. By default uses the index.
y:label or position, optional
Column to plot. By default uses all columns.
stacked:bool, default True
Area plots are stacked by default. Set to False to create a unstacked plot. **kwargs
Additional keyword arguments are documented in DataFrame.plot(). Returns
matplotlib.axes.Axes or numpy.ndarray
Area plot, or array of area plots if subplots is True. See also DataFrame.plot
Make plots of DataFrame using matplotlib / pylab. Examples Draw an area plot based on basic business metrics:
>>> df = pd.DataFrame({
... 'sales': [3, 2, 3, 9, 10, 6],
... 'signups': [5, 5, 6, 12, 14, 13],
... 'visits': [20, 42, 28, 62, 81, 50],
... }, index=pd.date_range(start='2018/01/01', end='2018/07/01',
... freq='M'))
>>> ax = df.plot.area()
Area plots are stacked by default. To produce an unstacked plot, pass stacked=False:
>>> ax = df.plot.area(stacked=False)
Draw an area plot for a single column:
>>> ax = df.plot.area(y='sales')
Draw with a different x:
>>> df = pd.DataFrame({
... 'sales': [3, 2, 3],
... 'visits': [20, 42, 28],
... 'day': [1, 2, 3],
... })
>>> ax = df.plot.area(x='day') | pandas.reference.api.pandas.series.plot.area |
pandas.Series.plot.bar Series.plot.bar(x=None, y=None, **kwargs)[source]
Vertical bar plot. A bar plot is a plot that presents categorical data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, and the other axis represents a measured value. Parameters
x:label or position, optional
Allows plotting of one column versus another. If not specified, the index of the DataFrame is used.
y:label or position, optional
Allows plotting of one column versus another. If not specified, all numerical columns are used.
color:str, array-like, or dict, optional
The color for each of the DataFrame’s columns. Possible values are:
A single color string referred to by name, RGB or RGBA code,
for instance ‘red’ or ‘#a98d19’.
A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each column recursively. For instance [‘green’,’yellow’] each column’s bar will be filled in green or yellow, alternatively. If there is only a single column to be plotted, then only the first color from the color list will be used.
A dict of the form {column name:color}, so that each column will be
colored accordingly. For example, if your columns are called a and b, then passing {‘a’: ‘green’, ‘b’: ‘red’} will color bars for column a in green and bars for column b in red. New in version 1.1.0. **kwargs
Additional keyword arguments are documented in DataFrame.plot(). Returns
matplotlib.axes.Axes or np.ndarray of them
An ndarray is returned with one matplotlib.axes.Axes per column when subplots=True. See also DataFrame.plot.barh
Horizontal bar plot. DataFrame.plot
Make plots of a DataFrame. matplotlib.pyplot.bar
Make a bar plot with matplotlib. Examples Basic plot.
>>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
>>> ax = df.plot.bar(x='lab', y='val', rot=0)
Plot a whole dataframe to a bar plot. Each column is assigned a distinct color, and each row is nested in a group along the horizontal axis.
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.bar(rot=0)
Plot stacked bar charts for the DataFrame
>>> ax = df.plot.bar(stacked=True)
Instead of nesting, the figure can be split by column with subplots=True. In this case, a numpy.ndarray of matplotlib.axes.Axes are returned.
>>> axes = df.plot.bar(rot=0, subplots=True)
>>> axes[1].legend(loc=2)
If you don’t like the default colours, you can specify how you’d like each column to be colored.
>>> axes = df.plot.bar(
... rot=0, subplots=True, color={"speed": "red", "lifespan": "green"}
... )
>>> axes[1].legend(loc=2)
Plot a single column.
>>> ax = df.plot.bar(y='speed', rot=0)
Plot only selected categories for the DataFrame.
>>> ax = df.plot.bar(x='lifespan', rot=0) | pandas.reference.api.pandas.series.plot.bar |
pandas.Series.plot.barh Series.plot.barh(x=None, y=None, **kwargs)[source]
Make a horizontal bar plot. A horizontal bar plot is a plot that presents quantitative data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, and the other axis represents a measured value. Parameters
x:label or position, optional
Allows plotting of one column versus another. If not specified, the index of the DataFrame is used.
y:label or position, optional
Allows plotting of one column versus another. If not specified, all numerical columns are used.
color:str, array-like, or dict, optional
The color for each of the DataFrame’s columns. Possible values are:
A single color string referred to by name, RGB or RGBA code,
for instance ‘red’ or ‘#a98d19’.
A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each column recursively. For instance [‘green’,’yellow’] each column’s bar will be filled in green or yellow, alternatively. If there is only a single column to be plotted, then only the first color from the color list will be used.
A dict of the form {column name:color}, so that each column will be
colored accordingly. For example, if your columns are called a and b, then passing {‘a’: ‘green’, ‘b’: ‘red’} will color bars for column a in green and bars for column b in red. New in version 1.1.0. **kwargs
Additional keyword arguments are documented in DataFrame.plot(). Returns
matplotlib.axes.Axes or np.ndarray of them
An ndarray is returned with one matplotlib.axes.Axes per column when subplots=True. See also DataFrame.plot.bar
Vertical bar plot. DataFrame.plot
Make plots of DataFrame using matplotlib. matplotlib.axes.Axes.bar
Plot a vertical bar plot using matplotlib. Examples Basic example
>>> df = pd.DataFrame({'lab': ['A', 'B', 'C'], 'val': [10, 30, 20]})
>>> ax = df.plot.barh(x='lab', y='val')
Plot a whole DataFrame to a horizontal bar plot
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh()
Plot stacked barh charts for the DataFrame
>>> ax = df.plot.barh(stacked=True)
We can specify colors for each column
>>> ax = df.plot.barh(color={"speed": "red", "lifespan": "green"})
Plot a column of the DataFrame to a horizontal bar plot
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh(y='speed')
Plot DataFrame versus the desired column
>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
... 'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
... 'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh(x='lifespan') | pandas.reference.api.pandas.series.plot.barh |
pandas.Series.plot.box Series.plot.box(by=None, **kwargs)[source]
Make a box plot of the DataFrame columns. A box plot is a method for graphically depicting groups of numerical data through their quartiles. The box extends from the Q1 to Q3 quartile values of the data, with a line at the median (Q2). The whiskers extend from the edges of box to show the range of the data. The position of the whiskers is set by default to 1.5*IQR (IQR = Q3 - Q1) from the edges of the box. Outlier points are those past the end of the whiskers. For further details see Wikipedia’s entry for boxplot. A consideration when using this chart is that the box and the whiskers can overlap, which is very common when plotting small sets of data. Parameters
by:str or sequence
Column in the DataFrame to group by. Changed in version 1.4.0: Previously, by is silently ignore and makes no groupings **kwargs
Additional keywords are documented in DataFrame.plot(). Returns
matplotlib.axes.Axes or numpy.ndarray of them
See also DataFrame.boxplot
Another method to draw a box plot. Series.plot.box
Draw a box plot from a Series object. matplotlib.pyplot.boxplot
Draw a box plot in matplotlib. Examples Draw a box plot from a DataFrame with four columns of randomly generated data.
>>> data = np.random.randn(25, 4)
>>> df = pd.DataFrame(data, columns=list('ABCD'))
>>> ax = df.plot.box()
You can also generate groupings if you specify the by parameter (which can take a column name, or a list or tuple of column names): Changed in version 1.4.0.
>>> age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85]
>>> df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list})
>>> ax = df.plot.box(column="age", by="gender", figsize=(10, 8)) | pandas.reference.api.pandas.series.plot.box |
pandas.Series.plot.density Series.plot.density(bw_method=None, ind=None, **kwargs)[source]
Generate Kernel Density Estimate plot using Gaussian kernels. In statistics, kernel density estimation (KDE) is a non-parametric way to estimate the probability density function (PDF) of a random variable. This function uses Gaussian kernels and includes automatic bandwidth determination. Parameters
bw_method:str, scalar or callable, optional
The method used to calculate the estimator bandwidth. This can be ‘scott’, ‘silverman’, a scalar constant or a callable. If None (default), ‘scott’ is used. See scipy.stats.gaussian_kde for more information.
ind:NumPy array or int, optional
Evaluation points for the estimated PDF. If None (default), 1000 equally spaced points are used. If ind is a NumPy array, the KDE is evaluated at the points passed. If ind is an integer, ind number of equally spaced points are used. **kwargs
Additional keyword arguments are documented in pandas.%(this-datatype)s.plot(). Returns
matplotlib.axes.Axes or numpy.ndarray of them
See also scipy.stats.gaussian_kde
Representation of a kernel-density estimate using Gaussian kernels. This is the function used internally to estimate the PDF. Examples Given a Series of points randomly sampled from an unknown distribution, estimate its PDF using KDE with automatic bandwidth determination and plot the results, evaluating them at 1000 equally spaced points (default):
>>> s = pd.Series([1, 2, 2.5, 3, 3.5, 4, 5])
>>> ax = s.plot.kde()
A scalar bandwidth can be specified. Using a small bandwidth value can lead to over-fitting, while using a large bandwidth value may result in under-fitting:
>>> ax = s.plot.kde(bw_method=0.3)
>>> ax = s.plot.kde(bw_method=3)
Finally, the ind parameter determines the evaluation points for the plot of the estimated PDF:
>>> ax = s.plot.kde(ind=[1, 2, 3, 4, 5])
For DataFrame, it works in the same way:
>>> df = pd.DataFrame({
... 'x': [1, 2, 2.5, 3, 3.5, 4, 5],
... 'y': [4, 4, 4.5, 5, 5.5, 6, 6],
... })
>>> ax = df.plot.kde()
A scalar bandwidth can be specified. Using a small bandwidth value can lead to over-fitting, while using a large bandwidth value may result in under-fitting:
>>> ax = df.plot.kde(bw_method=0.3)
>>> ax = df.plot.kde(bw_method=3)
Finally, the ind parameter determines the evaluation points for the plot of the estimated PDF:
>>> ax = df.plot.kde(ind=[1, 2, 3, 4, 5, 6]) | pandas.reference.api.pandas.series.plot.density |
pandas.Series.plot.hist Series.plot.hist(by=None, bins=10, **kwargs)[source]
Draw one histogram of the DataFrame’s columns. A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one matplotlib.axes.Axes. This is useful when the DataFrame’s Series are in a similar scale. Parameters
by:str or sequence, optional
Column in the DataFrame to group by. Changed in version 1.4.0: Previously, by is silently ignore and makes no groupings
bins:int, default 10
Number of histogram bins to be used. **kwargs
Additional keyword arguments are documented in DataFrame.plot(). Returns
class:matplotlib.AxesSubplot
Return a histogram plot. See also DataFrame.hist
Draw histograms per DataFrame’s Series. Series.hist
Draw a histogram with Series’ data. Examples When we roll a die 6000 times, we expect to get each value around 1000 times. But when we roll two dice and sum the result, the distribution is going to be quite different. A histogram illustrates those distributions.
>>> df = pd.DataFrame(
... np.random.randint(1, 7, 6000),
... columns = ['one'])
>>> df['two'] = df['one'] + np.random.randint(1, 7, 6000)
>>> ax = df.plot.hist(bins=12, alpha=0.5)
A grouped histogram can be generated by providing the parameter by (which can be a column name, or a list of column names):
>>> age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85]
>>> df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list})
>>> ax = df.plot.hist(column=["age"], by="gender", figsize=(10, 8)) | pandas.reference.api.pandas.series.plot.hist |
pandas.Series.plot.kde Series.plot.kde(bw_method=None, ind=None, **kwargs)[source]
Generate Kernel Density Estimate plot using Gaussian kernels. In statistics, kernel density estimation (KDE) is a non-parametric way to estimate the probability density function (PDF) of a random variable. This function uses Gaussian kernels and includes automatic bandwidth determination. Parameters
bw_method:str, scalar or callable, optional
The method used to calculate the estimator bandwidth. This can be ‘scott’, ‘silverman’, a scalar constant or a callable. If None (default), ‘scott’ is used. See scipy.stats.gaussian_kde for more information.
ind:NumPy array or int, optional
Evaluation points for the estimated PDF. If None (default), 1000 equally spaced points are used. If ind is a NumPy array, the KDE is evaluated at the points passed. If ind is an integer, ind number of equally spaced points are used. **kwargs
Additional keyword arguments are documented in pandas.%(this-datatype)s.plot(). Returns
matplotlib.axes.Axes or numpy.ndarray of them
See also scipy.stats.gaussian_kde
Representation of a kernel-density estimate using Gaussian kernels. This is the function used internally to estimate the PDF. Examples Given a Series of points randomly sampled from an unknown distribution, estimate its PDF using KDE with automatic bandwidth determination and plot the results, evaluating them at 1000 equally spaced points (default):
>>> s = pd.Series([1, 2, 2.5, 3, 3.5, 4, 5])
>>> ax = s.plot.kde()
A scalar bandwidth can be specified. Using a small bandwidth value can lead to over-fitting, while using a large bandwidth value may result in under-fitting:
>>> ax = s.plot.kde(bw_method=0.3)
>>> ax = s.plot.kde(bw_method=3)
Finally, the ind parameter determines the evaluation points for the plot of the estimated PDF:
>>> ax = s.plot.kde(ind=[1, 2, 3, 4, 5])
For DataFrame, it works in the same way:
>>> df = pd.DataFrame({
... 'x': [1, 2, 2.5, 3, 3.5, 4, 5],
... 'y': [4, 4, 4.5, 5, 5.5, 6, 6],
... })
>>> ax = df.plot.kde()
A scalar bandwidth can be specified. Using a small bandwidth value can lead to over-fitting, while using a large bandwidth value may result in under-fitting:
>>> ax = df.plot.kde(bw_method=0.3)
>>> ax = df.plot.kde(bw_method=3)
Finally, the ind parameter determines the evaluation points for the plot of the estimated PDF:
>>> ax = df.plot.kde(ind=[1, 2, 3, 4, 5, 6]) | pandas.reference.api.pandas.series.plot.kde |
pandas.Series.plot.line Series.plot.line(x=None, y=None, **kwargs)[source]
Plot Series or DataFrame as lines. This function is useful to plot lines using DataFrame’s values as coordinates. Parameters
x:label or position, optional
Allows plotting of one column versus another. If not specified, the index of the DataFrame is used.
y:label or position, optional
Allows plotting of one column versus another. If not specified, all numerical columns are used.
color:str, array-like, or dict, optional
The color for each of the DataFrame’s columns. Possible values are:
A single color string referred to by name, RGB or RGBA code,
for instance ‘red’ or ‘#a98d19’.
A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each column recursively. For instance [‘green’,’yellow’] each column’s line will be filled in green or yellow, alternatively. If there is only a single column to be plotted, then only the first color from the color list will be used.
A dict of the form {column name:color}, so that each column will be
colored accordingly. For example, if your columns are called a and b, then passing {‘a’: ‘green’, ‘b’: ‘red’} will color lines for column a in green and lines for column b in red. New in version 1.1.0. **kwargs
Additional keyword arguments are documented in DataFrame.plot(). Returns
matplotlib.axes.Axes or np.ndarray of them
An ndarray is returned with one matplotlib.axes.Axes per column when subplots=True. See also matplotlib.pyplot.plot
Plot y versus x as lines and/or markers. Examples
>>> s = pd.Series([1, 3, 2])
>>> s.plot.line()
<AxesSubplot:ylabel='Density'>
The following example shows the populations for some animals over the years.
>>> df = pd.DataFrame({
... 'pig': [20, 18, 489, 675, 1776],
... 'horse': [4, 25, 281, 600, 1900]
... }, index=[1990, 1997, 2003, 2009, 2014])
>>> lines = df.plot.line()
An example with subplots, so an array of axes is returned.
>>> axes = df.plot.line(subplots=True)
>>> type(axes)
<class 'numpy.ndarray'>
Let’s repeat the same example, but specifying colors for each column (in this case, for each animal).
>>> axes = df.plot.line(
... subplots=True, color={"pig": "pink", "horse": "#742802"}
... )
The following example shows the relationship between both populations.
>>> lines = df.plot.line(x='pig', y='horse') | pandas.reference.api.pandas.series.plot.line |
pandas.Series.plot.pie Series.plot.pie(**kwargs)[source]
Generate a pie plot. A pie plot is a proportional representation of the numerical data in a column. This function wraps matplotlib.pyplot.pie() for the specified column. If no column reference is passed and subplots=True a pie plot is drawn for each numerical column independently. Parameters
y:int or label, optional
Label or position of the column to plot. If not provided, subplots=True argument must be passed. **kwargs
Keyword arguments to pass on to DataFrame.plot(). Returns
matplotlib.axes.Axes or np.ndarray of them
A NumPy array is returned when subplots is True. See also Series.plot.pie
Generate a pie plot for a Series. DataFrame.plot
Make plots of a DataFrame. Examples In the example below we have a DataFrame with the information about planet’s mass and radius. We pass the ‘mass’ column to the pie function to get a pie plot.
>>> df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
... 'radius': [2439.7, 6051.8, 6378.1]},
... index=['Mercury', 'Venus', 'Earth'])
>>> plot = df.plot.pie(y='mass', figsize=(5, 5))
>>> plot = df.plot.pie(subplots=True, figsize=(11, 6)) | pandas.reference.api.pandas.series.plot.pie |
pandas.Series.pop Series.pop(item)[source]
Return item and drops from series. Raise KeyError if not found. Parameters
item:label
Index of the element that needs to be removed. Returns
Value that is popped from series.
Examples
>>> ser = pd.Series([1,2,3])
>>> ser.pop(0)
1
>>> ser
1 2
2 3
dtype: int64 | pandas.reference.api.pandas.series.pop |
pandas.Series.pow Series.pow(other, level=None, fill_value=None, axis=0)[source]
Return Exponential power of series and other, element-wise (binary operator pow). Equivalent to series ** other, 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.rpow
Reverse of the Exponential power operator, 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.reference.api.pandas.series.pow |
pandas.Series.prod Series.prod(axis=None, skipna=True, level=None, numeric_only=None, min_count=0, **kwargs)[source]
Return the product of the values over the requested axis. 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.
min_count:int, default 0
The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. **kwargs
Additional keyword arguments to be passed to the function. Returns
scalar or Series (if level specified)
See also Series.sum
Return the sum. Series.min
Return the minimum. Series.max
Return the maximum. Series.idxmin
Return the index of the minimum. Series.idxmax
Return the index of the maximum. DataFrame.sum
Return the sum over the requested axis. DataFrame.min
Return the minimum over the requested axis. DataFrame.max
Return the maximum over the requested axis. DataFrame.idxmin
Return the index of the minimum over the requested axis. DataFrame.idxmax
Return the index of the maximum over the requested axis. Examples By default, the product of an empty or all-NA Series is 1
>>> pd.Series([], dtype="float64").prod()
1.0
This can be controlled with the min_count parameter
>>> pd.Series([], dtype="float64").prod(min_count=1)
nan
Thanks to the skipna parameter, min_count handles all-NA and empty series identically.
>>> pd.Series([np.nan]).prod()
1.0
>>> pd.Series([np.nan]).prod(min_count=1)
nan | pandas.reference.api.pandas.series.prod |
pandas.Series.product Series.product(axis=None, skipna=True, level=None, numeric_only=None, min_count=0, **kwargs)[source]
Return the product of the values over the requested axis. 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.
min_count:int, default 0
The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. **kwargs
Additional keyword arguments to be passed to the function. Returns
scalar or Series (if level specified)
See also Series.sum
Return the sum. Series.min
Return the minimum. Series.max
Return the maximum. Series.idxmin
Return the index of the minimum. Series.idxmax
Return the index of the maximum. DataFrame.sum
Return the sum over the requested axis. DataFrame.min
Return the minimum over the requested axis. DataFrame.max
Return the maximum over the requested axis. DataFrame.idxmin
Return the index of the minimum over the requested axis. DataFrame.idxmax
Return the index of the maximum over the requested axis. Examples By default, the product of an empty or all-NA Series is 1
>>> pd.Series([], dtype="float64").prod()
1.0
This can be controlled with the min_count parameter
>>> pd.Series([], dtype="float64").prod(min_count=1)
nan
Thanks to the skipna parameter, min_count handles all-NA and empty series identically.
>>> pd.Series([np.nan]).prod()
1.0
>>> pd.Series([np.nan]).prod(min_count=1)
nan | pandas.reference.api.pandas.series.product |
pandas.Series.quantile Series.quantile(q=0.5, interpolation='linear')[source]
Return value at the given quantile. Parameters
q:float or array-like, default 0.5 (50% quantile)
The quantile(s) to compute, which can lie in range: 0 <= q <= 1.
interpolation:{‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}
This optional parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j:
linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j. lower: i. higher: j. nearest: i or j whichever is nearest. midpoint: (i + j) / 2.
Returns
float or Series
If q is an array, a Series will be returned where the index is q and the values are the quantiles, otherwise a float will be returned. See also core.window.Rolling.quantile
Calculate the rolling quantile. numpy.percentile
Returns the q-th percentile(s) of the array elements. Examples
>>> s = pd.Series([1, 2, 3, 4])
>>> s.quantile(.5)
2.5
>>> s.quantile([.25, .5, .75])
0.25 1.75
0.50 2.50
0.75 3.25
dtype: float64 | pandas.reference.api.pandas.series.quantile |
pandas.Series.radd Series.radd(other, level=None, fill_value=None, axis=0)[source]
Return Addition of series and other, element-wise (binary operator radd). 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.add
Element-wise Addition, 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.add(b, fill_value=0)
a 2.0
b 1.0
c 1.0
d 1.0
e NaN
dtype: float64 | pandas.reference.api.pandas.series.radd |
pandas.Series.rank Series.rank(axis=0, method='average', numeric_only=NoDefault.no_default, na_option='keep', ascending=True, pct=False)[source]
Compute numerical data ranks (1 through n) along axis. By default, equal values are assigned a rank that is the average of the ranks of those values. Parameters
axis:{0 or ‘index’, 1 or ‘columns’}, default 0
Index to direct ranking.
method:{‘average’, ‘min’, ‘max’, ‘first’, ‘dense’}, default ‘average’
How to rank the group of records that have the same value (i.e. ties): average: average rank of the group min: lowest rank in the group max: highest rank in the group first: ranks assigned in order they appear in the array dense: like ‘min’, but rank always increases by 1 between groups.
numeric_only:bool, optional
For DataFrame objects, rank only numeric columns if set to True.
na_option:{‘keep’, ‘top’, ‘bottom’}, default ‘keep’
How to rank NaN values: keep: assign NaN rank to NaN values top: assign lowest rank to NaN values bottom: assign highest rank to NaN values
ascending:bool, default True
Whether or not the elements should be ranked in ascending order.
pct:bool, default False
Whether or not to display the returned rankings in percentile form. Returns
same type as caller
Return a Series or DataFrame with data ranks as values. See also core.groupby.GroupBy.rank
Rank of values within each group. Examples
>>> df = pd.DataFrame(data={'Animal': ['cat', 'penguin', 'dog',
... 'spider', 'snake'],
... 'Number_legs': [4, 2, 4, 8, np.nan]})
>>> df
Animal Number_legs
0 cat 4.0
1 penguin 2.0
2 dog 4.0
3 spider 8.0
4 snake NaN
The following example shows how the method behaves with the above parameters: default_rank: this is the default behaviour obtained without using any parameter. max_rank: setting method = 'max' the records that have the same values are ranked using the highest rank (e.g.: since ‘cat’ and ‘dog’ are both in the 2nd and 3rd position, rank 3 is assigned.) NA_bottom: choosing na_option = 'bottom', if there are records with NaN values they are placed at the bottom of the ranking. pct_rank: when setting pct = True, the ranking is expressed as percentile rank.
>>> df['default_rank'] = df['Number_legs'].rank()
>>> df['max_rank'] = df['Number_legs'].rank(method='max')
>>> df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom')
>>> df['pct_rank'] = df['Number_legs'].rank(pct=True)
>>> df
Animal Number_legs default_rank max_rank NA_bottom pct_rank
0 cat 4.0 2.5 3.0 2.5 0.625
1 penguin 2.0 1.0 1.0 1.0 0.250
2 dog 4.0 2.5 3.0 2.5 0.625
3 spider 8.0 4.0 4.0 4.0 1.000
4 snake NaN NaN NaN 5.0 NaN | pandas.reference.api.pandas.series.rank |
pandas.Series.ravel Series.ravel(order='C')[source]
Return the flattened underlying data as an ndarray. Returns
numpy.ndarray or ndarray-like
Flattened data of the Series. See also numpy.ndarray.ravel
Return a flattened array. | pandas.reference.api.pandas.series.ravel |
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.reference.api.pandas.series.rdiv |
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.reference.api.pandas.series.rdivmod |
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.reference.api.pandas.series.reindex |
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.reference.api.pandas.series.reindex_like |
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.reference.api.pandas.series.rename |
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.reference.api.pandas.series.rename_axis |
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.reference.api.pandas.series.reorder_levels |
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.reference.api.pandas.series.repeat |
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.reference.api.pandas.series.replace |
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.reference.api.pandas.series.resample |
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.reference.api.pandas.series.reset_index |
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.reference.api.pandas.series.rfloordiv |
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.reference.api.pandas.series.rmod |
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.reference.api.pandas.series.rmul |
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.reference.api.pandas.series.rolling |
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.reference.api.pandas.series.round |
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.reference.api.pandas.series.rpow |
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.reference.api.pandas.series.rsub |
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.reference.api.pandas.series.rtruediv |
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.reference.api.pandas.series.sample |
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.reference.api.pandas.series.searchsorted |
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.reference.api.pandas.series.sem |
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.reference.api.pandas.series.set_axis |
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.reference.api.pandas.series.set_flags |
pandas.Series.shape propertySeries.shape
Return a tuple of the shape of the underlying data. | pandas.reference.api.pandas.series.shape |
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.reference.api.pandas.series.shift |
pandas.Series.size propertySeries.size
Return the number of elements in the underlying data. | pandas.reference.api.pandas.series.size |
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.reference.api.pandas.series.skew |
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.reference.api.pandas.series.slice_shift |
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.reference.api.pandas.series.sort_index |
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.reference.api.pandas.series.sort_values |
pandas.Series.sparse Series.sparse()[source]
Accessor for SparseSparse from other sparse matrix data types. | pandas.reference.api.pandas.series.sparse |
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.reference.api.pandas.series.sparse.density |
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.reference.api.pandas.series.sparse.fill_value |
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.reference.api.pandas.series.sparse.from_coo |
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.reference.api.pandas.series.sparse.npoints |
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.reference.api.pandas.series.sparse.sp_values |
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.reference.api.pandas.series.sparse.to_coo |
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.reference.api.pandas.series.squeeze |
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.reference.api.pandas.series.std |
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.reference.api.pandas.series.str |
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.reference.api.pandas.series.str.capitalize |
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.reference.api.pandas.series.str.casefold |
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.reference.api.pandas.series.str.cat |
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.reference.api.pandas.series.str.center |
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.reference.api.pandas.series.str.contains |
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.reference.api.pandas.series.str.count |
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.reference.api.pandas.series.str.decode |
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.reference.api.pandas.series.str.encode |
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.reference.api.pandas.series.str.endswith |
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.reference.api.pandas.series.str.extract |
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.reference.api.pandas.series.str.extractall |
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. | pandas.reference.api.pandas.series.str.find |
pandas.Series.str.findall Series.str.findall(pat, flags=0)[source]
Find all occurrences of pattern or regular expression in the Series/Index. Equivalent to applying re.findall() to all the elements in the Series/Index. Parameters
pat:str
Pattern or regular expression.
flags:int, default 0
Flags from re module, e.g. re.IGNORECASE (default is 0, which means no flags). Returns
Series/Index of lists of strings
All non-overlapping matches of pattern or regular expression in each string of this Series/Index. See also count
Count occurrences of pattern or regular expression in each string of the Series/Index. extractall
For each string in the Series, extract groups from all matches of regular expression and return a DataFrame with one row for each match and one column for each group. re.findall
The equivalent re function to all non-overlapping matches of pattern or regular expression in string, as a list of strings. Examples
>>> s = pd.Series(['Lion', 'Monkey', 'Rabbit'])
The search for the pattern ‘Monkey’ returns one match:
>>> s.str.findall('Monkey')
0 []
1 [Monkey]
2 []
dtype: object
On the other hand, the search for the pattern ‘MONKEY’ doesn’t return any match:
>>> s.str.findall('MONKEY')
0 []
1 []
2 []
dtype: object
Flags can be added to the pattern or regular expression. For instance, to find the pattern ‘MONKEY’ ignoring the case:
>>> import re
>>> s.str.findall('MONKEY', flags=re.IGNORECASE)
0 []
1 [Monkey]
2 []
dtype: object
When the pattern matches more than one string in the Series, all matches are returned:
>>> s.str.findall('on')
0 [on]
1 [on]
2 []
dtype: object
Regular expressions are supported too. For instance, the search for all the strings ending with the word ‘on’ is shown next:
>>> s.str.findall('on$')
0 [on]
1 []
2 []
dtype: object
If the pattern is found more than once in the same string, then a list of multiple strings is returned:
>>> s.str.findall('b')
0 []
1 []
2 [b, b]
dtype: object | pandas.reference.api.pandas.series.str.findall |
pandas.Series.str.fullmatch Series.str.fullmatch(pat, case=True, flags=0, na=None)[source]
Determine if each string entirely matches a regular expression. New in version 1.1.0. Parameters
pat:str
Character sequence or regular expression.
case:bool, default True
If True, case sensitive.
flags:int, default 0 (no flags)
Regex module flags, 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. Returns
Series/Index/array of boolean values
See also match
Similar, but also returns True when only a prefix of the string matches the regular expression. extract
Extract matched groups. | pandas.reference.api.pandas.series.str.fullmatch |
pandas.Series.str.get Series.str.get(i)[source]
Extract element from each component at specified position. Extract element from lists, tuples, or strings in each element in the Series/Index. Parameters
i:int
Position of element to extract. Returns
Series or Index
Examples
>>> s = pd.Series(["String",
... (1, 2, 3),
... ["a", "b", "c"],
... 123,
... -456,
... {1: "Hello", "2": "World"}])
>>> s
0 String
1 (1, 2, 3)
2 [a, b, c]
3 123
4 -456
5 {1: 'Hello', '2': 'World'}
dtype: object
>>> s.str.get(1)
0 t
1 2
2 b
3 NaN
4 NaN
5 Hello
dtype: object
>>> s.str.get(-1)
0 g
1 3
2 c
3 NaN
4 NaN
5 None
dtype: object | pandas.reference.api.pandas.series.str.get |
pandas.Series.str.get_dummies Series.str.get_dummies(sep='|')[source]
Return DataFrame of dummy/indicator variables for Series. Each string in Series is split by sep and returned as a DataFrame of dummy/indicator variables. Parameters
sep:str, default “|”
String to split on. Returns
DataFrame
Dummy variables corresponding to values of the Series. See also get_dummies
Convert categorical variable into dummy/indicator variables. Examples
>>> pd.Series(['a|b', 'a', 'a|c']).str.get_dummies()
a b c
0 1 1 0
1 1 0 0
2 1 0 1
>>> pd.Series(['a|b', np.nan, 'a|c']).str.get_dummies()
a b c
0 1 1 0
1 0 0 0
2 1 0 1 | pandas.reference.api.pandas.series.str.get_dummies |
pandas.Series.str.index Series.str.index(sub, start=0, end=None)[source]
Return lowest indexes in each string in Series/Index. Each of the returned indexes corresponds to the position where the substring is fully contained between [start:end]. This is the same as str.find except instead of returning -1, it raises a ValueError when the substring is not found. Equivalent to standard str.index. Parameters
sub:str
Substring being searched.
start:int
Left edge index.
end:int
Right edge index. Returns
Series or Index of object
See also rindex
Return highest indexes in each strings. | pandas.reference.api.pandas.series.str.index |
pandas.Series.str.isalnum Series.str.isalnum()[source]
Check whether all characters in each string are alphanumeric. This is equivalent to running the Python string method str.isalnum() for each element of the Series/Index. If a string has zero characters, False is returned for that check. Returns
Series or Index of bool
Series or Index of boolean values with the same length as the original Series/Index. See also Series.str.isalpha
Check whether all characters are alphabetic. Series.str.isnumeric
Check whether all characters are numeric. Series.str.isalnum
Check whether all characters are alphanumeric. Series.str.isdigit
Check whether all characters are digits. Series.str.isdecimal
Check whether all characters are decimal. Series.str.isspace
Check whether all characters are whitespace. Series.str.islower
Check whether all characters are lowercase. Series.str.isupper
Check whether all characters are uppercase. Series.str.istitle
Check whether all characters are titlecase. Examples Checks for Alphabetic and Numeric Characters
>>> s1 = pd.Series(['one', 'one1', '1', ''])
>>> s1.str.isalpha()
0 True
1 False
2 False
3 False
dtype: bool
>>> s1.str.isnumeric()
0 False
1 False
2 True
3 False
dtype: bool
>>> s1.str.isalnum()
0 True
1 True
2 True
3 False
dtype: bool
Note that checks against characters mixed with any additional punctuation or whitespace will evaluate to false for an alphanumeric check.
>>> s2 = pd.Series(['A B', '1.5', '3,000'])
>>> s2.str.isalnum()
0 False
1 False
2 False
dtype: bool
More Detailed Checks for Numeric Characters There are several different but overlapping sets of numeric characters that can be checked for.
>>> s3 = pd.Series(['23', '³', '⅕', ''])
The s3.str.isdecimal method checks for characters used to form numbers in base 10.
>>> s3.str.isdecimal()
0 True
1 False
2 False
3 False
dtype: bool
The s.str.isdigit method is the same as s3.str.isdecimal but also includes special digits, like superscripted and subscripted digits in unicode.
>>> s3.str.isdigit()
0 True
1 True
2 False
3 False
dtype: bool
The s.str.isnumeric method is the same as s3.str.isdigit but also includes other characters that can represent quantities such as unicode fractions.
>>> s3.str.isnumeric()
0 True
1 True
2 True
3 False
dtype: bool
Checks for Whitespace
>>> s4 = pd.Series([' ', '\t\r\n ', ''])
>>> s4.str.isspace()
0 True
1 True
2 False
dtype: bool
Checks for Character Case
>>> s5 = pd.Series(['leopard', 'Golden Eagle', 'SNAKE', ''])
>>> s5.str.islower()
0 True
1 False
2 False
3 False
dtype: bool
>>> s5.str.isupper()
0 False
1 False
2 True
3 False
dtype: bool
The s5.str.istitle method checks for whether all words are in title case (whether only the first letter of each word is capitalized). Words are assumed to be as any sequence of non-numeric characters separated by whitespace characters.
>>> s5.str.istitle()
0 False
1 True
2 False
3 False
dtype: bool | pandas.reference.api.pandas.series.str.isalnum |
pandas.Series.str.isalpha Series.str.isalpha()[source]
Check whether all characters in each string are alphabetic. This is equivalent to running the Python string method str.isalpha() for each element of the Series/Index. If a string has zero characters, False is returned for that check. Returns
Series or Index of bool
Series or Index of boolean values with the same length as the original Series/Index. See also Series.str.isalpha
Check whether all characters are alphabetic. Series.str.isnumeric
Check whether all characters are numeric. Series.str.isalnum
Check whether all characters are alphanumeric. Series.str.isdigit
Check whether all characters are digits. Series.str.isdecimal
Check whether all characters are decimal. Series.str.isspace
Check whether all characters are whitespace. Series.str.islower
Check whether all characters are lowercase. Series.str.isupper
Check whether all characters are uppercase. Series.str.istitle
Check whether all characters are titlecase. Examples Checks for Alphabetic and Numeric Characters
>>> s1 = pd.Series(['one', 'one1', '1', ''])
>>> s1.str.isalpha()
0 True
1 False
2 False
3 False
dtype: bool
>>> s1.str.isnumeric()
0 False
1 False
2 True
3 False
dtype: bool
>>> s1.str.isalnum()
0 True
1 True
2 True
3 False
dtype: bool
Note that checks against characters mixed with any additional punctuation or whitespace will evaluate to false for an alphanumeric check.
>>> s2 = pd.Series(['A B', '1.5', '3,000'])
>>> s2.str.isalnum()
0 False
1 False
2 False
dtype: bool
More Detailed Checks for Numeric Characters There are several different but overlapping sets of numeric characters that can be checked for.
>>> s3 = pd.Series(['23', '³', '⅕', ''])
The s3.str.isdecimal method checks for characters used to form numbers in base 10.
>>> s3.str.isdecimal()
0 True
1 False
2 False
3 False
dtype: bool
The s.str.isdigit method is the same as s3.str.isdecimal but also includes special digits, like superscripted and subscripted digits in unicode.
>>> s3.str.isdigit()
0 True
1 True
2 False
3 False
dtype: bool
The s.str.isnumeric method is the same as s3.str.isdigit but also includes other characters that can represent quantities such as unicode fractions.
>>> s3.str.isnumeric()
0 True
1 True
2 True
3 False
dtype: bool
Checks for Whitespace
>>> s4 = pd.Series([' ', '\t\r\n ', ''])
>>> s4.str.isspace()
0 True
1 True
2 False
dtype: bool
Checks for Character Case
>>> s5 = pd.Series(['leopard', 'Golden Eagle', 'SNAKE', ''])
>>> s5.str.islower()
0 True
1 False
2 False
3 False
dtype: bool
>>> s5.str.isupper()
0 False
1 False
2 True
3 False
dtype: bool
The s5.str.istitle method checks for whether all words are in title case (whether only the first letter of each word is capitalized). Words are assumed to be as any sequence of non-numeric characters separated by whitespace characters.
>>> s5.str.istitle()
0 False
1 True
2 False
3 False
dtype: bool | pandas.reference.api.pandas.series.str.isalpha |
pandas.Series.str.isdecimal Series.str.isdecimal()[source]
Check whether all characters in each string are decimal. This is equivalent to running the Python string method str.isdecimal() for each element of the Series/Index. If a string has zero characters, False is returned for that check. Returns
Series or Index of bool
Series or Index of boolean values with the same length as the original Series/Index. See also Series.str.isalpha
Check whether all characters are alphabetic. Series.str.isnumeric
Check whether all characters are numeric. Series.str.isalnum
Check whether all characters are alphanumeric. Series.str.isdigit
Check whether all characters are digits. Series.str.isdecimal
Check whether all characters are decimal. Series.str.isspace
Check whether all characters are whitespace. Series.str.islower
Check whether all characters are lowercase. Series.str.isupper
Check whether all characters are uppercase. Series.str.istitle
Check whether all characters are titlecase. Examples Checks for Alphabetic and Numeric Characters
>>> s1 = pd.Series(['one', 'one1', '1', ''])
>>> s1.str.isalpha()
0 True
1 False
2 False
3 False
dtype: bool
>>> s1.str.isnumeric()
0 False
1 False
2 True
3 False
dtype: bool
>>> s1.str.isalnum()
0 True
1 True
2 True
3 False
dtype: bool
Note that checks against characters mixed with any additional punctuation or whitespace will evaluate to false for an alphanumeric check.
>>> s2 = pd.Series(['A B', '1.5', '3,000'])
>>> s2.str.isalnum()
0 False
1 False
2 False
dtype: bool
More Detailed Checks for Numeric Characters There are several different but overlapping sets of numeric characters that can be checked for.
>>> s3 = pd.Series(['23', '³', '⅕', ''])
The s3.str.isdecimal method checks for characters used to form numbers in base 10.
>>> s3.str.isdecimal()
0 True
1 False
2 False
3 False
dtype: bool
The s.str.isdigit method is the same as s3.str.isdecimal but also includes special digits, like superscripted and subscripted digits in unicode.
>>> s3.str.isdigit()
0 True
1 True
2 False
3 False
dtype: bool
The s.str.isnumeric method is the same as s3.str.isdigit but also includes other characters that can represent quantities such as unicode fractions.
>>> s3.str.isnumeric()
0 True
1 True
2 True
3 False
dtype: bool
Checks for Whitespace
>>> s4 = pd.Series([' ', '\t\r\n ', ''])
>>> s4.str.isspace()
0 True
1 True
2 False
dtype: bool
Checks for Character Case
>>> s5 = pd.Series(['leopard', 'Golden Eagle', 'SNAKE', ''])
>>> s5.str.islower()
0 True
1 False
2 False
3 False
dtype: bool
>>> s5.str.isupper()
0 False
1 False
2 True
3 False
dtype: bool
The s5.str.istitle method checks for whether all words are in title case (whether only the first letter of each word is capitalized). Words are assumed to be as any sequence of non-numeric characters separated by whitespace characters.
>>> s5.str.istitle()
0 False
1 True
2 False
3 False
dtype: bool | pandas.reference.api.pandas.series.str.isdecimal |
pandas.Series.str.isdigit Series.str.isdigit()[source]
Check whether all characters in each string are digits. This is equivalent to running the Python string method str.isdigit() for each element of the Series/Index. If a string has zero characters, False is returned for that check. Returns
Series or Index of bool
Series or Index of boolean values with the same length as the original Series/Index. See also Series.str.isalpha
Check whether all characters are alphabetic. Series.str.isnumeric
Check whether all characters are numeric. Series.str.isalnum
Check whether all characters are alphanumeric. Series.str.isdigit
Check whether all characters are digits. Series.str.isdecimal
Check whether all characters are decimal. Series.str.isspace
Check whether all characters are whitespace. Series.str.islower
Check whether all characters are lowercase. Series.str.isupper
Check whether all characters are uppercase. Series.str.istitle
Check whether all characters are titlecase. Examples Checks for Alphabetic and Numeric Characters
>>> s1 = pd.Series(['one', 'one1', '1', ''])
>>> s1.str.isalpha()
0 True
1 False
2 False
3 False
dtype: bool
>>> s1.str.isnumeric()
0 False
1 False
2 True
3 False
dtype: bool
>>> s1.str.isalnum()
0 True
1 True
2 True
3 False
dtype: bool
Note that checks against characters mixed with any additional punctuation or whitespace will evaluate to false for an alphanumeric check.
>>> s2 = pd.Series(['A B', '1.5', '3,000'])
>>> s2.str.isalnum()
0 False
1 False
2 False
dtype: bool
More Detailed Checks for Numeric Characters There are several different but overlapping sets of numeric characters that can be checked for.
>>> s3 = pd.Series(['23', '³', '⅕', ''])
The s3.str.isdecimal method checks for characters used to form numbers in base 10.
>>> s3.str.isdecimal()
0 True
1 False
2 False
3 False
dtype: bool
The s.str.isdigit method is the same as s3.str.isdecimal but also includes special digits, like superscripted and subscripted digits in unicode.
>>> s3.str.isdigit()
0 True
1 True
2 False
3 False
dtype: bool
The s.str.isnumeric method is the same as s3.str.isdigit but also includes other characters that can represent quantities such as unicode fractions.
>>> s3.str.isnumeric()
0 True
1 True
2 True
3 False
dtype: bool
Checks for Whitespace
>>> s4 = pd.Series([' ', '\t\r\n ', ''])
>>> s4.str.isspace()
0 True
1 True
2 False
dtype: bool
Checks for Character Case
>>> s5 = pd.Series(['leopard', 'Golden Eagle', 'SNAKE', ''])
>>> s5.str.islower()
0 True
1 False
2 False
3 False
dtype: bool
>>> s5.str.isupper()
0 False
1 False
2 True
3 False
dtype: bool
The s5.str.istitle method checks for whether all words are in title case (whether only the first letter of each word is capitalized). Words are assumed to be as any sequence of non-numeric characters separated by whitespace characters.
>>> s5.str.istitle()
0 False
1 True
2 False
3 False
dtype: bool | pandas.reference.api.pandas.series.str.isdigit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.