如何根据另一列的值在具有开始日期和结束日期的时间序列熊猫数据框中查找链?

时间:2021-02-10 22:51:03

标签: python python-3.x pandas dataframe

我有一个看起来像这样的数据框

          beginDate     endDate        rating 
id
1         2019-11-05    2020-03-24      2    
2         2020-03-24    2020-08-19      1    
3         2020-08-19    2020-12-31      2
4         2020-12-31    2050-12-31      3

我希望能够检测 1 -> 2 和 2 -> 1 之间的评级值链,并综合添加行以获取此新数据框,其中包含链开头的 beginDate 和结尾的 endDate链:

          beginDate     endDate        rating 
id
1         2019-11-05    2020-03-24      2    
2         2020-03-24    2020-08-19      1    
3         2020-08-19    2020-12-31      2
4         2020-12-31    2050-12-31      3
5         2019-11-05    2020-12-31      1+2

关于如何干净地、更重要的是有效地做到这一点有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这做了很多假设,即您的数据总是正确排序,您正在寻找 1 和 2 中的变化,而不是 1 或 2 个评级,并且您没有说是否需要将其作为更大数据框的一部分其中 groupbyapply 是必需的。这可以适用于这些场景:

df =  pd.read_csv(io.StringIO('''id   beginDate     endDate        rating 
1         2019-11-05    2020-03-24      2    
2         2020-03-24    2020-08-19      1    
3         2020-08-19    2020-12-31      2
4         2020-12-31    2050-12-31      3'''), sep='\s+', engine='python').set_index('id')

# drop ratings 3 and above and find start and end dates, add r       
s = df.loc[df.rating < 3].head(1)['beginDate'].iat[0]
e = df.loc[df.rating < 3].tail(1)['endDate'].iat[0]
r = '1+2'

add_dict = {'beginDate': s, 'endDate': e,  'rating': r}
# append dictionary
df.append(add_dict, ignore_index=True)

输出:

df.append(add_dict, ignore_index=True)

    beginDate     endDate rating
0  2019-11-05  2020-03-24      2
1  2020-03-24  2020-08-19      1
2  2020-08-19  2020-12-31      2
3  2020-12-31  2050-12-31      3
4  2019-11-05  2020-12-31    1+2
相关问题