python - 如何通过应用函数交换两列中的值?
问题描述
我有一个包含各种列的数据集。我想通过应用函数来交换最低温度(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
解决方案
tmin
这是在大于的行上索引数据框tmax
并DataFrame.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
推荐阅读
- delphi - 传递对象的过程而不参考过程的类型
- react-native - 反应原生动画。您必须为每个变换对象指定一个属性
- javascript - highcharts 热图的奇怪问题 - 不正确的 Y 轴缩放
- sql - 从 sql server 中的各个行获取最大 ID 行
- flutter - Q:Flutter 插件 just_audio
- pandas - Pandas eval:对生成的结果运行方法(例如 (A/B).min())
- jquery - 选择2:如何创建列表中已存在的选项
- java - 设置 XMLGregorianCalendar 的时区
- c++ - 如何使用 boost::process::system 运行脚本?
- postgresql - 如何在我的 postgres 图像中更正 set work_mem amd max_wal_size