如何在column 1值小于column 2时交换对应行两列的数值
需求说明
逐行判断数据的column 1与column 2取值,当column 1的值小于column 2的值时,交换当前行这两列的对应数值。
输入输出示例
输入示例:
Index column 1 column 2 0 5 6 1 4 3 2 6 8 3 2 4
期望输出示例:
Index column 1 column 2 0 6 5 1 4 3 2 8 6 3 4 2
实现方案
方案1:Pandas实现(适合结构化表格数据处理场景)
核心逻辑是先筛选出满足column 1 < column 2的行,再批量交换两列取值:
import pandas as pd # 可替换为pd.read_csv/ pd.read_excel读取本地数据文件 df = pd.DataFrame( data=[[5,6],[4,3],[6,8],[2,4]], columns=["column 1", "column 2"], index=[0,1,2,3] ) df.index.name = "Index" # 核心交换逻辑 swap_mask = df["column 1"] < df["column 2"] df.loc[swap_mask, ["column 1", "column 2"]] = df.loc[swap_mask, ["column 2", "column 1"]].values print(df)
方案2:纯Python原生实现(无需依赖第三方库)
直接遍历每行数据做判断交换,适合轻量场景:
# 原始数据可从文件读取后按格式解析为嵌套列表 raw_data = [ [0,5,6], [1,4,3], [2,6,8], [3,2,4] ] # 遍历交换逻辑 for row in raw_data: col1_val = row[1] col2_val = row[2] if col1_val < col2_val: row[1], row[2] = col2_val, col1_val # 格式化打印输出 print("Index column 1 column 2") for item in raw_data: print(f"{item[0]:<8}{item[1]:<10}{item[2]}")
内容的提问来源于stack exchange,提问作者surendra suri
相关产品推荐
相关产品推荐

