Pandas 模块-操纵数据(11)-二元运算--超级add、sub、mul、div、mod、pow等等

                                                                        目录

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 DataFrame
    Any 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 label
    Broadcast across a level, matching Index values on the
    passed MultiIndex level.
fill_value : float or None, default None
    Fill existing missing (NaN) values, and any new element needed for
    successful DataFrame alignment, with this value before computation.
    If data in both corresponding DataFrame locations is missing
    the result will be missing.

Returns
-------
DataFrame
    Result 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 参数说明

  1. other:标量、序列、series、dict 或 DataFrame;可以是任何单个或多个元素的数据结构,或类似列表的对象。
  2. axis:{ 0 或 “index”,1 或 “columns ”};是否按索引(0 或 “index”)或列(1 或 “columns ”)进行比较。对于“Series ”输入,要与上的 “index” 索引匹配的轴。
  3. level:int 或 label,跨级别广播,匹配上的索引值;通过了 MultiIndex 级别。
  4. 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 DataFrame
    Any 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 label
    Broadcast across a level, matching Index values on the
    passed MultiIndex level.
fill_value : float or None, default None
    Fill existing missing (NaN) values, and any new element needed for
    successful DataFrame alignment, with this value before computation.
    If data in both corresponding DataFrame locations is missing
    the result will be missing.

Returns
-------
DataFrame
    Result 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'])
>>> df
           angles  degrees
circle          0      360
triangle        3      180
rectangle       4      360

Add 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 DataFrame
    Any 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 label
    Broadcast across a level, matching Index values on the
    passed MultiIndex level.
fill_value : float or None, default None
    Fill existing missing (NaN) values, and any new element needed for
    successful DataFrame alignment, with this value before computation.
    If data in both corresponding DataFrame locations is missing
    the result will be missing.

Returns
-------
DataFrame
    Result 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 DataFrame
    Any 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 label
    Broadcast across a level, matching Index values on the
    passed MultiIndex level.
fill_value : float or None, default None
    Fill existing missing (NaN) values, and any new element needed for
    successful DataFrame alignment, with this value before computation.
    If data in both corresponding DataFrame locations is missing
    the result will be missing.

Returns
-------
DataFrame
    Result 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 DataFrame
    Any 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 label
    Broadcast across a level, matching Index values on the
    passed MultiIndex level.
fill_value : float or None, default None
    Fill existing missing (NaN) values, and any new element needed for
    successful DataFrame alignment, with this value before computation.
    If data in both corresponding DataFrame locations is missing
    the result will be missing.

Returns
-------
DataFrame
    Result 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

        不知道大家明白了吗?

  1. DataFrame.radd(other[, axis,fill_value]) #右侧加法,元素指向

  2. DataFrame.rsub(other[, axis,fill_value]) #右侧减法,元素指向

  3. DataFrame.rmul(other[, axis,fill_value]) #右侧乘法,元素指向

  4. DataFrame.rdiv(other[, axis,fill_value]) #右侧小数除法,元素指向

  5. DataFrame.rtruediv(other[, axis, …]) #右侧真除法,元素指向

  6. DataFrame.rfloordiv(other[, axis, …]) #右侧向下取整除法,元素指向

  7. DataFrame.rmod(other[, axis,fill_value]) #右侧模运算,元素指向

  8. DataFrame.rpow(other[, axis,fill_value]) #右侧幂运算,元素指向

'''

要是大家觉得写得还行,麻烦点个赞或者收藏吧,想给博客涨涨人气,非常感谢!

'''

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/575077.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

MySQL中什么情况下会出现索引失效?如何排查索引失效?

目录 1-引言:什么是MySQL的索引失效?(What、Why)1-1 索引失效定义1-2 为什么排查索引失效 2- 索引失效的原因及排查(How)2-1 索引失效的情况① 索引列参与计算② 对索引列进行函数操作③ 查询中使用了 OR 两边有范围查询 > 或 …

2.7设计模式——Proxy 代理模式(结构型)

意图 为其它对象提供一种代理以控制这个对象的访问。 结构 Proxy保存一个引用使得代理可以访问实体;提供一个与Subject的接口相同的接口,使代理可以用来替代实体;控制实体的存取,并可能负责创建和删除它;其他功能依赖…

项目分享|基于ELF 1开发板的MQTT远程温湿度监测系统

今天非常荣幸向各位小伙伴详细展示一个由共创社成员完成的MQTT远程温湿度监控系统项目。该项目借助ELF 1开发板作为核心技术支撑,成功实现了对各类环境空间中温湿度数据的实时、远程、稳定监测。该系统不仅集成了先进的数据采集模块,用于精确感知现场环境…

uniapp问题归类

最近使用uniapp中,遇到了一些问题,这边mark下。 1. 启动页变形 设置启动页的时候发现在部分android手机上启动页被拉伸了,最后看了下官方建议使用9.png图 生成9.png地址,推荐图片大小为1080x2340 uniapp推荐官方地址传送门 我…

JAVA实现easyExcel动态生成excel

添加pom依赖 <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version> </dependency><!--工具类--> <dependency><groupId>cn.hutool</groupId><…

在Mac M1笔记本上跑大语言模型llama3的4个步骤?(install、pull、run、ask)

要点 Ollama一个功能强大的本地大语言模型LLM运行工具&#xff0c;支持很多模型&#xff0c;并且操作极其简单快速回忆步骤&#xff1a; 下载ollama工具&#xff1a;https://ollama.com/download 下载模型&#xff1a;ollama pull llama3 #根据libs列表直接指定名字 运行模型…

安卓studio插件开发(一)本地搭建工程

