DolphaGo / TIL

TIL & issues
0 stars 1 forks source link

[Python] CSV 파일의 특정 컬럼을 읽고, 해당 컬럼 값을 전처리 하여 새로운 CSV 파일로 저장하기 #127

Open DolphaGo opened 1 year ago

DolphaGo commented 1 year ago
import pandas as pd

def preprocess_string(input_string):
    # Add your string pre-processing logic here
    # For example, let's convert the string to uppercase
    processed_string = f'"{input_string}"'
    return processed_string

def read_specific_column(input_file, column_name, output_file):
    try:
        # Read the CSV file into a pandas DataFrame
        df = pd.read_csv(input_file, encoding_errors="ignore")

        # Get the specific column
        specific_column = df[column_name]

        # Preprocess the strings in the column
        processed_column = specific_column.apply(preprocess_string)

        # Save the processed column to another CSV file
        processed_df = pd.DataFrame({column_name: processed_column})
        processed_df.to_csv(output_file, index=False)

        print(f"Successfully processed the column '{column_name}' and saved to '{output_file}'.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    input_file = "input.csv"  # Replace with your input CSV file path
    output_file = "output.csv"  # Replace with your output CSV file path
    column_name = "columnName"  # Replace with the name of the column you want to process

    read_specific_column(input_file, column_name, output_file)