Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping column values based on column conditions (Pandas DataFrame)

Tags:

python

pandas

The DataFrame has two columns A and B of integers.

a        b
1        3
4        2
2        0
6        1
...

I need to swap in the following way:

if df.a > df.b:
    temp = df.b
    df.b = df.a
    df.a = temp

expected output:

a        b
1        3
2        4    <----
0        2    <----
1        6    <----

Basically always having in column A the smaller value of the twos.

I feel I should use loc but I couldn't find the right way yet.

like image 719
csbr Avatar asked Dec 02 '22 12:12

csbr


2 Answers

In [443]: df['a'], df['b'] = df.min(axis=1), df.max(axis=1)

In [444]: df
Out[444]:
   a  b
0  1  3
1  2  4
2  0  2
3  1  6

or

pd.DataFrame(np.sort(d.values, axis=1), d.index, d.columns)
like image 73
MaxU - stop WAR against UA Avatar answered Mar 09 '23 01:03

MaxU - stop WAR against UA


Using np.where you can do

In [21]: df.a, df.b = np.where(df.a > df.b, [df.b, df.a], [df.a, df.b])

In [23]: df
Out[23]:
   a  b
0  1  3
1  2  4
2  0  2
3  1  6

Or, using .loc

In [35]: cond = df.a > df.b

In [36]: df.loc[cond, ['a', 'b']] = df.loc[cond, ['b', 'a']].values

In [37]: df
Out[37]:
   a  b
0  1  3
1  2  4
2  0  2
3  1  6

Or, .apply(np.sort, axis=1) if you need smaller a values and larger b

In [54]: df.apply(np.sort, axis=1)
Out[54]:
   a  b
0  1  3
1  2  4
2  0  2
3  1  6
like image 28
Zero Avatar answered Mar 09 '23 01:03

Zero