Mert Açikel
Mert Açikel

Reputation: 99

detecting only changing value sign from positive to negative

i have a df like:

    A   B   C
0   1   7   1
1   2   8   -1
2   3   12  -3
3   4   14  4
4   3   16  -3
5   4   22  1
6   5   23  1
7   3   23  8
8   4   4   10
9   5   56  12

how can i detect sign change from positive to negative and insert a spesific row to a dataframe. For example column C is starting with 1 then turning -1, so i need to add a row. I am trying to get a dataframe like:

    A   B      C
0   1.0 7.0    1
X   NaN NaN    NaN
1   2.0 8.0   -1
2   3.0 12.0  -3
3   4.0 14.0   4
X   NaN NaN    NaN
4   3.0 16.0  -3
5   4.0 22.0   1
6   5.0 23.0   1
7   3.0 23.0   8
8   4.0 4.0    10
9   5.0 56.0   12

Or can you just tell where should i look for that gives a series values that is only detecting sign change from postive to negative?

Upvotes: 1

Views: 361

Answers (2)

anky
anky

Reputation: 75080

You can create a helper series with help of np.sign and series.diff to identify each group and append a blank row then concat:

s = np.sign(df['C']).diff().fillna(0).lt(0).cumsum()
out = pd.concat([g.append(pd.Series(name='X')) for _,g in df.groupby(s)]).iloc[:-1]

print(out)

     A     B     C
0  1.0   7.0   1.0
X  NaN   NaN   NaN
1  2.0   8.0  -1.0
2  3.0  12.0  -3.0
3  4.0  14.0   4.0
X  NaN   NaN   NaN
4  3.0  16.0  -3.0
5  4.0  22.0   1.0
6  5.0  23.0   1.0
7  3.0  23.0   8.0
8  4.0   4.0  10.0
9  5.0  56.0  12.0

Upvotes: 1

Henry Yik
Henry Yik

Reputation: 22493

You can obtain the position to insert the NaNs and then append:

idx = df.index[df["C"].ge(0)&df["C"].shift(-1).lt(0)]

print (df.append(pd.DataFrame(np.NaN, index=idx, columns=df.columns)).sort_index())

     A     B     C
0  1.0   7.0   1.0
0  NaN   NaN   NaN
1  2.0   8.0  -1.0
2  3.0  12.0  -3.0
3  4.0  14.0   4.0
3  NaN   NaN   NaN
4  3.0  16.0  -3.0
5  4.0  22.0   1.0
6  5.0  23.0   1.0
7  3.0  23.0   8.0
8  4.0   4.0  10.0
9  5.0  56.0  12.0

Upvotes: 2

Related Questions