下载idea 社区版本 建立IDE Plugin工程 点击create就行&#xff0c;新建立的工程长这样 比较重要的文件 build.gradle&#xff1a;配置工程的参数 plugin.xml&#xff1a;设置插件的Action位置 build.gradle.kts内容如下&#xff1a; plugins {id("java")id(&quo…

常用的时间序列分析方法总结和代码示例

时间序列是最流行的数据类型之一。视频&#xff0c;图像&#xff0c;像素&#xff0c;信号&#xff0c;任何有时间成分的东西都可以转化为时间序列。 在本文中将在分析时间序列时使用的常见的处理方法。这些方法可以帮助你获得有关数据本身的见解&#xff0c;为建模做好准备并…

网站建设价格多少合理

网站建设价格多少合理&#xff0c;是很多企业和个人在寻找网站建设服务时&#xff0c;最为关心的问题之一。在选择好的网站建设服务商前&#xff0c;了解合理的网站建设价格&#xff0c;对于选择合适的网站建设服务商具有重要的参考作用。下面我们就来讨论一下&#xff0c;网站…

vue+element 树形结构 改成懒加载模式(原理element有),这里只做个人理解笔记

1 找到属性标签添加 lazy 和 :load"loadNode" 这两个属性 2 引入树形接口,并和后端约定好传值,(拿我的举例 第一次获取全部父级默认第一次传参数:{ parentId : 0},可获取全部父级 第二次通过点击的子级把子级id传进去,这一步就用到了:load"loadNode&quo…

区块链技术与应用学习笔记(10-11节)——北大肖臻课程

目录 10.分岔 ①什么是分叉&#xff1f; ②导致分叉的原因&#xff1f; ③在比特币新共识规则发布会会导致什么分叉&#xff1f; 什么是硬分叉&#xff1f; 硬分叉例子&#xff1f; 什么是软分叉&#xff1f; 软分叉和硬分叉区别&#xff1f; 软分叉实例 11.问答 转…

在no branch上commmit后,再切换到其他分支,找不到no branch分支的修改怎么办?

解决办法 通过git reflog我们可以查看历史提交记录&#xff0c;这里的第二条提交&#xff08;fbd3ea8&#xff09;就是我在no branch上的提交。 再通过git checkout -b backup fbd3ea8&#xff0c;恢复到上次提交的状态&#xff0c;并且为其创建个分支backup&#xff0c;此时…

ES6要点

ES6/ES7内容解析 一、变量/赋值1、变量2、解构赋值 二、函数1、箭头函数2、默认参数3、参数展开&#xff08;剩余参数&#xff0c;数组展开&#xff09; 三、数组/JSON1、 数组2、JSON 四、字符串1、字符串模版2、字符串方法 五、面向对象1、类2、bind()3、箭头函数的this 六、…

【Python特征工程系列】递归特征消除法分析特征重要性-SVC模型为例(案例+源码)

这是我的第268篇原创文章。 一、引言 递归特征消除&#xff08;RFE&#xff09;是一种高效的特征选择方法&#xff0c;它通过递归减少特征的数量来找出模型最重要的特征。本文基于支持向量机分类器作为选择器的基模型&#xff0c;采用递归消除法进行特征筛选。 二、实现过程 2…

HTTP与HTTPS 对比,区别详解(2024-04-25)

一、简介 HTTP&#xff08;超文本传输协议&#xff0c;Hypertext Transfer Protocol&#xff09;是一种用于从网络传输超文本到本地浏览器的传输协议。它定义了客户端与服务器之间请求和响应的格式。HTTP 工作在 TCP/IP 模型之上&#xff0c;通常使用端口 80。 HTTPS&#xf…

Jmeter(十九) - 从入门到精通 - JMeter监听器 -上篇(详解教程)

宏哥微信粉丝群&#xff1a;https://bbs.csdn.net/topics/618423372 有兴趣的可以扫码加入 1.简介 监听器用来监听及显示JMeter取样器测试结果&#xff0c;能够以树、表及图形形式显示测试结果&#xff0c;也可以以文件方式保存测试结果&#xff0c;JMeter测试结果文件格式多样…

使用docker安装本地pdf工具集合Stirling-PDF

平时工作中需要处理pdf&#xff0c;市面上的很多工具都需要充会员才能使用&#xff0c;偶然发现了一个可私有化部署且易于使用的PDF在线工具&#xff0c;使用docker部署&#xff0c;使用起来非常方便&#xff0c;而且功能齐全。 这里是官网&#xff1a; https://pdf.errui.cc/…

任务调度xxljob的使用记录

1.基本使用 a.下载代码&#xff0c;地址&#xff1a;https://gitee.com/xuxueli0323/xxl-job.git b.执行sql&#xff0c;修改配置&#xff0c;启动任务调度中心的代码 启动代码后任务调度中心访问地址&#xff1a;http://localhost:8080/xxl-job-admin&#xff08;自己机器…

D-Wave 推出快速退火功能,扩大量子计算性能增益

内容来源&#xff1a;量子前哨&#xff08;ID&#xff1a;Qforepost&#xff09; 文丨浪味仙 排版丨沛贤 深度好文&#xff1a;1400字丨6分钟阅读 摘要&#xff1a;量子计算公司 D-Wave 宣布在其 Leap™ 实时量子云服务中的所有量子处理单元 (QPU) 上推出新的快速退火功能。…

30 OpenCV 点多边形测试

文章目录 点多边形测试pointPolygonTest示例 点多边形测试 pointPolygonTest pointPolygonTest( InputArray contour,// 输入的轮廓 Point2f pt, // 测试点 bool measureDist // 是否返回距离值&#xff0c;如果是false&#xff0c;1表示在内面&#xff0c;0表示在边界上&a…