I'm trying to look for true conditions where "this" is greater than "that" starting with row 2 (index is greater than 1). For instance if the df is 5 rows long and "this" is greater than "that" in rows 1, 4, and 5 then the return would be 0,0,0,1,1. The index itself is a datetime string. However, someinteger is the actual index row value (a value from zero to length-1 of the df) It seems pretty easy and trivial but I'm having difficulty. I have tried this, but it's not working.
import panda as pd
import numpy as np
df = pd.DataFrame({
'this': [5,2,2,5,5],
'that': [3,3,3,3,3]})
someintegervalue = 1
df['blah blah blah'] = np.where(df.index > someintegervalue & df['this'] > df['that'], 0, 1)
CodePudding user response:
IIUC, you could just do:
import numpy as np
df['blah blah blah']= np.where(np.arange(len(df)) > someintegervalue & df['this']>df['that'], 0, 1)
CodePudding user response:
You were close. You just need to enclose your conditions in () and flip the last two np.where() arguments.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'this': [5,2,2,5,5],
'that': [3,3,3,3,3]})
someintegervalue = 1
df['blah blah blah']= np.where((df.index > someintegervalue) & (df['this'] > df['that']), 1, 0)
Output:
this that blah blah blah
0 5 3 0
1 2 3 0
2 2 3 0
3 5 3 1
4 5 3 1