Python | Pandas dataframe.subtract ()
Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.
Pandas dataframe.subtract() function is used for finding the subtraction of dataframe and other, element-wise. This function is essentially same as doing dataframe - other but with a support to substitute for missing data in one of the inputs.
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 leve
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
Example #1: Use subtract() function to subtract each element of a dataframe with a corresponding element in a series.
# importing pandas as pdimport 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 dataframedf |

Let’s create the series
# importing pandas as pdimport pandas as pd # Create the seriessr = pd.Series([12, 25, 64, 18], index =["A", "B", "C", "D"]) # Print the seriessr |

Let’s use the dataframe.subtract() function for subtraction.
# equivalent to df - srdf.subtract(sr, axis = 1) |
Output :
Example #2: Use subtract() function to subtract each element in a dataframe with the corresponding element in other dataframe
# importing pandas as pdimport 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 dataframedf2 = 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 df1df1.subtract(df2) |
Выход :
Обратите внимание, что каждый элемент кадра данных df1 был вычтен из соответствующего элемента в df2.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.