首页 > 解决方案 > 如何通过应用函数交换两列中的值?

问题描述

我有一个包含各种列的数据集。我想通过应用函数来交换最低温度(tmin)大于最高温度(tmax)的值。

我要应用的功能:

def swap(a,b):
    if a >= b:
        return b,a
    else:
        return a,b

应用它:

cam.apply(lambda row: swap(row['tmin'], row['tmax']), axis=1)

当我检查代码是否有效时,我发现它没有改变任何东西 cam.query('tmin>tmax')

station       date  year  month  day  rain  tmin  tmax

126  garoua  1954-05-07  1954      5  127  NaN   35.6  33.8

2012 garoua  1959-07-06  1959      7  187  NaN   33.0  31.6

标签: pythonpython-3.x

解决方案


tmin这是在大于的行上索引数据框tmaxDataFrame.reindex用于交换两列中的值的一种方法:

# 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

或使用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

推荐阅读