Python中使用asammdf从Pandas DataFrame生成MDF文件时时间索引异常问题求助
I've run into this exact issue before—here's what's happening and how to fix it quickly:
The Root Cause
When you call mdf_obj.append(df) directly, asammdf defaults to treating your DataFrame's integer index as timestamp values, with each index increment representing 1 second. Since your actual sample interval is 0.015 seconds, this means every data point gets scaled to 1 second in the MDF file—hence the 66.6x duration inflation you're seeing.
Solution 1: Use the time_column Parameter (Recommended)
The MDF.append() method has a time_column argument that lets you specify which DataFrame column to use as the time axis (in seconds). You just need to convert your datetime TIME column to a Unix timestamp (float, in seconds) first:
import pandas as pd import numpy as np from asammdf import MDF, Signal data = { "TIME": pd.date_range(start='2024-01-01', periods=200, freq='15ms'), "FLOAT_SIGNAL": np.random.rand(200), } df = pd.DataFrame(data) # Convert datetime column to Unix timestamps (in seconds, with millisecond precision) df["TIME_SEC"] = df["TIME"].apply(lambda dt: dt.timestamp()) mdf_obj = MDF() # Tell asammdf to use our TIME_SEC column for timestamps mdf_obj.append(df, time_column="TIME_SEC") # Use raw string for Windows path to avoid escape issues mdf_obj.save(r"C:\Users\user\Desktop\output.mdf", compression=2)
Solution 2: Manually Create Signal Objects
If you need more control (or if your asammdf version doesn't support time_column), you can build Signal instances explicitly and attach the correct timestamp array:
import pandas as pd import numpy as np from asammdf import MDF, Signal data = { "TIME": pd.date_range(start='2024-01-01', periods=200, freq='15ms'), "FLOAT_SIGNAL": np.random.rand(200), } df = pd.DataFrame(data) # Convert datetime column to a numpy array of timestamps (seconds) timestamps = df["TIME"].apply(lambda dt: dt.timestamp()).to_numpy() # Create the signal with the correct time axis float_signal = Signal( samples=df["FLOAT_SIGNAL"].to_numpy(), timestamps=timestamps, name="FLOAT_SIGNAL", unit="", # Add your actual unit if applicable comment="Random floating-point signal" ) mdf_obj = MDF() mdf_obj.append(float_signal) mdf_obj.save(r"C:\Users\user\Desktop\output.mdf", compression=2)
Key Notes
asammdfexpects timestamps in seconds (floats are supported for sub-second precision, which is perfect for your 15ms intervals).- The datetime-to-timestamp conversion preserves millisecond data (e.g.,
2024-01-01 00:00:00.015becomes1704067200.015), so the MDF file will calculate the correct total duration based on the actual time between samples. - Always use raw strings (
r"path") or escaped backslashes ("C:\\Users\\...") for Windows file paths to avoid parsing errors.
内容的提问来源于stack exchange,提问作者jB777

