Create a New Column Based on Some Values From Other Column in Pandas

Viewed 54

Imagine that this Data Set:

   A
1  2
2  4
3  3
4  5
5  5
6  5

I would like to create new column by this condition from A:

if A[i] < A[i-1] then B[i] = -1 else B[i] = 1 

the result is:

   A   B
1  2   NaN
2  4   1
3  3   -1
4  5   1
5  7   1
6  6   -1

All codes and solutions that I have found just compare the rows in same location.

3 Answers
df['B']=[1 if i!=0 and df['A'][i] < df['A'][i-1] else -1 for i,v in enumerate(df['A'])]

or

df['B']=[1 if i!=0 and df['A'][i] < df['A'][i-1] else -1 for i in range(len(df['A']))]

Edit (for three states like greater, less, and equal):

import numpy as np
df['B']=np.NAN*len(df.a)
for i in range(1,len(df['a'])):
    if df['a'][i] < df['a'][i-1]: df['B'][i]=1
    elif df['a'][i] == df['a'][i-1]: df['B'][i]=0
    else: df['B'][i]=-1
    

Use the diff function. then the sign function:

df.assign(B = np.sign(df.A.diff()))

Out[248]: 
   A    B
0  2  NaN
1  4  1.0
2  3 -1.0
3  5  1.0
4  7  1.0
5  6 -1.0
import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [2,4,3,5,7,6]})
df['B'] = np.where(df['A'] < df['A'].shift(1), -1, 1)

in order to keep the nan in the beginning:

df['B'] = np.where(df['A'].shift(1).isna(), np.nan, df['B'])
Related