KnowledgeBoat Logo
|

Informatics Practices

Given the two DataFrames as :

>>> dfc1        
    -   -         
    0   1        
0   2   a      
1   3   b      
2   4   c   
>>> dfc2
    -   -   
    0   1   2
0   2   3   4
2   p   q   r

Why are following statements giving errors ?

(a) print(dfc1 + dfc2)

(b) print(dfc1.sub(dfc2))

(c) print(dfc1 * dfc2)

Python Pandas

3 Likes

Answer

(a) print(dfc1 + dfc2) — This statement tries to add two DataFrames dfc1 and dfc2. However, they have different shapes (dfc1 has 3 rows and 2 columns, while dfc2 has 2 rows and 3 columns), and their indices do not match. DataFrame addition requires both DataFrames to have the same shape and compatible indices, which is not the case here.

(b) print(dfc1.sub(dfc2)) — This statement attempts to subtract dfc1 from dfc2 using the sub() method. Similar to addition, subtraction between DataFrames requires them to have the same shape and compatible indices, which is not satisfied here due to the mismatch in shapes and indices.

(c) print(dfc1 * dfc2) — This statement tries to perform element-wise multiplication between dfc1 and dfc2. Again, this operation requires both DataFrames to have the same shape and compatible indices, which is not the case here due to the mismatched shapes and indices.

Answered By

3 Likes


Related Questions