首页 > 解决方案 > 遍历行并比较两列并应用逻辑并更改熊猫中的一列

问题描述

我知道这里的语法很离谱,但基本上是试图确定这个功能。最后,我想比较这两列中的年份。如果第一列中的年份与第二列中的年份匹配,那么我想验证一列的年份小于 2006 年,如果年份小于 2006 年,我想将该年份的行更改为 2006 年。功能上下面的 if else 语句是我想要的,只需要确定 pandas 中的语法。

数据: 在此处输入图像描述

for index,row in product_df.iterrows():
    if row(product_df['inputs/ConstructionYearRoof']) = row(product_df['inputs/ConstructionYear']) and row(product_df['inputs/ConstructionYearRoof']) < 2006:
        row(product_df['inputs/ConstructionYearRoof']) = 2006
    else:
        pass

标签: pythonpandasdataframesyntaxdata-science

解决方案


你不会用.iterrows(). 习惯使用 pandas 的最大技巧之一是考虑选择行然后执行列操作

你会用布尔掩码做这种事情:

# First select the rows you want by creating a boolean mask for each condition
mask1 = product_df['inputs/ConstructionYearRoof'] == product_df['inputs/ConstructionYear']
mask2 = product_df["inputs/ConstructionYearRoof"] < 2006
mask3 = mask1 & mask2

# Then use the mask to select only those rows at the column you want
# You are now setting the desired value on the whole column but only 
# on the selected rows.
product_df.loc[mask3, "inputs/ConstructionYearRoof"] = 2006

推荐阅读