Here's the optimized code wrapped in a function, ready to be used in another file:
def encode_categorical_features(input_csv_path, output_tsv_path, columns_to_encode, id_column='Image Name', remove_extension='.jpg', sep='\t', header=False, index=False):
"""
Reads an input CSV file, performs one-hot encoding on specified categorical columns,
and writes the result to an output TSV file.
Parameters:
input_csv_path (str): Path to the input CSV file.
output_tsv_path (str): Path to save the output TSV file.
columns_to_encode (list of str): List of column names to be one-hot encoded.
id_column (str, optional): Name of the identifier column to be included. Default is 'Image Name'.
remove_extension (str or None, optional): If provided, this extension will be removed from the values in id_column. Default is '.jpg'.
sep (str, optional): Field delimiter for the output file. Default is '\t'.
header (bool, optional): Write out the column names. Default is False.
index (bool, optional): Write row names (index). Default is False.
"""
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
# Read only the necessary columns to improve efficiency
columns_to_read = [id_column] + columns_to_encode
df = pd.read_csv(input_csv_path, usecols=columns_to_read)
# Initialize OneHotEncoder with dtype set to integer to output int values
enc = OneHotEncoder(handle_unknown='ignore', dtype=np.int8)
# Fit and transform the categorical columns
emb = enc.fit_transform(df[columns_to_encode])
# Retrieve the names of the one-hot encoded features
feature_names = enc.get_feature_names_out(columns_to_encode)
# Create a DataFrame with the encoded features and ensure they are integers
emb_df = pd.DataFrame(emb.toarray(), columns=feature_names, dtype=np.int8)
# Concatenate the id_column with the one-hot encoded features
result_df = pd.concat([df[[id_column]], emb_df], axis=1)
# Remove specified extension from id_column
if remove_extension:
result_df[id_column] = result_df[id_column].str.replace(remove_extension, '', regex=False)
# Save the final DataFrame to a TSV file without headers and index
result_df.to_csv(output_tsv_path, index=index, header=header, sep=sep)
Usage Example:
Assuming you have this function saved in a file named encoding_utils.py, you can use it in another script as follows:
from encoding_utils import encode_categorical_features
input_csv = '/path/to/your/input.csv'
output_tsv = '/path/to/your/output.tsv'
columns_to_encode = ['Object', 'Adjective', 'Activity', 'Place', 'Feeling']
encode_categorical_features(input_csv, output_tsv, columns_to_encode)
Note on Optimizations:
- Parameterization: The function is parameterized to accept different input and output paths, columns to encode, and other optional parameters, making it flexible and reusable.
- Memory Efficiency: By specifying
dtype=np.int8 in the OneHotEncoder, the memory footprint is reduced when dealing with the integer output of the encoder.
- Selective Reading: Only necessary columns are read from the CSV using
usecols, which reduces the memory usage and speeds up the reading process.
- Extension Removal: The extension removal from the
id_column is made optional, and it can be customized via the remove_extension parameter.
Important Considerations:
- For very large datasets, converting the sparse matrix to a dense array with
toarray() might not be memory efficient. In such cases, consider processing the data in chunks or using methods that can handle sparse data structures.
- Ensure that the
columns_to_encode are correctly specified and exist in your input CSV file.
- You may need to adjust the
id_column and remove_extension parameters based on your specific data.
This function can now be imported and used in any other Python file, providing a reusable and optimized way to perform one-hot encoding on categorical data.