sparrow
sparrow

Reputation: 11460

Pandas conditionaly swap values in two columns

I have a Pandas DataFrame with two columns. In some of the rows the columns are swapped. If they're swapped then column "a" will be negative. What would be the best way to check that and then swap the values of the two columns.

def swap(a,b):
    if a < 0:
        return b,a
    else:
        return a,b

Is there some way to use apply with this function to swap the two values?

Upvotes: 3

Views: 4230

Answers (2)

piRSquared
piRSquared

Reputation: 294258

Out of boredom:

df.values[:] = df.values[
    np.arange(len(df))[:, None],
    np.eye(2, dtype=int)[(df.a.values >= 0).astype(int)]
]

df

   a  b
0  3 -1
1  3 -1
2  8 -1
3  2  9
4  0  7
5  0  4

Upvotes: 1

BENY
BENY

Reputation: 323226

Try this ? By using np.where

ary=np.where(df.a<0,[df.b,df.a],[df.a,df.b])
pd.DataFrame({'a':ary[0],'b':ary[1]})

Out[560]: 
   a  b
0  3 -1
1  3 -1
2  8 -1
3  2  9
4  0  7
5  0  4

Data input :

df
Out[561]: 
   a  b
0 -1  3
1 -1  3
2 -1  8
3  2  9
4  0  7
5  0  4

And using apply

def swap(x):
    if x[0] < 0:
        return [x[1],x[0]]
    else:
        return [x[0],x[1]]


df.apply(swap,1)
Out[568]: 
   a  b
0  3 -1
1  3 -1
2  8 -1
3  2  9
4  0  7
5  0  4

Upvotes: 5

Related Questions