Skip to content Skip to sidebar Skip to footer

Pandas Dataframe Fails To Assign Value To Slice Subset

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-

Solution 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] = -1print(df)

   col1  col2
01-512-523-134-145-156-1

Solution 2:

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-1713:00:00')&(test.index<'2018-07-1714:00:00')m1=np.arange(len(test))>1test.loc[mask&m1,'col_1']=-1print(test)col_12018-07-17 13:51:00     -52018-07-17 13:52:00     -12018-07-17 13:53:00     -12018-07-17 13:54:00     -12018-07-17 13:55:00     -12018-07-17 13:56:00     -12018-07-17 13:57:00     -12018-07-17 13:58:00     -12018-07-17 13:59:00     -1

Post a Comment for "Pandas Dataframe Fails To Assign Value To Slice Subset"