metalrules211
metalrules211

Reputation: 197

Add a state column when another column is increasing/decreasing

I would like to add a column in a data frame when another column is increasing/decreasing or stays the same with: 1 -> increasing, 0 -> same, -1 -> decreasing

So if df['battery'] = [1,2,3,4,7,9,3,3,3,] I would like state to be df['state'] = [1,1,1,1,1,-1,0,0]

Upvotes: 2

Views: 173

Answers (4)

BENY
BENY

Reputation: 323356

Try pd.np.sign

pd.np.sign(df.battery.diff().fillna(1))
0    1.0
1    1.0
2    1.0
3    1.0
4    1.0
5    1.0
6   -1.0
7    0.0
8    0.0
Name: battery, dtype: float64

Upvotes: 1

Georgy
Georgy

Reputation: 13737

You could use pd.Series.diff method to get the difference between consecutive values, and then assign the necessary state values by using boolean indexing:

import pandas as pd

df = pd.DataFrame()
df['battery'] = [1,2,3,4,7,9,3,3,3]

diff = df['battery'].diff()
df.loc[diff > 0, 'state'] = 1
df.loc[diff == 0, 'state'] = 0
df.loc[diff < 0, 'state'] = -1

print(df)
#    battery  state
# 0        1    NaN
# 1        2    1.0
# 2        3    1.0
# 3        4    1.0
# 4        7    1.0
# 5        9    1.0
# 6        3   -1.0
# 7        3    0.0
# 8        3    0.0

Or, alternatively, one could use np.select:

import numpy as np

diff = df['battery'].diff()
df['state'] = np.select([diff < 0, diff > 0], [-1, 1], 0)
# Be careful, default 0 will replace the first NaN as well.

print(df)
#    battery  state
# 0        1      0
# 1        2      1
# 2        3      1
# 3        4      1
# 4        7      1
# 5        9      1
# 6        3     -1
# 7        3      0
# 8        3      0

Upvotes: 1

Giorgos Myrianthous
Giorgos Myrianthous

Reputation: 39910

So here's your dataframe:

>>> import pandas as pd
>>> data = [[[1,2,3,4,7,9,3,3,3]]]
>>> df = pd.DataFrame(data, columns = ['battery'])
>>> df
                       battery
0  [1, 2, 3, 4, 7, 9, 3, 3, 3]

And finally use apply and a lambda function in order to generate the required result:

>>> df['state'] = df.apply(lambda row: [1 if t - s > 0 else -1 if t-s < 0 else 0 for s, t in zip(row['battery'], row['battery'][1:])], axis=1)
>>> df
                       battery                      state
0  [1, 2, 3, 4, 7, 9, 3, 3, 3]  [1, 1, 1, 1, 1, -1, 0, 0]

Alternatively, if you want the exact difference between each element in the list, you can use the following:

>>> df['state'] = df.apply(lambda row: [t - s for s, t in zip(row['battery'], row['battery'][1:])], axis=1)
>>> df
                       battery                      state
0  [1, 2, 3, 4, 7, 9, 3, 3, 3]  [1, 1, 1, 3, 2, -6, 0, 0]

Upvotes: 1

ToTheMax
ToTheMax

Reputation: 1031

This should do the trick!

a = [1,2,3,4,7,9,3,3,3]
b = []

for x in range(len(a)-1):
  b.append((a[x+1] > a[x]) - (a[x+1] < a[x]))

print(b)

Upvotes: 2

Related Questions