问题描述
我有一个包含三列的时间序列数据框......日期、时间和值,它看起来像这样:
I have a timeseries dataframe that has three columns... date, time and value and it looks like this:
**date** **time** **value**
11.03.2020 1103 5
11.03.2020 0000 10
11.03.2020 0100 6
12.03.2020 0201 8
12.03.2020 0305 7
12.03.2020 0400 4
基本上时间列每行增加 60 (+-5) 分钟.我想以这样的方式更正我的日期列值,当时间为 0000 (+-5) 时,日期列的日期部分增加 1,直到遇到下一个 0000 (+-5) 时间值,然后增加再次减 1,直到遇到下一个这样的时间值或到达数据帧的末尾.
basically the time column is incrementing by 60 (+-5) mins for every row. I want to correct my date column values in such a way that whenever the time is 0000 (+-5) the day part of the date column increments by 1 untill the next 0000 (+-5) time value is encountered and than it increments by 1 again untill the next such time value is encountered or the end of the data frame is reached.
结果应该是这样的:
**date** **time** **value**
11.03.2020 1103 5
12.03.2020 0000 10
12.03.2020 0100 6
12.03.2020 0201 8
12.03.2020 0305 7
12.03.2020 0400 4
我希望得到一些帮助.谢谢
I would appreciate some help. Thanks
推荐答案
将date
列中的字符串解析为datetime
df['date'] = pd.to_datetime(df['date'], dayfirst=True)
通过将 time
列与 0000
进行比较来创建布尔掩码 m
,使用布尔索引添加 DateOffset
1 days
到日期列中布尔掩码为真的值,然后 mask
和 forward fill
更新日期列中的值,其中当前日期小于前一个日期
Create a boolean mask m
by comparing the time
column with 0000
, using boolean indexing add the DateOffset
of 1 days
to the values in date column where the boolean mask holds true, then mask
and forward fill
the values in updated date column where the current date is less that previous date
m = df['time'].eq('0000')
df.loc[m, 'date'] += pd.DateOffset(days=1)
df['date'] = df['date'].mask(df['date'].diff().dt.days.lt(0)).ffill()
date time value
0 2020-03-11 1103 5
1 2020-03-12 0000 10
2 2020-03-12 0100 6
3 2020-03-12 0201 8
4 2020-03-12 0305 7
5 2020-03-12 0400 4
这篇关于根据时间序列数据帧的时间列更正日期列中的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!