The error you're encountering arises from a misunderstanding in how the one-hot encoded data is being converted to a DataFrame. The issue is in this part of your code:
one_hot_df = pd.DataFrame(one_hot_encoded, columns=encoder.get_feature_names_out(input_features=['name']))
The one_hot_encoded output from OneHotEncoder.fit_transform() is a sparse matrix, not a dense NumPy array. Additionally, the way columns is being specified is incorrect because the number of columns in one_hot_encoded is dependent on the number of unique categories, so it doesn't match the length implied by encoder.get_feature_names_out(...). Let's fix these issues:
- Convert
one_hot_encoded to a dense array with .toarray().
- Correctly specify column names using just
encoder.get_feature_names_out().
Here is the corrected version:
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)
Explanation:
- Sparse to Dense: By specifying
sparse=False in the OneHotEncoder, the returned encoding is a dense array, ideal for conversion into a DataFrame.
- Column Names: The corrected column names are obtained directly from
encoder.get_feature_names_out(), which appropriately generates feature names for one-hot encoded variables.
- Reset Index Before Concatenation: I added an explicit index reset for both
df and one_hot_row before concatenation to ensure there are no index-related issues during the concatenation. This step is vital if your row indices have non-standard ordering or missing values.