How To Extract Named Columns From A Csv?
I have a csv file that contains around 50 columns, but I only need about 10 of them. I want to be able to extract the columns I need from that csv file to a new csv file. The top a
Solution 1:
Read it in using the DictReader class, then you can write out fields by name instead of by index.
Solution 2:
The advantage of using pandas for this is that not only it makes easy to open and save your files in different formats and modify columns and rows, but also because you can also modify, calculate and play with your data if you need it.
To obtain a csv file with selected columns is straighforward:
import pandas as p
df = p.read_csv('File2.csv') # reads your csv file as a table (dataframe object)
df2 = df[['cost', 'date']] # selects two of the columns in your file
df2.to_csv('my_out.csv') # saves again in csv format
Post a Comment for "How To Extract Named Columns From A Csv?"