Write the code in pandas to create the following dataframes : df1 df2 mark1 mark2mark1 mark2 0 10 150 30 20 1 40 45 1 20 25 2 15 302 20 30 3 40 703 50 30 Write the commands to do the following operations on the dataframes given above : (i) To add dataframes df1 and df2. (ii) To subtract df2 from df1 (iii) To rename column mark1 as marks1in both the dataframes df1 and df2. (iv) To change index label of df1 from 0 to zero and from 1 to one.
Answers
Code to create dataframe:
import numpy as np
import pandas as pd
df1 = pd.DataFrame({'mark1':[30,40,15,40], mark2':[20,45,30,70]});
df2 = pd.DataFrame({'mark1':[10,20,20,50], 'mark2':[15,25,30,30]});
print(df1)
print(df2)
(i) Add dataframe
print(df1.add(df2))
In the above code, the marks in df2 is added with marks in df1.
Syntax for add in python is add(elem)
(ii) Subtract dataframe
print(df1.subtract(df2))
In the above code, the marks in df2 is subtracted with marks in df1.
Syntax for in python is subtract(elem)
(iii) Rename column
df1.rename(columns={'mark1':'marks1'}, inplace=True) print(df1)
Syntax to rename column in python is rename(columns)
The "true" is added to confirm the change.
(iv) Change index label
df1.rename(index = {0: "zero", 1:"one"}, inplace = True) print(df1)
Syntax to rename the index label in python is rename(index)
The "true" is added to confirm the change.