You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python的asammdf库从Pandas时序DataFrame向MDF文件添加字符串信号?

Adding String Channels to MDF Files with asammdf from Pandas DataFrames

I see exactly what's going on here—when dealing with string columns in a Pandas DataFrame, asammdf can't automatically infer the correct signal type from Pandas' default object dtype array. Let's fix this with a straightforward adjustment.

Why the Error Occurs

Pandas stores string data in columns with dtype=object, which is a generic container for any Python object. asammdf's Signal class doesn't recognize this as a valid MDF signal type, hence the "Unknown type" error. MDF requires string signals to be stored as fixed-length byte arrays (for ASCII) or Unicode arrays, so we need to explicitly convert and define the type ourselves.

Solution: Explicitly Convert String Data and Specify Datatype

Here's how to modify your code to handle the string channel properly:

  1. Convert the string column to a fixed-length numpy string array (use S for ASCII, U for Unicode, followed by the maximum length of your strings).
  2. When creating the Signal for the string column, explicitly set the datatype parameter to match the converted array type.

Corrected Code

import pandas as pd
import numpy as np
from asammdf import MDF, Signal

data = {
    "GLOBAL_TIME": [1, 2, 3, 4, 5],
    "INT_SIGNAL": [10, 20, 30, 40, 50],
    "FLOAT_SIGNAL": [1.1, 2.2, 3.3, 4.4, 5.5],
    "STRING_SIGNAL": ["a", "a", "a", "a", "a"],
}
df_test2 = pd.DataFrame(data)

new_mdf_from_df = MDF()
for column in df_test2.columns:
    col_values = df_test2[column].values
    
    # Handle string column with specific processing
    if column == "STRING_SIGNAL":
        # Convert to fixed-length ASCII array (S1 = supports 1 character; adjust length as needed)
        # Use 'U1' and datatype='unicode' if you need non-ASCII character support
        formatted_strings = col_values.astype('S1')
        sig = Signal(
            samples=formatted_strings,
            timestamps=df_test2.index.values,
            name=column,
            datatype='ascii'  # Matches the ASCII array type we created
        )
    else:
        sig = Signal(
            samples=col_values,
            timestamps=df_test2.index.values,
            name=column
        )
    
    try:
        new_mdf_from_df.append(sig)
        print(f"Successfully added signal: {column}")
    except Exception as e:
        print(f"Error adding signal '{column}': {e}")

# Optional: Save the completed MDF file
new_mdf_from_df.save("string_signal_test.mf4", overwrite=True)

Key Notes

  • Fixed String Length: Ensure the length in astype('S1') matches or exceeds the longest string in your column. For example, use 'S5' if your strings are up to 5 characters long.
  • Unicode Support: If you need to handle non-ASCII characters, use 'U' prefix (e.g., 'U5') and set datatype='unicode' when creating the Signal.
  • Alternative Conversion: You can also use np.char.encode(col_values, encoding='ascii') instead of astype('S1') to achieve the same fixed-length byte array result.

内容的提问来源于stack exchange,提问作者jB777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 06:39:14