How to Swap Values Between Two Columns

How do I swap values in two columns by applying a function?

Here's one way indexing the dataframe on the rows where tmin is greater than tmax and using DataFrame.reindex to swap the values in both columns:

# columns to be used for indexing
cols = ["tmin","tmax"]
#indices where tmin is greater than tmax
ixs = df.tmin.gt(df.tmax)
# Where ixs is True, values are swapped
df.loc[ixs,cols] = df.loc[ixs, cols].reindex(columns=cols[::-1]).values

station date year month day rain tmin tmax
126 garoua 1954-05-07 1954 5 127 NaN 33.8 35.6
2012 garoua 1959-07-06 1959 7 187 NaN 31.6 33.0

Or using DataFrame.where:

df[cols] = df[cols].where(df.tmin.lt(df.tmax), df[cols[::-1]].values)

station date year month day rain tmin tmax
126 garoua 1954-05-07 1954 5 127 NaN 33.8 35.6
2012 garoua 1959-07-06 1959 7 187 NaN 31.6 33.0

How to swap the values in two columns in R?

the easiest way to do this:

tmp <- df[1]
df[1] <- df[2]
df[2] <- tmp


Related Topics



Leave a reply



Submit