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
Limit Ggplot2 Axes Without Removing Data (Outside Limits): Zoom
Consistent Width For Geom_Bar in the Event of Missing Data
Unordered Combinations of All Lengths
How to Remove Outliers from a Dataset
Why Is Rbindlist "Better" Than Rbind
Multiple Plots in For Loop Ignoring Par
Intelligent Point Label Placement in R
Merging Two Data Frames Using Fuzzy/Approximate String Matching in R
How to Change the Order of Facet Labels in Ggplot (Custom Facet Wrap Labels)
Select Groups Which Have At Least One of a Certain Value
Convert Column With Pipe Delimited Data into Dummy Variables
Finding Rows Containing a Value (Or Values) in Any Column
Increment by 1 For Every Change in Column
Scatterplot With Marginal Histograms in Ggplot2
Usage of '...' (Three-Dots or Dot-Dot-Dot) in Functions