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中的相应元素相减。