You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中对year列超2018的值执行减100的条件替换?

Fixing Conditional Year Replacement in Pandas DataFrame

Hey there! Let's sort out that incorrect year value issue you're facing. Those 2067-style years (which should be 1967) are easy to fix with a few Pandas tricks. Here are three reliable methods to do the conditional replacement:

Method 1: Use loc for Explicit Indexing

This is the most straightforward and Pandas-idiomatic way to target specific rows:

# Target rows where year > 2018, subtract 100 from the 'year' column
new_df.loc[new_df['year'] > 2018, 'year'] -= 100

The loc operator lets you precisely select the subset of data that needs updating—no risk of modifying unintended rows.

Method 2: Use numpy.where for Concise One-Liner

If you prefer a more compact approach, numpy.where works perfectly here:

import numpy as np

# Syntax: np.where(condition, value_if_true, value_if_false)
new_df['year'] = np.where(new_df['year'] > 2018, new_df['year'] - 100, new_df['year'])

This replaces values that meet the condition with year - 100, and leaves all other values as-is in a single line.

Method 3: Use apply for Custom Logic (Good for More Complex Cases)

While not as performant as the first two for large datasets, apply is flexible if you ever need to expand the logic later:

# Apply a lambda function to each value in the 'year' column
new_df['year'] = new_df['year'].apply(lambda x: x - 100 if x > 2018 else x)

The lambda function checks each year individually and adjusts it only if it's over 2018.

Verify the Fix

After applying any of these methods, you should double-check that the issue is resolved:

# Check the updated statistics
print(new_df['year'].describe())

# Confirm no values are still above 2018
print(new_df[new_df['year'] > 2018])  # This should return an empty DataFrame

内容的提问来源于stack exchange,提问作者EdwardC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:14:11