Reputation: 527
I want to compare for each row, values of A with the other columns
The problem is more complex but i tried to simplify it in this table:
A B C D
0 1.3 1.0 1.1 1
1 2.5 2.9 2.6 3
2 3.1 3.0 3.2 2
The result should look like this:
Here in index 0: 1.3 is larger than the values in B,C and D, then we return 1, otherwise it is 0
A B C D result
0 1.3 1.0 1.1 1 1
1 2.5 2.9 2.6 3 0
2 3.1 3.0 3.2 2 0
Thank you in advance
Upvotes: 1
Views: 505
Reputation: 6589
You can use idxmax:
df['result'] = (df.idxmax(axis=1)== 'A').astype(int)
Output:
A B C D result
0 1.3 1.0 1.1 1 1
1 2.5 2.9 2.6 3 0
2 3.1 3.0 3.2 2 0
Upvotes: 1
Reputation: 387
if you know the column names do:
df['results']=(df.loc[:,'A']>df.loc[:,'B':'D'].max(axis=1)).astype(int)
if you know want to work with columns order you can do:
df['results']=(df.iloc[:,0]>df.iloc[:,1:].max(axis=1)).astype(int)
on your example those will give the same output. the "astype(int)" at the end converts the boolean value to 0/1.
Upvotes: 0
Reputation: 862511
You can use gt
or le
for compare, then any
or all
for get at least one True
or all
Trues and last cast boolean mask to int
:
df['result'] = (~df[['B','C','D']].gt(df.A, axis=0).any(1)).astype(int)
print (df)
A B C D result
0 1.3 1.0 1.1 1 1
1 2.5 2.9 2.6 3 0
2 3.1 3.0 3.2 2 0
Another solution:
df['result'] = df[['B','C','D']].le(df.A, axis=0).all(1).astype(int)
print (df)
A B C D result
0 1.3 1.0 1.1 1 1
1 2.5 2.9 2.6 3 0
2 3.1 3.0 3.2 2 0
Upvotes: 2
Reputation: 294218
Use assign
to create new column
Use df.le(df.A, 0)
to compare column 'A'
to all other columns
Use all(1)
to find where True
for all columns
Use astype(int)
to make it 1
or 0
df.assign(result=df.lt(df.A, 0).all(1).astype(int))
A B C D result
0 1.3 1.0 1.1 1 1
1 2.5 2.9 2.6 3 0
2 3.1 3.0 3.2 2 0
Upvotes: 5