python sub函数用法_Python Pandas dataframe.sub()用法及代码示例

Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统。 Pandas是其中的一种,使导入和分析数据更加容易。

Pandas dataframe.sub()函数用于查找数据帧和其他逐元素的减法。此功能与执行dataframe - other但支持替换其中一个输入中的丢失数据。

用法:DataFrame.sub(other, axis=’columns’, level=None, fill_value=None)

参数:

other:系列,DataFrame或常量

axis:对于系列输入,轴与系列索引匹配

level:在一个级别上广播,在传递的MultiIndex级别上匹配Index值

fill_value:在计算之前,请使用此值填充现有的缺失(NaN)值以及成功完成DataFrame对齐所需的任何新元素。如果两个对应的DataFrame位置中的数据均丢失,则结果将丢失。

返回:结果:DataFrame

范例1:采用sub()函数用于将 DataFrame 中的每个元素与一系列相应元素相减。

# importing pandas as pd

import pandas as pd

# Creating the dataframe

df = pd.DataFrame({"A":[1, 5, 3, 4, 2],

"B":[3, 2, 4, 3, 4],

"C":[2, 2, 7, 3, 4],

"D":[4, 3, 6, 12, 7]},

index =["A1", "A2", "A3", "A4", "A5"])

# Print the dataframe

df

让我们创建系列

# importing pandas as pd

import pandas as pd

# Create the series

sr = pd.Series([12, 25, 64, 18], index =["A", "B", "C", "D"])

# Print the series

sr

让我们使用dataframe.sub()减法功能。

# equivalent to df - sr

df.sub(sr, axis = 1)

输出:

范例2:采用sub()函数将 DataFrame 中的每个元素与其他 DataFrame 中的相应元素相减

# importing pandas as pd

import pandas as pd

# Creating the first dataframe

df1 = pd.DataFrame({"A":[1, 5, 3, 4, 2],

"B":[3, 2, 4, 3, 4],

"C":[2, 2, 7, 3, 4],

"D":[4, 3, 6, 12, 7]},

index =["A1", "A2", "A3", "A4", "A5"])

# Creating the second dataframe

df2 = pd.DataFrame({"A":[10, 11, 7, 8, 5],

"B":[21, 5, 32, 4, 6],

"C":[11, 21, 23, 7, 9],

"D":[1, 5, 3, 8, 6]},

index =["A1", "A2", "A3", "A4", "A5"])

# subtract df2 from df1

df1.sub(df2)

输出:

注意,数据帧df1的每个元素已与df2中的相应元素相减。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值