Pandas DataFrame | floordiv method
Start your free 7-days trial now!
Pandas DataFrame.floordiv(~) method divides the values in the source DataFrame by a scalar, sequence, Series or DataFrame via integer division, that is:
DataFrame // other
Unless you use the parameters axis, level and fill_value, the floordiv(~) is equivalent to performing division using the // operator.
Parameters
1. otherlink | scalar or sequence or Series or DataFrame
The resulting DataFrame will be the source DataFrame divided by other via integer division.
2. axislink | int or string | optional
Whether to broadcast other for each column or row of the source DataFrame:
Axis | Description |
|---|---|
|
|
|
|
Note that this is only relevant if the shape of the source DataFrame and that of other does not match up. By default, axis=1.
3. level | int or string | optional
The name or the integer index of the level to consider. This is relevant only if your DataFrame is Multi-index.
4. fill_valuelink | float or None | optional
The value to replace NaN before the computation. Note that if both pair of entries are NaN, then the result would still be NaN. By default, fill_value=None.
Return Value
A new DataFrame resulting from integer division.
Examples
Basic usage
Consider the following DataFrame:
df = pd.DataFrame({"A":[5,6], "B":[7,8]})df_other = pd.DataFrame({"A":[1,2], "B":[3,4]})
A B | A B0 5 7 | 0 1 3 1 6 8 | 1 2 4
Performing integer division:
df.floordiv(df_other)
A B0 5 21 3 2
Here, we're performing the following element-wise floor division:
5//1 7//36//2 8//4
Note that this is equivalent to:
df // df_other
A B0 5 21 3 2
Broadcasting
Consider the following DataFrame:
df = pd.DataFrame({"A":[3,4], "B":[5,6]})df
A B0 3 51 4 6
Row-wise integer division
By default, axis=1, which means that other will be broadcasted for each row in df:
df.floordiv([1,2]) # axis=1
A B0 3 21 4 3
Here, we're doing the following element-wise integer division:
3//1 5//24//1 6//2
Column-wise integer division
To broadcast other for each column in df, set axis=0 like so:
df.floordiv([1,2], axis=0)
A B0 3 51 2 3
Here, we're doing the following element-wise division:
3//1 5//14//2 6//2
Specifying fill_value
Consider the following DataFrames:
df = pd.DataFrame({"A":[6,np.NaN], "B":[np.NaN,7]})df_other = pd.DataFrame({"A":[2,3], "B":[np.NaN,np.NaN]})
A B | A B0 6.0 NaN | 0 2 NaN1 NaN 7.0 | 1 3 NaN
By default, when we perform integer division using floordiv(~), any operation with NaN results in NaN:
df.floordiv(df_other)
A B0 3.0 NaN1 NaN NaN
We can fill the NaN values before we perform integer division by using the fill_value parameter:
df.floordiv(df_other, fill_value=1)
A B0 3.0 NaN1 0.0 7.0
Notice how if the integer division is between two NaN, then the result would always be NaN regardless of fill_value.