surendra suri
surendra suri

Reputation: 31

Swapping Column values based on condition

this is my dataframe

S.No    Column1 Column2
0   7   A   B
1   2   D   F
2   5   C   H
3   9   NaN J
4   1   T   G
5   4   Z   True
6   10  S   Y
7   3   G   V
8   10  R   Y
9   8   T   X

df.replace([np.nan,True],'A',inplace=True)

    S.No    Column1 Column2
0   7   A   B
1   2   D   F
2   5   C   H
3   9   A   J
4   1   T   G
5   4   Z   A
6   10  S   Y
7   3   G   V
8   10  R   Y
9   8   T   X

required output be like

    S.No    Column1 Column2
0   7   B   A
1   2   F   D
2   5   H   C
3   9   J   A
4   1   T   G
5   4   Z   A
6   10  Y   S
7   3   V   G
8   10  Y   V
9   8   X   T

HOW TO WRITE CODE

Upvotes: 0

Views: 51

Answers (2)

SeaBean
SeaBean

Reputation: 23217

If you want to swap the contents of the 2 columns, you can use:

df[['Column1', 'Column2']] = list(zip(df['Column2'], df['Column1']))

or use .to_numpy() or .values, as follows:

df[['Column1', 'Column2']] = df[['Column2', 'Column1']].to_numpy()

or

df[['Column1', 'Column2']] = df[['Column2', 'Column1']].values

Result:

Based on your data after df.replace:

print(df)

   S.No Column1 Column2
0     7       B       A
1     2       F       D
2     5       H       C
3     9       J       A
4     1       G       T
5     4       A       Z
6    10       Y       S
7     3       V       G
8    10       Y       R
9     8       X       T

Upvotes: 1

Corralien
Corralien

Reputation: 120409

Use rename:

>>> df

   S.No Column1 Column2
0     7       A       B
1     2       D       F
2     5       C       H
3     9     NaN       J
4     1       T       G
5     4       Z    True
6    10       S       Y
7     3       G       V
8    10       R       Y
9     8       T       X

>>> df.rename(columns={'Column1': 'Column2', 'Column2': 'Column1'})[df.columns]

   S.No Column1 Column2
0     7       B       A
1     2       F       D
2     5       H       C
3     9       J     NaN
4     1       G       T
5     4    True       Z
6    10       Y       S
7     3       V       G
8    10       Y       R
9     8       X       T

Upvotes: 1

Related Questions