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

Time:04-24

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.

CodePudding user response:

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']))]

CodePudding user response:

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