目录
1. DataFrame.add
1.1 DataFrame.add 语法结构
1.2 DataFrame.add 参数说明
1.3 DataFrame.add 用法示例
1.3.1 正常的使用
1.3.2 需要注意类型相符合
2. DataFrame.sub
2.1 DataFrame.sub 语法结构
2.2 DataFrame.sub 参数说明
2.3 DataFrame.sub 用法示例
3. DataFrame.mul
3.1 DataFrame.mul 语法结构
3.2 DataFrame.mul 参数说明
3.3 DataFrame.mul 用法示例
4. DataFrame.div
4.1 DataFrame.div 语法结构
4.2 DataFrame.div 参数说明
4.3 DataFrame.div 用法示例
5. DataFrame.truediv
6.DataFrame.floordiv
7. DataFrame.mod
8. DataFrame.pow
9. DataFrame 其余二元运算
前面说过 Pandas 模块最大的优势是数据计算非常快,尤其是在希望对每个数据进行相同数据操作时候;如果只是会Python的基本操作,免不了一顿 for 循环,但是使用 Pandas 模块,那么代码表现就优雅多了,也快多了。
今天我们熟悉一下 DataFrame 自带的二元运算,从我们熟悉的加减乘除开始吧。
1. DataFrame.add
1.1 DataFrame.add 语法结构
首先我们要明确,DataFrame.add 等同于 DataFrame + XX 这个动作,但是它在输入数据丢失时候还支持替换 fill_value。它有一个反作用函数 radd。
Signature: df.add(other, axis: 'Axis' = 'columns', level=None, fill_value=None) Docstring: Get Addition of dataframe and other, element-wise (binary operator `add`).Equivalent to ``dataframe + other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `radd`.Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.Parameters ---------- other : scalar, sequence, Series, dict or DataFrameAny single or multiple element data structure, or list-like object. axis : {0 or 'index', 1 or 'columns'}Whether to compare by the index (0 or 'index') or columns.(1 or 'columns'). For Series input, axis to match Series index on. level : int or labelBroadcast across a level, matching Index values on thepassed MultiIndex level. fill_value : float or None, default NoneFill existing missing (NaN) values, and any new element needed forsuccessful DataFrame alignment, with this value before computation.If data in both corresponding DataFrame locations is missingthe result will be missing.Returns ------- DataFrameResult of the arithmetic operation.See Also -------- DataFrame.add : Add DataFrames. DataFrame.sub : Subtract DataFrames. DataFrame.mul : Multiply DataFrames. DataFrame.div : Divide DataFrames (float division). DataFrame.truediv : Divide DataFrames (float division). DataFrame.floordiv : Divide DataFrames (integer division). DataFrame.mod : Calculate modulo (remainder after division). DataFrame.pow : Calculate exponential power.
1.2 DataFrame.add 参数说明
- other:标量、序列、series、dict 或 DataFrame;可以是任何单个或多个元素的数据结构,或类似列表的对象。
- axis:{ 0 或 “index”,1 或 “columns ”};是否按索引(0 或 “index”)或列(1 或 “columns ”)进行比较。对于“Series ”输入,要与上的 “index” 索引匹配的轴。
- level:int 或 label,跨级别广播,匹配上的索引值;通过了 MultiIndex 级别。
- fill_value:float 或 None,默认值 None;为了 DataFrame 对齐,在计算之前使用此值,填充现有的缺失(NaN)值。如果两个相应 DataFrame 位置中的数据都丢失,结果将丢失。
1.3 DataFrame.add 用法示例
1.3.1 正常的使用
举例说明,当数据是字符类型时候:
import numpy as np
import pandas as pd
dict_data={"a":list("abcdef"),"b":list("defghi"),"c":list("ghijkl")}
df=pd.DataFrame.from_dict(dict_data)
df
df.add("c")
举例说明,当数据是数字类型时候:
dict_data={"a":[0,1,2,3,4,5,6,7],"b":[10,11,12,13,14,15,16,17],"c":[20,21,22,23,24,25,26,27]}
df=pd.DataFrame.from_dict(dict_data)
df
df.add(100)
1.3.2 需要注意类型相符合
2. DataFrame.sub
2.1 DataFrame.sub 语法结构
DataFrame.sub 语法结构如下:
Signature: df.sub(other, axis: 'Axis' = 'columns', level=None, fill_value=None) Docstring: Get Subtraction of dataframe and other, element-wise (binary operator `sub`).Equivalent to ``dataframe - other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rsub`.Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.Parameters ---------- other : scalar, sequence, Series, dict or DataFrameAny single or multiple element data structure, or list-like object. axis : {0 or 'index', 1 or 'columns'}Whether to compare by the index (0 or 'index') or columns.(1 or 'columns'). For Series input, axis to match Series index on. level : int or labelBroadcast across a level, matching Index values on thepassed MultiIndex level. fill_value : float or None, default NoneFill existing missing (NaN) values, and any new element needed forsuccessful DataFrame alignment, with this value before computation.If data in both corresponding DataFrame locations is missingthe result will be missing.Returns ------- DataFrameResult of the arithmetic operation.See Also -------- DataFrame.add : Add DataFrames. DataFrame.sub : Subtract DataFrames. DataFrame.mul : Multiply DataFrames. DataFrame.div : Divide DataFrames (float division). DataFrame.truediv : Divide DataFrames (float division). DataFrame.floordiv : Divide DataFrames (integer division). DataFrame.mod : Calculate modulo (remainder after division). DataFrame.pow : Calculate exponential power.Notes ----- Mismatched indices will be unioned together.Examples -------- >>> df = pd.DataFrame({'angles': [0, 3, 4], ... 'degrees': [360, 180, 360]}, ... index=['circle', 'triangle', 'rectangle']) >>> dfangles degrees circle 0 360 triangle 3 180 rectangle 4 360Add a scalar with operator version which return the same results.Signature: df.sub(other, axis: 'Axis' = 'columns', level=None, fill_value=None) Docstring: Get Subtraction of dataframe and other, element-wise (binary operator `sub`).Equivalent to ``dataframe - other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rsub`.Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.Parameters ---------- other : scalar, sequence, Series, dict or DataFrameAny single or multiple element data structure, or list-like object. axis : {0 or 'index', 1 or 'columns'}Whether to compare by the index (0 or 'index') or columns.(1 or 'columns'). For Series input, axis to match Series index on. level : int or labelBroadcast across a level, matching Index values on thepassed MultiIndex level. fill_value : float or None, default NoneFill existing missing (NaN) values, and any new element needed forsuccessful DataFrame alignment, with this value before computation.If data in both corresponding DataFrame locations is missingthe result will be missing.Returns ------- DataFrameResult of the arithmetic operation.
2.2 DataFrame.sub 参数说明
请参考 1.2
2.3 DataFrame.sub 用法示例
dict_data={"a":[0,1,2,3,4,5,6,7],"b":[10,11,12,13,14,15,16,17],"c":[20,21,22,23,24,25,26,27]}
df=pd.DataFrame.from_dict(dict_data)
df
df.sub(10)
3. DataFrame.mul
3.1 DataFrame.mul 语法结构
Signature: df.mul(other, axis: 'Axis' = 'columns', level=None, fill_value=None) Docstring: Get Multiplication of dataframe and other, element-wise (binary operator `mul`).Equivalent to ``dataframe * other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rmul`.Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.Parameters ---------- other : scalar, sequence, Series, dict or DataFrameAny single or multiple element data structure, or list-like object. axis : {0 or 'index', 1 or 'columns'}Whether to compare by the index (0 or 'index') or columns.(1 or 'columns'). For Series input, axis to match Series index on. level : int or labelBroadcast across a level, matching Index values on thepassed MultiIndex level. fill_value : float or None, default NoneFill existing missing (NaN) values, and any new element needed forsuccessful DataFrame alignment, with this value before computation.If data in both corresponding DataFrame locations is missingthe result will be missing.Returns ------- DataFrameResult of the arithmetic operation.
3.2 DataFrame.mul 参数说明
请参考 1.2
3.3 DataFrame.mul 用法示例
4. DataFrame.div
4.1 DataFrame.div 语法结构
Signature: df.div(other, axis: 'Axis' = 'columns', level=None, fill_value=None) Docstring: Get Floating division of dataframe and other, element-wise (binary operator `truediv`).Equivalent to ``dataframe / other``, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, `rtruediv`.Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`) to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.Parameters ---------- other : scalar, sequence, Series, dict or DataFrameAny single or multiple element data structure, or list-like object. axis : {0 or 'index', 1 or 'columns'}Whether to compare by the index (0 or 'index') or columns.(1 or 'columns'). For Series input, axis to match Series index on. level : int or labelBroadcast across a level, matching Index values on thepassed MultiIndex level. fill_value : float or None, default NoneFill existing missing (NaN) values, and any new element needed forsuccessful DataFrame alignment, with this value before computation.If data in both corresponding DataFrame locations is missingthe result will be missing.Returns ------- DataFrameResult of the arithmetic operation.
4.2 DataFrame.div 参数说明
请参考 1.2
4.3 DataFrame.div 用法示例
5. DataFrame.truediv
DataFrame.truediv 和 DataFrame.div 都是 Pandas 库中DataFrame对象的除法运算方法。它们都可以用来执行元素级的除法运算。
DataFrame.div(other, axis=0) 方法用于元素级的除法,它的参数 other 可以是一个数,也可以是另一个 DataFrame,如果是后者,则必须两个 DataFrame 有相同的维度。
DataFrame.truediv(other, axis=0) 方法与 DataFrame.div(other, axis=0) 方法功能一致,唯一不同的是,当遇到除数为 0 的情况时,DataFrame.truediv 会返回 inf,而 DataFrame.div 会返回错误信息。
6.DataFrame.floordiv
DataFrame.floordiv 和 DataFrame.truediv 有一个重要的区别:
DataFrame.truediv(other, axis="columns", level=None, fill_value=None):这个方法计算的是真正的除法,也就是说,它会返回浮点数结果,即使是整数除以整数也会返回浮点数结果。
DataFrame.floordiv(other, axis="columns", level=None, fill_value=None):这个方法计算的是向下取整的除法,即结果会向下取整到最接近的整数。注意,这里的结果仍然是整数。
当遇到除数为 0 的情况时,DataFrame.truediv 和 DataFrame.truediv 一样会返回 inf,而 DataFrame.div 会返回错误信息。
7. DataFrame.mod
DataFrame.mod 是取模的动作,类似与 DataFrame % other
8. DataFrame.pow
DataFrame.pow 指数幂,DataFrame.pow(2) 等同于 DataFrame * DataFrame。
9. DataFrame 其余二元运算
下面很多二元运算,提到的右侧算法,是和左侧算法相对应的。
如 DataFrame.sub(other[, axis,fill_value]) ,DataFrame.rsub(other[, axis,fill_value]),前者是左侧算法,后者是右侧算法。
例如两个 DataFrame 数据 df1,df2。
df1.sub(df2)=df1-df2;
df1.rsub(df2)=df2-df1
不知道大家明白了吗?
DataFrame.radd(other[, axis,fill_value]) #右侧加法,元素指向
DataFrame.rsub(other[, axis,fill_value]) #右侧减法,元素指向
DataFrame.rmul(other[, axis,fill_value]) #右侧乘法,元素指向
DataFrame.rdiv(other[, axis,fill_value]) #右侧小数除法,元素指向
DataFrame.rtruediv(other[, axis, …]) #右侧真除法,元素指向
DataFrame.rfloordiv(other[, axis, …]) #右侧向下取整除法,元素指向
DataFrame.rmod(other[, axis,fill_value]) #右侧模运算,元素指向
DataFrame.rpow(other[, axis,fill_value]) #右侧幂运算,元素指向
'''
要是大家觉得写得还行,麻烦点个赞或者收藏吧,想给博客涨涨人气,非常感谢!
'''