如何在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:
Method 1: Vectorized Processing (Efficient & Recommended)
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.
Method 2: Loop Processing (For Reference Only, Not Recommended)
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

