Compare last element of a row to the rest of a row in pandas
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams
--
Chapters
00:00 Compare Last Element Of A Row To The Rest Of A Row In Pandas
00:47 Accepted Answer Score 2
01:20 Thank you
--
Full question
https://stackoverflow.com/questions/6095...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams
--
Chapters
00:00 Compare Last Element Of A Row To The Rest Of A Row In Pandas
00:47 Accepted Answer Score 2
01:20 Thank you
--
Full question
https://stackoverflow.com/questions/6095...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
ACCEPTED ANSWER
Score 2
Use DataFrame.lt for compare with last column selected by position:
df1 = df.iloc[:,:-1].lt(df.iloc[:, -1], axis=0)
#if want specify last column by label
#df1 = df.iloc[:,:-1].lt(df.col3, axis=0)
print (df1)
col1 col2
0 False False
1 True False
2 True True
3 False False
Last if need 0,1 convert to integers by DataFrame.astype:
df1 = df.iloc[:,:-1].lt(df.iloc[:, -1], axis=0).astype(int)
#if want specify last column by label
#df1 = df.iloc[:,:-1].lt(df.col3, axis=0).astype(int)
print (df1)
col1 col2
0 0 0
1 1 0
2 1 1
3 0 0
Your solution with numpy.where is possible use with DataFrame constructor:
arr = np.where(df.iloc[:,:-1].lt(df.col3, axis=0),1,0)
df1 = pd.DataFrame(arr, index=df.index, columns = df.columns[:-1])
print (df1)
col1 col2
0 0 0
1 1 0
2 1 1
3 0 0