如何基于未知格式EventTime列与Price列绘制CSV数据图表?
Got it, let's tackle this step by step. First, let's decode that tricky EventTime format, then we'll convert it into a usable datetime object, and finally plot your Price data over time.
Step 1: Understand the EventTime Format
Looking at your example 20180402-070000.164-0400, here's what each part breaks down to:
20180402:YYYYMMDD(Year: 2018, Month: 04, Day: 02)070000.164:HHMMSS.sss(Hour: 07, Minute: 00, Second: 00, Millisecond: 164)-0400: UTC timezone offset (UTC minus 4 hours)
The full format string we'll use to parse this is %Y%m%d-%H%M%S.%f-%z — it perfectly matches each segment of the timestamp.
Step 2: Parse the CSV and Convert EventTime
We'll use Python's pandas (the standard tool for this kind of data work) to read the CSV and convert the EventTime column into proper datetime values. Here's the code:
import pandas as pd import matplotlib.pyplot as plt # Read the CSV (skip the comment line starting with #) df = pd.read_csv('your_data.csv', comment='#') # Convert EventTime to datetime type using our format string df['EventTime'] = pd.to_datetime(df['EventTime'], format='%Y%m%d-%H%M%S.%f-%z') # Quick check to confirm the conversion worked print(df[['EventTime', 'Price']].head())
Step 3: Plot the Price vs. Time
Now that we have properly formatted datetime values, plotting is straightforward with matplotlib:
# Set up the plot size plt.figure(figsize=(12, 6)) # Plot Price against EventTime with small markers for clarity plt.plot(df['EventTime'], df['Price'], marker='o', linestyle='-', markersize=3, color='steelblue') # Add labels and a title to make the plot readable plt.xlabel('Event Time') plt.ylabel('Price') plt.title('AKER Price Over Time') # Rotate x-axis labels to prevent overlap plt.xticks(rotation=45) # Adjust layout so labels don't get cut off plt.tight_layout() # Display the plot plt.show()
Quick Edge Case Tips
- If timezone handling causes issues, you can convert all timestamps to UTC (or your local timezone) with
df['EventTime'] = df['EventTime'].tz_convert('UTC') - If your CSV has missing values, clean the data first with
df.dropna(subset=['EventTime', 'Price'])to avoid plotting errors
内容的提问来源于stack exchange,提问作者Jeremie

