Пытаемся сопоставить данные из двух листов с определенным соглашением об именах. Код может идентифицировать файлы Excel, но продолжает возвращать: Study Test/Purticipant 1/text_export_P1S1T2.xlsx: индекс рабочего листа 0 недействителен, найдено 0 рабочих листов.
Ниже приведен код что я использовал:
import pandas as pd
import numpy as np
import os
from scipy.interpolate import interp1d
from datetime import datetime
import warnings
# Suppress specific warnings
warnings.filterwarnings("ignore", category=UserWarning, module='openpyxl')
# Directory containing the participant folders
home_dir = os.getcwd()
# Standardized increment and stance phase conversion
X2 = np.linspace(0, 100, 101) # Standardized to 101 points for interpolation
# Prepare to collect results in a single DataFrame
consolidated_results = []
def process_file(filepath):
# Load Excel file
try:
df = pd.read_excel(filepath, skiprows=9, engine='openpyxl')
except Exception as e:
print(f"Error reading {filepath}: {e}")
return None # Return None if there's an error
# Check if expected columns are present
if df.shape[1] < 51: # Ensure there are at least 51 columns
print(f"Expected columns not found in {filepath}. Found columns: {df.shape[1]}")
return None
# Extract relevant columns
T = df.iloc[:, 1].dropna().values # Time (s)
COP1x = df.iloc[:, 49].dropna().values # Filtered COP x (mm)
COP1y = df.iloc[:, 50].dropna().values # Filtered COP y (mm)
# Normalize time to 0-100 for Stance Phase
if len(T) < 2: # Need at least two points to calculate min and max
print(f"Not enough time points in {filepath}. Found points: {len(T)}")
return None
Tmin, Tmax = np.min(T), np.max(T)
SP = (T - Tmin) * (100 / (Tmax - Tmin))
# Interpolate data
interp_func = lambda y: interp1d(SP, y, kind='cubic', fill_value="extrapolate")(X2)
return {
'Stance Phase (%)': X2,
'COP1x (mm)': interp_func(COP1x),
'COP1y (mm)': interp_func(COP1y)
}
participants = [
1, 3, 4, 6, 7, 8, 9, 10, 11, 12
]
# Iterate through each participant folder and process files
for participant in participants:
participant_folder = f"Participant {participant}"
participant_path = os.path.join(home_dir, participant_folder)
for file in os.listdir(participant_path):
if file.startswith("text_export") and file.endswith(".xlsx"):
# Process file
filepath = os.path.join(participant_path, file)
processed_data = process_file(filepath)
if processed_data is not None: # Only append if processing was successful
# Append data to consolidated results
for i in range(len(processed_data['COP1x (mm)'])):
consolidated_results.append({
'COP1x (mm)': processed_data['COP1x (mm)'][i],
'COP1y (mm)': processed_data['COP1y (mm)'][i]
})
# Convert the results to a DataFrame and save to an Excel file
if consolidated_results: # Only save if there's data to save
consolidated_df = pd.DataFrame(consolidated_results)
output_filename = f"Consolidated_Results_{datetime.now().strftime('%y%m%d')}.xlsx"
consolidated_df.to_excel(output_filename, index=False)
print(f"Consolidated data saved to {output_filename}")
else:
print("No data to save.")
Я пытался создать тестовый файл Excel, чтобы проверить, не связана ли это с моей пандой, но мне удалось создать файл Excel.
Пытаемся сопоставить данные из двух листов с определенным соглашением об именах. Код может идентифицировать файлы Excel, но продолжает возвращать: Study Test/Purticipant 1/text_export_P1S1T2.xlsx: индекс рабочего листа 0 недействителен, найдено 0 рабочих листов. Ниже приведен код что я использовал: [code]import pandas as pd import numpy as np import os from scipy.interpolate import interp1d from datetime import datetime import warnings
# Suppress specific warnings warnings.filterwarnings("ignore", category=UserWarning, module='openpyxl')
# Directory containing the participant folders home_dir = os.getcwd()
# Standardized increment and stance phase conversion X2 = np.linspace(0, 100, 101) # Standardized to 101 points for interpolation
# Prepare to collect results in a single DataFrame consolidated_results = []
def process_file(filepath): # Load Excel file try: df = pd.read_excel(filepath, skiprows=9, engine='openpyxl') except Exception as e: print(f"Error reading {filepath}: {e}") return None # Return None if there's an error
# Check if expected columns are present if df.shape[1] < 51: # Ensure there are at least 51 columns print(f"Expected columns not found in {filepath}. Found columns: {df.shape[1]}") return None
# Extract relevant columns T = df.iloc[:, 1].dropna().values # Time (s) COP1x = df.iloc[:, 49].dropna().values # Filtered COP x (mm) COP1y = df.iloc[:, 50].dropna().values # Filtered COP y (mm)
# Normalize time to 0-100 for Stance Phase if len(T) < 2: # Need at least two points to calculate min and max print(f"Not enough time points in {filepath}. Found points: {len(T)}") return None
# Iterate through each participant folder and process files for participant in participants: participant_folder = f"Participant {participant}" participant_path = os.path.join(home_dir, participant_folder)
for file in os.listdir(participant_path): if file.startswith("text_export") and file.endswith(".xlsx"): # Process file filepath = os.path.join(participant_path, file) processed_data = process_file(filepath)
if processed_data is not None: # Only append if processing was successful # Append data to consolidated results for i in range(len(processed_data['COP1x (mm)'])): consolidated_results.append({ 'COP1x (mm)': processed_data['COP1x (mm)'][i], 'COP1y (mm)': processed_data['COP1y (mm)'][i] })
# Convert the results to a DataFrame and save to an Excel file if consolidated_results: # Only save if there's data to save consolidated_df = pd.DataFrame(consolidated_results) output_filename = f"Consolidated_Results_{datetime.now().strftime('%y%m%d')}.xlsx" consolidated_df.to_excel(output_filename, index=False) print(f"Consolidated data saved to {output_filename}") else: print("No data to save.") [/code] Я пытался создать тестовый файл Excel, чтобы проверить, не связана ли это с моей пандой, но мне удалось создать файл Excel.
Я использую пакет ClosedXML (версия 0.95.4), чтобы открыть файл Excel (.xlsx), написанный с использованием расширения NPOI, и загрузить его в хранилище BLOB-объектов в Azure. Итак, к файлу есть доступ.
Однако, когда я пытаюсь открыть файл с помощью...
Я генерирую лист Excel с Phpexcel, когда использую условное форматирование с условием, которое будет (поиск текста или его части), я получаю ошибку проверки при попытке открыть сгенерированный лист. Отлично работает с числами, меньше с текстами....