hi, i have 4 csv files each has a unique name i want to create onehot encode from their…
- User
hi, i have 4 csv files each has a unique name i want to create one_hot encode from their names and add to each csv file
i have following code : import os import pandas as pd import numpy as np from sklearn.preprocessing import OneHotEncoder
Directory containing your CSV files
directory = r'E:\01_calculate_talib\New folder (2)'
List all CSV files
csv_files = [file for file in os.listdir(directory) if file.endswith('.csv')]
Extract unique names (without .csv extension)
unique_names = [os.path.splitext(filename)[0] for filename in csv_files]
Reshape names for One-Hot Encoder
unique_names = np.array(unique_names).reshape(-1, 1)
Apply One-Hot Encoding
encoder = OneHotEncoder(sparse=False) one_hot_encoded = encoder.fit_transform(unique_names)
Create a DataFrame for easier handling
one_hot_df = pd.DataFrame(one_hot_encoded, columns=encoder.get_feature_names_out())
Read Each CSV, Modify, and Save
for i, file in enumerate(csv_files): # Read the CSV file path = os.path.join(directory, file) df = pd.read_csv(path)
# Get the corresponding one-hot encoded row (as a DataFrame to align columns) one_hot_row = one_hot_df.iloc[[i]] # If handling as a column, we temporarily reset index for concatenation df.reset_index(drop=True, inplace=True) one_hot_row.reset_index(drop=True, inplace=True) # Concatenate the CSV data with the one-hot encoded row modified_df = pd.concat([df, one_hot_row], axis=1) # Save the modified DataFrame back to a CSV modified_df.to_csv(path, index=False)but it dosnt work it throws following errors: TypeError: OneHotEncoder.init() got an unexpected keyword argument 'sparse' ValueError: Shape of passed values is (4, 1), indices imply (4, 4)
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.