I'm trying to change all values in the slice except the first one but it does not work... what am i doing wrong ?
print(test)
test.loc[(test.col_1==-5)&(test.index>'2018-07-17 13:00:00')&(test.index<'2018-07-17 14:00:00'),['col_1']][1:]=-1
print(test)
provides the below output
17/07/2018 13:51:00 -5
17/07/2018 13:52:00 -1
17/07/2018 13:53:00 -5
17/07/2018 13:54:00 -5
17/07/2018 13:55:00 -5
17/07/2018 13:56:00 -5
17/07/2018 13:57:00 -5
17/07/2018 13:58:00 -5
17/07/2018 13:59:00 -5
17/07/2018 13:51:00 -5
17/07/2018 13:52:00 -1
17/07/2018 13:53:00 -5
17/07/2018 13:54:00 -5
17/07/2018 13:55:00 -5
17/07/2018 13:56:00 -5
17/07/2018 13:57:00 -5
17/07/2018 13:58:00 -5
17/07/2018 13:59:00 -5
whereas i was expecting the 2nd output to be
17/07/2018 13:51:00 -5
17/07/2018 13:52:00 -1
17/07/2018 13:53:00 -1
17/07/2018 13:54:00 -1
17/07/2018 13:55:00 -1
17/07/2018 13:56:00 -1
17/07/2018 13:57:00 -1
17/07/2018 13:58:00 -1
17/07/2018 13:59:00 -1
You can use numpy.where
and use indexing [1:]
to exclude the first time the criterion is True
. Here's a minimal example:
df = pd.DataFrame([[1, -5], [2, -5], [3, -1], [4, -5], [5, -5], [6, -1]],
columns=['col1', 'col2'])
df.iloc[np.where(df['col1'].between(2, 5))[0][1:], 1] = -1
print(df)
col1 col2
0 1 -5
1 2 -5
2 3 -1
3 4 -1
4 5 -1
5 6 -1
There is problem join boolean indexing (filtering) with selecting, one possible solution is add new condiction:
test.index = pd.to_datetime(test.index)
mask = (test.col_1==-5)&(test.index>'2018-07-17 13:00:00')&(test.index<'2018-07-17 14:00:00')
m1 = np.arange(len(test)) > 1
test.loc[mask & m1, 'col_1']=-1
print (test)
col_1
2018-07-17 13:51:00 -5
2018-07-17 13:52:00 -1
2018-07-17 13:53:00 -1
2018-07-17 13:54:00 -1
2018-07-17 13:55:00 -1
2018-07-17 13:56:00 -1
2018-07-17 13:57:00 -1
2018-07-17 13:58:00 -1
2018-07-17 13:59:00 -1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.