The Python Oracle

Compare last element of a row to the rest of a row in pandas

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 Question
00:58 Accepted answer (Score 2)
01:50 Thank you

--

Full question
https://stackoverflow.com/questions/6095...

Accepted answer links:
[DataFrame.lt]: http://pandas.pydata.org/pandas-docs/sta...
[DataFrame.astype]: http://pandas.pydata.org/pandas-docs/sta...
[numpy.where]: https://docs.scipy.org/doc/numpy/referen...

--

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