如何在Pandas中合并日期与时间列生成标准时间戳?
Hey there! No worries—combining separate Date and Time columns into a standard timestamp like 2015-07-04 00:00:00 is totally doable with Pandas, and it's simpler than you might think. Let's break this down with your specific dataset.
Step 1: Understand Your Data Format
First, let's recap your data structure:
Dateuses theYYYY.MM.DDformat (e.g.,2000.12.22)Timeuses theHH:MMformat (e.g.,12:00)- Both columns are
pandas.core.series.Seriesobjects
Step 2: Combine and Convert to Timestamp
We'll use Pandas' pd.to_datetime() function, which excels at parsing date-time strings into proper datetime objects. Here's how to implement this:
First, replicate your sample data (to match your scenario):
import pandas as pd # Your dataset as provided data = { 'Date': ['2000.12.22', '2000.12.22', '2000.12.22', '2000.12.23', '2000.12.25'], 'Time': ['12:00', '16:00', '20:00', '00:01', '00:00'], 'Open': [0.91810, 0.92260, 0.92300, 0.92410, 0.92300], 'High': [0.92620, 0.92520, 0.92580, 0.92450, 0.92460], 'Low': [0.91650, 0.92220, 0.92260, 0.92270, 0.92300], 'Close': [0.92320, 0.92310, 0.92420, 0.92320, 0.92420], 'Vol': [2244, 1688, 955, 168, 260] } df = pd.DataFrame(data)
Option 1: Auto-detect the format
Pandas is usually smart enough to recognize the date-time structure on its own. Just concatenate the Date and Time columns with a space, then pass the result to pd.to_datetime():
# Create a new 'Datetime' column with the merged timestamp df['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
Option 2: Specify the format (for maximum reliability)
If you want to eliminate any auto-detection ambiguity, explicitly define the format using strftime codes:
# %Y = 4-digit year, %m = 2-digit month, %d = 2-digit day # %H = 24-hour format hour, %M = minute df['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'], format='%Y.%m.%d %H:%M')
Step 3: Verify the Result
Check the new column to confirm it's in your desired format:
print(df['Datetime'])
You'll get output like this:
0 2000-12-22 12:00:00 1 2000-12-22 16:00:00 2 2000-12-22 20:00:00 3 2000-12-23 00:01:00 4 2000-12-25 00:00:00 Name: Datetime, dtype: datetime64[ns]
Optional: Remove Original Columns
If you no longer need the separate Date and Time columns, drop them to clean up your DataFrame:
df = df.drop(['Date', 'Time'], axis=1)
Why This Works
The pd.to_datetime() function converts string inputs into Pandas' datetime64[ns] type, which is optimized for time-series tasks like filtering by date, resampling data, or calculating time differences.
Hope this solves your problem! Feel free to ask if you need help with any follow-up steps.
内容的提问来源于stack exchange,提问作者Flying pig

