简体   繁体   中英

removing a column from a CSV file in python

I am attempting to remove a duplicate column from a csv file in Python3. I am able to get the code to run without error...however when I attempt to print the number of rows processed I receive a blank response in codio.

The response to running comes back as 1001codio@sigma-portal:~/workspace$

Can anyone point out how I can fix this? Ideally I would like it to print how many columns were deleted.

import csv
import re
data = []

import csv

input_file = 'customerdata.csv'
output_file = 'outputcustomerdata.csv'
cols_to_remove = [11] # Column indexes to be removed (starts at 0)

cols_to_remove = sorted(cols_to_remove, reverse=True) # Reverse so we remove from the end first
row_count = 0 # Current amount of rows processed

with open(input_file, "r") as source:
   reader = csv.reader(source)
   with open(output_file, "wt") as result:
       writer = csv.writer(result)
       for row in reader:
           row_count += 1
           print('\r{0}'.format(row_count), end='') # Print rows processed
           for col_index in cols_to_remove:
               del row[col_index]
           writer.writerow(row)

Try pandas

import pandas as pd
df = pd.read_csv('customerdata.csv')
df = df.drop('column_name', axis=1)

# save your file
df.to_csv('outputcustomerdata.csv', encoding='utf-8')

print(df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM