[英]How to subtract two identical dataframes in pandas
I have got two identical dataframes in pandas/python (a and b) only values are different:我在 pandas/python(a 和 b)中有两个相同的数据框,只有值不同:
a: 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:我需要 a - b 并希望看到结果 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. a - b 不起作用,我不知道怎么做。 Would you please help me?
你能帮帮我吗? Thanks!
谢谢!
You can set_index
:您可以
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)
.尝试使用
df1.subtract(df2)
。 Simple and elegant.简单而优雅。
Assuming that dates in both dataframes are identical, you can use df.sub
:假设两个数据框中的日期相同,您可以使用
df.sub
:
df = a.set_index('date').sub(b.set_index('date')).reset_index()
Output: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.