Python|熊猫 dataframe.subtract()
Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。
Pandas dataframe.subtract()函数用于查找数据帧和其他元素的减法。此函数与执行数据帧基本相同 - 其他但支持替换其中一个输入中的缺失数据。
Syntax: DataFrame.subtract(other, axis=’columns’, level=None, fill_value=None)
Parameters :
other : Series, DataFrame, or constant
axis : For Series input, axis to match Series index on
level : Broadcast across a level, matching Index values on the passed MultiIndex level
fill_value : 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 : result : DataFrame
示例#1:使用减法()函数将数据帧的每个元素与系列中的相应元素相减。
Python3
# 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
Python3
# 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
Python3
# equivalent to df - sr
df.subtract(sr, axis = 1)
Python3
# 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.subtract(df2)
让我们创建系列
Python3
# 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.subtract()函数进行减法。
Python3
# equivalent to df - sr
df.subtract(sr, axis = 1)
输出 :
示例#2:使用减法()函数将数据框中的每个元素与其他数据框中的相应元素相减
Python3
# 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.subtract(df2)
输出 :
请注意,数据帧 df1 的每个元素都已减去 df2 中的相应元素。