copy and paste each column from an existing csv file into a new csv file

Viewed 1035

So I have an existing csv file with multiple columns. I am trying to copy each column (one by one) and paste it into a new csv file. The name of the new csv file will be the header of the column.

I am trying to tweak a code that picks specific columns but no luck so far for multiple columns.

import pandas as pd
cols = ['1']
my_file = r"D:/Excel/new_csv_3.csv"
pd.read_csv(my_file, usecols=cols).to_csv(r"D:/Excel/new1.csv", 
index=False)
2 Answers

Try this:

my_file = r"D:/Excel/new_csv_3.csv"
df = pd.read_csv(my_file)
for col in df.columns:
    df[col].to_csv(f'D:/Excel/new{col}.csv')

if you need specific columns, just change the for loop:

for col in ['1', '2', '3']:
    ...

So this code works fine with no additional column of row numbers

import pandas as pd
my_file = r"D:/Excel/new_csv_3.csv"
df = pd.read_csv(my_file)
for col in df.columns:
    df[col].to_csv(f'D:/Excel/{col}.csv', index=False)
Related