Overview
- Python pandas library provides multitude of functions to work on two dimensioanl Data through the DataFrame class.
- The sub() method of pandas DataFrame subtracts the elements of one DataFrame from the elements of another DataFrame.
- Invoking sub() method on a DataFrame object is equivalent to calling the binary subtraction operator(-).
- The sub() method supports passing a parameter for missing values(np.nan, None).
Example
import pandas as pd
# Create Data
data1 = [(2, 4, 6, 8),
(1, 3, 5, 7),
(5, 0, 0, 9)];
data2 = [(1, 1, 0 , 1),
(1, 0, 1 , 1),
(0, 1, 1 , 0)];
# Construct DataFrame1
dataFrame1 = pd.DataFrame(data=data1);
print("DataFrame1:");
print(dataFrame1);
# Construct DataFrame2
dataFrame2 = pd.DataFrame(data=data2);
print("DataFrame2:");
print(dataFrame2);
# Subtracting DataFrame2 from DataFrame1
subtractionResults = dataFrame1 - dataFrame2;
print("Result of subtracting dataFrame1 from dataFrame2:");
print(subtractionResults);Output
DataFrame1:
0 1 2 3
0 2 4 6 8
1 1 3 5 7
2 5 0 0 9
DataFrame2:
0 1 2 3
0 1 1 0 1
1 1 0 1 1
2 0 1 1 0
Result of subtracting dataFrame1 from dataFrame2:
0 1 2 3
0 1 3 6 7
1 0 3 4 6
2 5 -1 -1 9##