python-3.x - 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)如果数据先旋转,如何做减法
谢谢
解决方案
使用groupby
with 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
推荐阅读
- javascript - 在其他方法中使用 Javascript-Object 和 Json-objects
- spring-boot - Spring Data Elasticsearch 没有给出预期的结果
- python - python xml和csv提取
- git - git merge 自动解决而不是显示合并冲突
- networking - 通过 WSL(v1)在 YARN 上使用 Pyspark 访问 Spark UI 时出现问题
- java - JCEF 函数仅从第二次调用开始起作用(Java Chromium Embedded Framework)
- vue.js - Jest 在 Vue/Vuex 项目中无法从窗口对象中找到模块
- javascript - 比较两个对象并使用 react 从数组中找到匹配的对象
- apache-kafka - macOS 上的 node-rdkafka:错误:配置属性“security.protocol”的值“sasl_ssl”无效
- security - 如何在 Windows 机器上使用 oAuth 进行 Kafka 安全设置 SASL_SSL?