Reputation: 1723
Below is my dataframe
S2BillDate totSale count
0 2020-03-01 27880.21 796
1 2020-03-02 45664.74 1278
2 2020-03-03 41554.50 1170
3 2020-03-04 42929.59 1239
4 2020-03-05 49113.58 1380
5 2020-03-06 46945.72 1328
6 2020-03-07 12706.32 455
If my input is 2020-03-07
, how can I retrieve the value above it, ie in this case 2020-03-06
.
Also How can i use get_value()
to retrieve 'totSale' to the corresponding date ?
Is there any easier way to achieve it via pandas itself ?
Upvotes: 0
Views: 47
Reputation: 34056
This could be a simple solution:
In [65]: df['S2BillDate'] = pd.to_datetime(df['S2BillDate'])
In [67]: df = df.set_index('S2BillDate')
In [69]: s = '2020-03-07' ## input value
In [70]: s = pd.Timestamp(s)
In [73]: loc = df.index.get_loc(s)
get_value()
is now deprecated, do below instead:In [79]: df.iloc[loc - 1]['totSale']
Out[79]: 46945.72
Upvotes: 0
Reputation: 30920
We can use Series.eq
and Series.shift
in order to performance a boolean indexing
with DataFrame.loc
:
m = df['S2BillDate'].eq('2020-03-07').shift(-1, fill_value=False)
df.loc[m]
df.loc[m, 'S2BillDate']
df.loc[m, ['S2BillDate', 'totSale']]
Upvotes: 1
Reputation: 177
To retrive the value(s) above '2020-03-07':
df['S2BillDate'][df.S2BillDate.tolist().index('2020-03-07')-1]
>>> '2020-03-06'
df['totSale'][df.S2BillDate.tolist().index('2020-03-07')-1]
>>> 46945.72
Upvotes: 0