'How to output the last element by original sequences when using dataframe.last() after resample?
I have a dataframe as below and doing resample:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[datetime(2021, 3, 2, hour=11),
datetime(2021, 3, 2, hour=12),
datetime(2021, 3, 2, hour=13),
datetime(2021, 3, 2, hour=1),
datetime(2021, 3, 2, hour=2)])
r= df.resample('1D')
print(r.first())
print(r.last())
And the result is
0
2021-03-02 4
0
2021-03-02 3
Now I need r.first() to be datetime(2021, 3, 2, hour=11):1 and r.last() to be datetime(2021, 3, 2, hour=2):5 as the original sequences shows, but not the results after sorted. How can this be obtained?
Solution 1:[1]
For prevent sorting is possible use groupby with dates:
r= df.groupby(df.index.date)
print(r.first())
print(r.last())
0
2021-03-02 1
0
2021-03-02 5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jezrael |
