I have got two identical dataframes in pandas/python (a and b) only values are different:
a:
date a1 a2 a3
01.01.2020 2 2 2
02.01.2020 3 3 3
03.01.2020 4 4 4
b:
date a1 a2 a3
01.01.2020 1 1 1
01.01.2020 2 2 2
01.01.2020 3 3 3
I need a - b and expect to see result c:
date a1 a2 a3
01.01.2020 1 1 1
01.01.2020 1 1 1
01.01.2020 1 1 1
a - b does not work and I cannot figure out how. Would you please help me? Thanks!
You can set_index
:
new_df = (a.set_index('date') - b.set_index('date')).reset_index()
However, that only works if your dates are identical between the two dataframes and different within each.
In the other case (as shown in your sample data) you can do:
c = b.copy()
c.iloc[:,1:] = a.iloc[:, 1:] - b.iloc[:,1:]
Try using df1.subtract(df2)
. Simple and elegant.
Assuming that dates in both dataframes are identical, you can use df.sub
:
df = a.set_index('date').sub(b.set_index('date')).reset_index()
Output:
date a1 a2 a3
0 01.01.2020 1 1 1
1 01.01.2020 1 1 1
2 01.01.2020 1 1 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.