如何将Pandas中独立的日期、时间列转为to_datetime并设为索引
Hey there, here's the straightforward way to turn your int64 Date and Time columns into a properly formatted datetime index for your DataFrame:
Step 1: Combine and Convert to Datetime
First, we'll convert both columns to strings, concatenate them into a single datetime string, then use pd.to_datetime() with an explicit format to parse it correctly. This approach is faster and more reliable than letting pandas guess the format automatically.
import pandas as pd # Sample data matching your provided structure data = { 'Date': [20180316, 20180316, 20180316, 20180316], 'Time': [1935, 1937, 1939, 1946], 'Open': [178.15, 178.04, 178.06, 178.01], 'High': [178.24, 178.04, 178.06, 178.01], 'Low': [178.15, 178.04, 178.06, 178.01], 'Close': [178.24, 178.04, 178.06, 178.01], 'Volume': [5000.0, 80.0, 300.0, 50.0] } df = pd.DataFrame(data) # Convert Date/Time to strings, concatenate, then parse to datetime df['datetime'] = pd.to_datetime( df['Date'].astype(str) + df['Time'].astype(str), format='%Y%m%d%H%M' # Matches the "YYYYMMDDHHMM" string format )
Step 2: Set as Index and Clean Up
Next, set the new datetime column as the DataFrame index, then drop the original Date and Time columns since they're no longer needed:
# Assign datetime as index and remove old columns df = df.set_index('datetime').drop(['Date', 'Time'], axis=1)
Edge Case: Time Values with Less Than 4 Digits
If your Time column has values like 930 (instead of 0930 for 9:30 AM), use str.zfill(4) to pad leading zeros before concatenation:
df['datetime'] = pd.to_datetime( df['Date'].astype(str) + df['Time'].astype(str).str.zfill(4), format='%Y%m%d%H%M' )
Verify the Result
You can confirm the index type with print(df.index) — it should return a DatetimeIndex with dtype datetime64[ns], exactly what you need.
内容的提问来源于stack exchange,提问作者sslack88

