wavelet_df.loc[i] = energy_values发生报错:发生异常: ValueError cannot set a row with mismatched columns File "/Users/dingfengyan/工作/项目开发/哈理工/批量导出功能/binzcsv+feature.py", line 150, in <module> wavelet_df.loc[i] = energy_values ~~~~~~~~~~~~~~^^^ ValueError: cannot set a row with mismatched columns
时间: 2023-07-21 09:09:18 浏览: 169
这个报错是因为在设置`wavelet_df.loc[i]`的时候,`energy_values`的长度与DataFrame的列数不匹配。可能是因为`energy_values`的长度与窗口数量不一致导致的。请确保`energy_values`的长度与窗口数量相同,并且DataFrame的列数已经正确初始化。你可以尝试以下修改:
```python
import os
import struct
import pandas as pd
import numpy as np
import pywt
# 定义窗口大小和步长
window_size = 100
step_size = 50
# 获取当前目录路径
current_dir = os.getcwd()
# 创建原始csv目录
raw_csv_dir = os.path.join(current_dir, '原始csv')
if not os.path.exists(raw_csv_dir):
os.makedirs(raw_csv_dir)
# 创建时频域特征csv目录
feature_csv_dir = os.path.join(current_dir, '时频域特征csv目录')
if not os.path.exists(feature_csv_dir):
os.makedirs(feature_csv_dir)
def read_bin_file(file_path):
# 打开bin文件并读取数据
with open(file_path, 'rb') as f:
data = f.read()
return data
def convert_to_float(data):
# 将每8个字节转为浮点数
floats = []
for i in range(0, len(data), 8):
float_val = struct.unpack('f', data[i:i+4])[0]
floats.append(float_val)
return floats
def calculate_statistics(window_data):
# 计算统计指标和时频域参数
mean_value = np.mean(window_data)
var_value = np.var(window_data)
rms_value = np.sqrt(np.mean(np.square(window_data)))
skewness = pd.Series(window_data).skew()
kurtosis = pd.Series(window_data).kurt()
crest_factor = np.max(np.abs(window_data)) / rms_value
peak_factor = np.max(window_data) / rms_value
impulse_factor = np.max(np.abs(window_data)) / np.mean(np.abs(window_data))
margin_factor = np.max(np.abs(window_data)) / np.std(window_data)
return mean_value, var_value, rms_value, skewness, kurtosis, crest_factor, peak_factor, impulse_factor, margin_factor
def calculate_wavelet_energy(window_data):
# 计算小波能量值
coeffs = pywt.wavedec(window_data, 'db4', level=16)
energy_values = [np.sum(np.square(coeff)) for coeff in coeffs]
return energy_values
# 遍历当前目录及子目录下的所有bin文件
for root, dirs, files in os.walk(current_dir):
for file in files:
if file.endswith('.bin'):
bin_file_path = os.path.join(root, file)
# 读取bin文件
bin_data = read_bin_file(bin_file_path)
# 转换为浮点数
floats = convert_to_float(bin_data)
# 创建DataFrame用于存储数据
df = pd.DataFrame(columns=['1', '2', '3'])
# 将数据按顺序写入DataFrame的列中
df['1'] = floats[::3]
df['2'] = floats[1::3]
df['3'] = floats[2::3]
# 将DataFrame保存为原始csv文件
csv_file_path = os.path.join(raw_csv_dir, f'{file}.csv')
df.to_csv(csv_file_path, index=False)
# 创建新的DataFrame用于存储时频域特征数据
feature_df = pd.DataFrame(columns=[f'{file}_mean', f'{file}_var', f'{file}_rms',
f'{file}_skew', f'{file}_kurtosis', f'{file}_crest',
f'{file}_peak', f'{file}_impulse', f'{file}_margin'])
# 创建新的DataFrame用于存储小波特征数据
wavelet_df = pd.DataFrame(columns=[f'{file}_energy_{i}' for i in range(1, 17)])
# 对每列进行窗口切片,并计算统计指标和时频域参数
for col in df.columns:
col_data = df[col]
num_windows = (len(col_data) - window_size) // step_size + 1
for i in range(num_windows):
window_data = col_data[i*step_size : i*step_size + window_size]
# 计算统计指标和时频域参数
result = calculate_statistics(window_data)
# 将结果添加到时频域特征DataFrame
feature_df.loc[i] = result
# 计算小波能量值
energy_values = calculate_wavelet_energy(window_data)
# 将结果添加到小波特征DataFrame
wavelet_df.loc[i, [f'{file}_energy_{j+1}' for j in range(len(energy_values))]] = energy_values
# 将时频域特征数据保存为新的csv文件
feature_csv_file_path = os.path.join(feature_csv_dir, f'{file}.csv')
feature_df.to_csv(feature_csv_file_path, index=False)
# 将小波特征数据保存为新的csv文件
wavelet_csv_file_path = os.path.join(feature_csv_dir, f'{file}_wavelet.csv')
wavelet_df.to_csv(wavelet_csv_file_path, index=False)
print("时频域特征csv文件和小波特征csv文件生成完成")
```
在上述代码中,我修改了计算小波能量值的部分,使用`wavelet_df.loc[i, [f'{file}_energy_{j+1}' for j in range(len(energy_values))]]`来设置每行的值。这样可以确保`energy_values`的长度与DataFrame的列数匹配。请注意在保存小波特征数据的csv文件时,我将文件名命名为`{file}_wavelet.csv`,以区分时频域特征数据的csv文件。
阅读全文