Методы удаления столбца из файла CSV с использованием Python

Чтобы удалить столбец из CSV-файла с помощью Python, вы можете использовать различные методы. Вот несколько подходов:

Метод 1: использование модуля csv

import csv
# Specify the input and output file paths
input_file = 'input.csv'
output_file = 'output.csv'
# Specify the index of the column to delete
column_index = 2
with open(input_file, 'r') as file_in, open(output_file, 'w', newline='') as file_out:
    reader = csv.reader(file_in)
    writer = csv.writer(file_out)

    for row in reader:
        del row[column_index]
        writer.writerow(row)

Метод 2. Использование библиотеки pandas

import pandas as pd
# Read the CSV file into a DataFrame
df = pd.read_csv('input.csv')
# Specify the column to delete
column_name = 'column_name'
# Delete the column
df.drop(column_name, axis=1, inplace=True)
# Save the modified DataFrame to a new CSV file
df.to_csv('output.csv', index=False)

Метод 3. Использование библиотеки NumPy

import numpy as np
# Read the CSV file into a NumPy array
data = np.genfromtxt('input.csv', delimiter=',')
# Specify the column index to delete
column_index = 2
# Delete the column
updated_data = np.delete(data, column_index, axis=1)
# Save the modified array to a new CSV file
np.savetxt('output.csv', updated_data, delimiter=',')

Это всего лишь несколько примеров того, как можно удалить столбец из CSV-файла с помощью Python. Не забудьте настроить путь к входному файлу, индекс столбца или имя столбца в соответствии с вашими конкретными требованиями.