简体   繁体   English

如何在 pandas 中减去两个相同的数据帧

[英]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.

相关问题 减去两个 Pandas 数据帧 - Subtract two Pandas Dataframes 减去熊猫中两个不平衡的数据框 - Subtract two unbalanced DataFrames in Pandas pandas 减去具有相同列的两个数据帧中的值创建新的 dataframe 以存储结果 - pandas subtract values in two dataframes with identical columns create new dataframe to store result 我应该如何减去两个数据帧和Pandas并显示所需的输出? - How should I subtract two dataframes and in Pandas and diplay the required output? 熊猫基于多个索引的两个数据帧相减 - Pandas Two Dataframes subtract based on multi indexes Pandas - 合并两个具有相同列名称的DataFrame - Pandas - merge two DataFrames with Identical Column Names 当索引是日期时间时,如何相互减去两个pandas日期时间系列DataFrame? - How do I subtract two pandas datetime series DataFrames from each other when the index is a datetime? 如何减去两个数据帧,部分公共索引 - How to subtract two dataframes , partial common indexes 如何合并两个具有相同属性的 pandas 数据帧并覆盖相同的行? - How do you merge two pandas dataframes with the same attributes and overwrite the rows that are identical? 如何从两个形状相同的Pandas数据框中选择元素位置,且值在一定范围内匹配? - How to select element locations from two Pandas dataframes of identical shape, where the values match within a certain range?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM