I have it currently working comparing two values on the same row but different columns but I need it to compare one value to the previous row.
For example: I need to compare the column 'Close' of the row at index 0 to the column 'Open' of the row at index 1.
df['HigherLower'] = 'No Change'
for index, row in df.iterrows():
if row['Open'] < row['Close'] :
df['HigherLower'] = df['HigherLower'].replace(['No Change'],'Lower')
else:
df['HigherLower'] = df['HigherLower'].replace(['No Change'],'Higher')
CodePudding user response:
Use np.where
:
import pandas as pd
import numpy as np
df = pd.DataFrame({'Open': [10, 20, 30], 'Close': [5, 25, 15]})
df['HigherLower'] = np.where(df['Open'].shift() < df['Close'], 'Lower', 'Higher')
print(df)
# Output:
Open Close HigherLower
0 10 5 Higher
1 20 25 Lower
2 30 15 Higher