import pandas as pd import wfdb from sklearn.model_selection import train_test_split import os import csv import numpy as np folder_path = r'C:\Users\bubble\PycharmProjects\pythonProject\csv' file_list = os.listdir(folder_path) for file_name in file_list: subfolder_path = os.path.join(folder_path, file_name) if os.path.isdir(subfolder_path): # 进入子文件夹 os.chdir(subfolder_path) # 获取子文件夹中的.csv文件列表 csv_list = [f for f in os.listdir(subfolder_path) if f.endswith('.csv')] # 读取.csv文件 dfs = [] for csv_file in csv_list: df = pd.read_csv(csv_file, header=None) dfs.append(df) csv_folder_name = os.path.basename(subfolder_path) last_char = csv_folder_name[-1] wave = [] form = [] records = dfs for record in records: wave = record form = last_char #print(wave) #print(form) W = [wave, form] T = [W] T = np.array(T) #划分特征与标签 X =T[:, :-1] y =T[:, -1] print(X) print(y)这段代码有错误吗?该怎么改
时间: 2024-01-22 12:03:51 浏览: 139
pd_split_train_test.rar_pandas_pandas对数据分类_pd.split_split_数据分类
这段代码有几个错误:
1. 在读取 CSV 文件时,需要使用完整路径而不是只使用文件名。可以使用 `os.path.join(subfolder_path, csv_file)` 来获取完整路径。
2. 在创建 `T` 数组时,应该先创建一个空的数组,然后使用 `np.append()` 函数将每个样本添加到数组中。可以使用以下代码来创建 `T` 数组:
```
T = np.empty((0, 2))
for record in records:
wave = record
form = last_char
W = [wave, form]
T = np.append(T, [W], axis=0)
```
3. 在划分特征和标签时,应该使用 `X = T[:, :-1]` 和 `y = T[:, -1]` 的方式来划分。
修改后的代码如下:
```
import pandas as pd
import wfdb
from sklearn.model_selection import train_test_split
import os
import csv
import numpy as np
folder_path = r'C:\Users\bubble\PycharmProjects\pythonProject\csv'
file_list = os.listdir(folder_path)
for file_name in file_list:
subfolder_path = os.path.join(folder_path, file_name)
if os.path.isdir(subfolder_path):
# 进入子文件夹
os.chdir(subfolder_path)
# 获取子文件夹中的.csv文件列表
csv_list = [f for f in os.listdir(subfolder_path) if f.endswith('.csv')]
# 读取.csv文件
dfs = []
for csv_file in csv_list:
csv_path = os.path.join(subfolder_path, csv_file)
df = pd.read_csv(csv_path, header=None)
dfs.append(df)
csv_folder_name = os.path.basename(subfolder_path)
last_char = csv_folder_name[-1]
wave = []
form = []
records = dfs
T = np.empty((0, 2))
for record in records:
wave = record
form = last_char
W = [wave, form]
T = np.append(T, [W], axis=0)
X = T[:, :-1]
y = T[:, -1]
print(X)
print(y)
```
阅读全文