How to substract the values of two different dataframes with the same column names and number of rows and store them into a new dataframe
Question:
i have two different dataframes with the same indexes and also the same column names and I want to substract each corrensponding value of them (for example df3[1,1]=df2[1,1]-df1[1,1]) and create a new dataframe with the new values. The dtypes of both dataframes are float64.
I tried the below and worked fine but it seems to me that it may exist a simpler way to do it.
df3=df2.select_dtypes(include=np.number)-df1.select_dtypes(include=np.number)
Can you please advise on an alternate way?
Thank you in advance for your support!
Answers:
You can do this in a shorter manner:
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.rand(5, 3), index=['a', 'b', 'c', 'd', 'e'], columns=['col1', 'col2', 'col3'])
df2 = pd.DataFrame(np.random.rand(5, 3), index=['a', 'b', 'c', 'd', 'e'], columns=['col1', 'col2', 'col3'])
df3 = df2.sub(df1)
print(df3)
which retunrs:
col1 col2 col3
a -0.263918 0.621965 -0.222294
b 0.939496 -0.448462 0.010776
c -0.762741 -0.053359 0.628212
d -0.316622 0.054509 0.297014
e 0.027428 0.065722 0.149325
i have two different dataframes with the same indexes and also the same column names and I want to substract each corrensponding value of them (for example df3[1,1]=df2[1,1]-df1[1,1]) and create a new dataframe with the new values. The dtypes of both dataframes are float64.
I tried the below and worked fine but it seems to me that it may exist a simpler way to do it.
df3=df2.select_dtypes(include=np.number)-df1.select_dtypes(include=np.number)
Can you please advise on an alternate way?
Thank you in advance for your support!
You can do this in a shorter manner:
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.rand(5, 3), index=['a', 'b', 'c', 'd', 'e'], columns=['col1', 'col2', 'col3'])
df2 = pd.DataFrame(np.random.rand(5, 3), index=['a', 'b', 'c', 'd', 'e'], columns=['col1', 'col2', 'col3'])
df3 = df2.sub(df1)
print(df3)
which retunrs:
col1 col2 col3
a -0.263918 0.621965 -0.222294
b 0.939496 -0.448462 0.010776
c -0.762741 -0.053359 0.628212
d -0.316622 0.054509 0.297014
e 0.027428 0.065722 0.149325