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

如何在Pandas DataFrame中就地剥离字符串,转为带时区Timestamp

Let's fix your issues step by step:

First, the KeyError: 1 happens because you're trying to access a column using positional index GC[1], but your DataFrame's timestamp column is named date—you should use GC['date'] instead. Additionally, there are a couple of flaws in your loop logic: Python strings are immutable, so ts.replace() won't modify the original string in-place; plus, there's no ts.to_datetime() method—you need to use pd.to_datetime() to process the string.

Here are two correct ways to handle this, with the first being the recommended pandas best practice:

Batch-process the entire date column directly—this is far faster than looping:

# Remove the unwanted suffix from all timestamps in the column
GC['date'] = GC['date'].str.replace(' (heure d%u2019été d%u2019Europe centrale)', '', regex=False)
# Convert cleaned strings to timezone-aware Timestamps
GC['date'] = pd.to_datetime(GC['date'])

The str.replace method is pandas' built-in vectorized string tool, which automatically iterates over every element in the column. Setting regex=False ensures the suffix is treated as a plain string, avoiding issues with regex special characters.

If you must use a loop, you'll need to correctly iterate over column elements and assign values back to the original DataFrame:

for idx, raw_ts in GC['date'].items():
    # Clean the timestamp string
    cleaned_ts = raw_ts.replace(' (heure d%u2019été d%u2019Europe centrale)', '')
    # Assign the converted timestamp back to the DataFrame
    GC.loc[idx, 'date'] = pd.to_datetime(cleaned_ts)

After processing, check the GC['date'] column—all elements will be timezone-aware Timestamps, matching the result you tested individually.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:15:41