python - 遍历行并比较两列并应用逻辑并更改熊猫中的一列
问题描述
我知道这里的语法很离谱,但基本上是试图确定这个功能。最后,我想比较这两列中的年份。如果第一列中的年份与第二列中的年份匹配,那么我想验证一列的年份小于 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
解决方案
你不会用.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
推荐阅读
- javascript - 指定从函数返回的键时,可选对象道具无法读取
- mysql - SQL treats similar to English and Swedish characters
- ios - Swift index of array of Dictionary
- reactjs - how to toggle a class on a div in react project for opening a mobile menu in mobile
- php - 我在哪里存储我的令牌服务器端?
- r - 矩阵的一行及其在R中的同一矩阵中反转
- c# - 带有 api 版本控制的 Autofac 和 swagger 给出异常
- session - Tensorflow Graph,用于交叉验证的会话管理
- reactjs - react-router 切换和404页面
- ios - 节点快速会话未在 iPhone IOS 中持续存在