How to extract named columns from a CSV?

前端 未结 2 1164
遇见更好的自我
遇见更好的自我 2021-01-06 21:03

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.

相关标签:
2条回答
  • 2021-01-06 21:45

    Read it in using the DictReader class, then you can write out fields by name instead of by index.

    0 讨论(0)
  • 2021-01-06 22:05

    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
    
    0 讨论(0)
提交回复
热议问题