如何在Python的NumPy数组首行添加传感器数据表头?
Adding Header Row to Your IMU Data CSV
Got it, let's sort out adding that header row to your IMU CSV file properly. The main issue with your current code is that it just appends data every time—we need to check if the file is brand new, and if so, write the header first before adding the sensor readings.
Here's the adjusted code with header support:
import numpy as np import time import os # Needed to check if the CSV file already exists # Define your header to match the order of your sensor data # Adjust these names if your sensor outputs have different dimensions/names header = [ "Timestamp", "Acceleration(g)_x", "Acceleration(g)_y", "Acceleration(g)_z", "Acceleration(angle)_x", "Acceleration(angle)_y", "Acceleration(angle)_z", "Gyroscope_raw_x", "Gyroscope_raw_y", "Gyroscope_raw_z", "Magnetometer_raw_x", "Magnetometer_raw_y", "Magnetometer_raw_z" ] # Collect your IMU data in order timestamp = time.time() * 1000 # Millisecond timestamp imu_readings = [] imu_readings.extend(lsm6ds33.get_accelerometer_g_forces()) imu_readings.extend(lsm6ds33.get_accelerometer_angles()) imu_readings.extend(lsm6ds33.get_gyroscope_raw()) imu_readings.extend(lis3mdl.get_magnetometer_raw()) # Prepend timestamp to the readings to match your original logic timestamped_row = np.array([timestamp] + imu_readings, dtype=np.float32) csv_filename = "IMU_Readings_muh.csv" with open(csv_filename, "ab") as f: # Write header only if the file doesn't exist yet if not os.path.exists(csv_filename): np.savetxt(f, [header], fmt="%s", delimiter=",") # Write the actual sensor data row np.savetxt(f, np.expand_dims(timestamped_row, axis=0), fmt="%4.8f", delimiter=",")
Key changes explained:
- Added
osmodule import to check if the CSV file already exists—this lets us only write the header once, on the first run. - Defined a clear
headerlist that matches the exact order of your data: timestamp first, followed by each sensor's axes in the order you collect them. - Switched to using a Python list to collect readings first (instead of multiple
np.appendcalls) — this is more efficient because numpy arrays are immutable, so each append creates a new array. - Used
fmt="%s"for the header to save the string labels correctly, while keeping your original%4.8fformat for the numerical sensor data.
Quick note:
Double-check that the number of header entries matches the number of data columns your code produces. For example, if get_accelerometer_g_forces() returns 2 values instead of 3, adjust the header to remove the extra axis entry.
内容的提问来源于stack exchange,提问作者rajy
相关产品推荐
相关产品推荐

