特征文件根据不同的列记录到不同csv中
时间: 2024-04-14 20:30:53 浏览: 77
CSV文件读取类C++源代码
非常抱歉之前的回答还存在问题。根据你的需求,以下是修正后的代码,可以将特征文件根据不同的列记录到不同的 CSV 文件中:
```python
import os
import csv
import struct
import numpy as np
import pywt
def calculate_features(data):
features = []
for i in range(3):
features.append(np.mean(data[:, i]))
features.append(np.var(data[:, i]))
features.append(np.sqrt(np.mean(np.square(data[:, i]))))
for i in range(1, 17):
coeffs = pywt.wavedec(data[:, i % 3], "db4", level=i)
energy = np.sum(np.square(coeffs))
features.append(energy)
return features
# 创建保存CSV文件的文件夹
csv_folder = "csv"
if not os.path.exists(csv_folder):
os.makedirs(csv_folder)
# 遍历文件夹及子文件夹中的二进制bin文件
for root, dirs, files in os.walk(".", topdown=True):
for filename in files:
if filename.endswith(".bin"):
# 构建CSV文件路径
bin_filepath = os.path.join(root, filename)
csv_dirpath = os.path.join(csv_folder, os.path.splitext(filename)[0])
if not os.path.exists(csv_dirpath):
os.makedirs(csv_dirpath)
# 打开二进制bin文件并读取数据
with open(bin_filepath, "rb") as bin_file:
bin_data = bin_file.read()
# 解析二进制数据并转换为浮点数
floats = []
for i in range(0, len(bin_data), 8):
float_value = struct.unpack("d", bin_data[i:i + 8])[0]
floats.append(float_value)
# 将数据按顺序分别放到1、2、3列并保存到CSV文件
data = np.array(floats).reshape(-1, 3)
for i in range(3):
csv_filename = f"{os.path.splitext(filename)[0]}_特征文件{i + 1}.csv"
csv_filepath = os.path.join(csv_dirpath, csv_filename)
with open(csv_filepath, "w", newline="") as csv_file:
writer = csv.writer(csv_file)
header = [f"特征{i + 1}"]
writer.writerow(header)
writer.writerows(data[:, i].reshape(-1, 1))
# 计算特征并保存到特征文件
feature_filename = f"{os.path.splitext(filename)[0]}_特征文件.csv"
feature_filepath = os.path.join(csv_folder, feature_filename)
with open(feature_filepath, "w", newline="") as feature_file:
writer = csv.writer(feature_file)
header = []
for i in range(1, 17):
header.append(f"均值{i}")
header.append(f"方差{i}")
header.append(f"RMS{i}")
header.append(f"能量{i}")
writer.writerow(header)
# 按窗口大小计算特征
window_size = 100
step_size = 50
num_windows = (len(data) - window_size) // step_size + 1
for i in range(num_windows):
start_idx = i * step_size
end_idx = start_idx + window_size
window_data = data[start_idx:end_idx]
features = calculate_features(window_data)
writer.writerow(features)
```
这次的代码会按照你的要求,将特征文件根据不同的列记录到不同的 CSV 文件中。特征文件的命名方式为`原始文件名_特征文件1.csv`、`原始文件名_特征文件2.csv`和`原始文件名_特征文件3.csv`。非常抱歉之前的错误带来的困扰,希望这次的回答能够满足你的需求。
阅读全文