I have a dataframe df like the one below:
city datetime value
0 city_a 2020-07-10 2
1 city_a 2020-07-11 5
2 city_b 2020-07-11 4
And I am trying to resample the daily datetimes with a 6h frequency (data every 00h, 6h, 12h and 18h).
The following code gives me almost the output I am expecting
my_df = my_df.set_index(['datetime', 'city'])
my_df = my_df.unstack(-1).resample('6H').pad()
my_df = my_df.stack().reset_index()
my_df = my_df[['city', 'datetime', 'value']]
my_df = my_df.sort_values(['city', 'datetime'])
Output:
city datetime value
0 city_a 2020-07-10 00:00:00 2.0
1 city_a 2020-07-10 06:00:00 2.0
2 city_a 2020-07-10 12:00:00 2.0
3 city_a 2020-07-10 18:00:00 2.0
4 city_a 2020-07-11 00:00:00 5.0
5 city_b 2020-07-11 00:00:00 4.0
However, we can see that the day 2020-07-11 is not complete. I would like the rows including 2020-07-11 06:00:00, 12:00:00 and 18:00:00 to appear into the output.
So my expected output should be:
city datetime value
0 city_a 2020-07-10 00:00:00 2.0
1 city_a 2020-07-10 06:00:00 2.0
2 city_a 2020-07-10 12:00:00 2.0
3 city_a 2020-07-10 18:00:00 2.0
4 city_a 2020-07-11 00:00:00 5.0
6 city_a 2020-07-11 06:00:00 5.0
8 city_a 2020-07-11 12:00:00 5.0
10 city_a 2020-07-11 18:00:00 5.0
5 city_b 2020-07-11 00:00:00 4.0
7 city_b 2020-07-11 06:00:00 4.0
9 city_b 2020-07-11 12:00:00 4.0
11 city_b 2020-07-11 18:00:00 4.0
Is there an elegant way to do it with Pandas ?
Code to generate the dataframe:
my_df = pd.DataFrame(data = {
'city': ['city_a', 'city_a', 'city_b'],
'datetime':
[pd.to_datetime('2020/07/10'),pd.to_datetime('2020/07/11'),pd.to_datetime('2020/07/11')],
'value': [2,5,4]
})