试图有条件地在数据帧中的列中运行循环,但没有得到我想要的结果



我的df中有一列的年份值为INT,但有些值为0。我试图运行for循环来保留0值,但用calc(即列中的2020-值(替换年份值。到目前为止,我有:

for (i, item) in enumerate(housing['YrRenovated']):
if item > 0:
housing['YrRenovated'][i] = 2020 - item,
else: 
housing['YrRenovated'] = 0,


它运行,但当它应该像45 时,列中的最大值是0

尝试使用apply和lambda函数。

housing['YrRenovated'] = housing['YrRenovated'].apply(lambda item: 2020-item if item > 0 else 0)

尝试使用以下循环:

for index, row in housing.iterrows():
if row['YrRenovated'] != 0:
newValue = 2020 - row['YrRenovated']
housing.at[index, 'YrRenovated'] = newValue

相关内容

最新更新