浅谈Pandas:Series和DataFrame间的算术元素
作者:BQW_ 时间:2023-02-02 18:52:52
如下所示:
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
一、Series与Series
s1 = Series([1,3,5,7],index=['a','b','c','d'])
s2 = Series([2,4,6,8],index=['a','b','c','e'])
索引对齐项相加,不对齐项的值取NaN
s1+s2
1
a 3.0
b 7.0
c 11.0
d NaN
e NaN
dtype: float64
二、DataFrame与DataFrame
data1 = {'水果':['苹果','梨','草莓'],
'数量':[3,2,5],
'价格':[10,9,8]}
data2 = {'数量':[3,2,5,6],
'价格':[10,9,8,7]}
df1 = DataFrame(data1)
df2 = DataFrame(data2)
在行和列上同时对齐后进行计算,如果找不到对应项则取NaN
print(df1*df2)
价格 数量 水果
0 100.0 9.0 NaN
1 81.0 4.0 NaN
2 64.0 25.0 NaN
3 NaN NaN NaN
三、Series与DataFrame
1.利用广播实现DataFrame与某行的运算
print(df2+df2.iloc[0]) # 将第0行加到所有行上
价格 数量
0 20 6
1 19 5
2 18 8
3 17 9
2.利用广播实现DataFrame与某列的运算(指定轴axis=0)
print(df2.sub(df2.iloc[:,0],axis=0))
价格 数量
0 0 -7
1 0 -7
2 0 -3
3 0 -1
3.运算时如果无法对齐,则填充NaN
s = Series([1,1,1],index=['数量','价格','重量'])
print(df2+s)
价格 数量 重量
0 11 4 NaN
1 10 3 NaN
2 9 6 NaN
3 8 7 NaN
来源:https://blog.csdn.net/bqw18744018044/article/details/79935676
标签:Pandas,Series,DataFrame
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Linux删除系统自带版本Python过程详解
2023-10-21 03:12:13
Python办公自动化之Excel介绍
2021-04-19 11:06:07
![](https://img.aspxhome.com/file/2023/2/95602_0s.png)
Python竟然能剪辑视频
2021-09-03 08:12:54
![](https://img.aspxhome.com/file/2023/7/83827_0s.gif)
python生成带有表格的图片实例
2023-05-22 03:30:16
![](https://img.aspxhome.com/file/2023/4/81474_0s.jpg)
PHP缓存集成库phpFastCache用法
2023-11-14 02:35:19
JS的千分位算法实现思路
2023-08-23 22:40:32
Go语言的IO库那么多纠结该如何选择
2023-10-08 07:16:46
![](https://img.aspxhome.com/file/2023/6/101056_0s.jpg)
JavaScript实现三种常用网页特效(offset、client、scroll系列)
2023-08-27 11:54:30
![](https://img.aspxhome.com/file/2023/3/56173_0s.png)
Python解释器以及PyCharm的安装教程图文详解
2021-04-09 11:56:32
![](https://img.aspxhome.com/file/2023/6/71386_0s.jpg)
Flaks基础之在URL中添加变量的实现详解
2023-07-22 00:42:20
![](https://img.aspxhome.com/file/2023/1/94091_0s.png)
Python实现EXCEL表格的排序功能示例
2021-05-17 20:50:11
![](https://img.aspxhome.com/file/2023/7/81727_0s.jpg)
Python计算双重差分模型DID及其对应P值使用详解
2022-08-06 21:07:53
![](https://img.aspxhome.com/file/2023/5/68335_0s.jpg)
Python字符串对齐、删除字符串不需要的内容以及格式化打印字符
2021-09-17 10:46:33
Python网络编程之xmlrpc模块
2023-04-06 15:19:24
![](https://img.aspxhome.com/file/2023/6/85126_0s.png)
ASP程序直接连接MYSQL数据库
2008-10-03 12:13:00
闲聊html和body标签
2009-02-21 10:50:00
Python数据结构队列解决约瑟夫斯问题
2022-01-07 03:20:53
OpenCV实现相机标定
2023-11-13 00:36:45
![](https://img.aspxhome.com/file/2023/7/96937_0s.jpg)
Pygame 精准检测图像碰撞的问题
2022-01-17 17:56:13
Django权限机制实现代码详解
2022-09-18 01:21:51