如何使用Python的asammdf库从Pandas时序DataFrame向MDF文件添加字符串信号?
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:
- Convert the string column to a fixed-length numpy string array (use
Sfor ASCII,Ufor Unicode, followed by the maximum length of your strings). - When creating the
Signalfor the string column, explicitly set thedatatypeparameter 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 setdatatype='unicode'when creating the Signal. - Alternative Conversion: You can also use
np.char.encode(col_values, encoding='ascii')instead ofastype('S1')to achieve the same fixed-length byte array result.
内容的提问来源于stack exchange,提问作者jB777

