首页 > 解决方案 > 根据熊猫数据框中的列值获取更改日期

问题描述

我有以下数据框:

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]

标签: pythonpandas

解决方案


使用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'])

推荐阅读