python - 根据熊猫数据框中的列值获取更改日期
问题描述
我有以下数据框:
fid date stage
test_fid 4/22/2019 a1
test_fid 4/23/2019 a1
test_fid 4/24/2019 a2
test_fid 4/25/2019 a2
test_fid 4/26/2019 a2
test_fid 4/27/2019 a3
test_fid 4/28/2019 a3
test_fid 4/29/2019 a3
test_fid1 4/30/2019 a1
test_fid1 5/1/2019 a1
test_fid1 5/2/2019 a1
test_fid1 5/3/2019 a1
test_fid1 5/4/2019 a2
test_fid1 5/5/2019 a2
test_fid1 5/6/2019 a2
test_fid1 5/7/2019 a2
test_fid1 5/8/2019 a3
test_fid1 5/9/2019 a3
test_fid1 5/10/2019 a3
我想确定阶段列值开始和结束的日期,例如 test_fid 的阶段 a1 从 2019 年 4 月 22 日到 2019 年 4 月 23 日。结果应如下所示:
fid stage start_date end_date
test_fid a1 4/22/2019 4/23/2019
test_fid a2 4/24/2019 4/26/2019
test_fid a3 4/27/2019 4/29/2019
test_fid1 a1 4/30/2019 5/3/2019
test_fid1 a2 5/4/2019 5/7/2019
test_fid1 a3 5/8/2019 5/10/2019
我试过这个:
df['stage_change'] = df['stage'].diff()
df_filtered = df[df['stage_change'] != 0]
解决方案
使用sort_values
日期和groupby
。然后汇总第一个和最后一个日期。
df.sort_values('date').groupby(['stage','fid']).agg({'date':['first', 'last']}).reset_index()
结果
stage fid date
first last
0 a1 test_fid 2019-04-22 2019-04-23
1 a1 test_fid1 2019-04-30 2019-05-03
2 a2 test_fid 2019-04-24 2019-04-26
3 a2 test_fid1 2019-05-04 2019-05-07
4 a3 test_fid 2019-04-27 2019-04-29
5 a3 test_fid1 2019-05-08 2019-05-10
编辑:我首先转换为日期时间
df['date'] = pd.to_datetime(df['date'])
推荐阅读
- c - 0/0 (NAN) 和 1/0 (INF) 的字节表示在任何 C 编译器和机器上都相同吗?
- angular - Angular 不在 UI 中显示数据
- docusignapi - DOCUSIGN API - 如何为多个用户使用同一个帐户
- java - 在 Android 中使用 JAVA 在 onFocusChange 中使用 AsyncTask
- vue.js - 如何保存十进制数字以保存点数
- internet-explorer - 浏览器中的 Acrobat - 更改书签字体大小
- php - 如何读取 html 页面并将其内容转换为 xml 以读取内容?
- mysql - MySQL:如何对数据库表的所有列使用 ANY_VALUE
- java - 字符类中是否有任何方法允许两个单词之间有空格
- javascript - Selenium webdriver 在 Electron 构建中不起作用