首页 > 解决方案 > Python中基于多个标准(列)的逐行减法

问题描述

我有以下数据:

date      locid month       price
11/2/2017   17  11/1/2017   -0.0025
11/2/2017   17  12/1/2017   0
11/2/2017   105 11/1/2017   -0.895
11/2/2017   105 12/1/2017   -1
11/3/2017   17  11/1/2017   -0.0025
11/3/2017   17  12/1/2017   0.01
11/3/2017   105 11/1/2017   -0.895
11/3/2017   105 12/1/2017   -1.01

我想返回一个结果,显示每个地点、每个月、每个日期的价格差异。结果将只有四行:

date        month       price
11/2/2017   11/1/2017   0.8925
11/2/2017   12/1/2017   1
11/3/2017   11/1/2017   0.8925
11/3/2017   12/1/2017   1.02

我仅通过以下行获得了结果:

df.loc[df['locid']==17].price - df.loc[df['locid']==105].price

但是,我认为这不是一个可靠的解决方案。在对 df.date 列进行排序之前,我的结果包含八行。另外,我不确定 python/pandas 是否与 df.months 匹配,我认为它们可能恰好处于正确的顺序。

我想知道如何:

1)确保我以正确的顺序减去(在这种情况下,我想要 locid 17-105),如果它们在我的数据中的顺序相反怎么办?如果有三个 locids 而我只想看两个呢?

2) 确保 locid 17-105 是日期==11/2/2017 和月份==11/1/2017。IE 日期和月份必须匹配,然后再减去

3)如果数据先旋转,如何做减法

谢谢

标签: python-3.xpandas

解决方案


使用groupbywith diff,然后内部concat返回原始 df

df1=df.drop(['locid','price'],axis = 1)
df2=df.groupby(['date','month']).price.diff().dropna().abs()
pd.concat([df1,df2], axis = 1 ,join ='inner' )
Out[552]: 
        date      month   price
2  11/2/2017  11/1/2017  0.8925
3  11/2/2017  12/1/2017  1.0000
6  11/3/2017  11/1/2017  0.8925
7  11/3/2017  12/1/2017  1.0200

推荐阅读