Read specific columns from a csv file with csv module?

后端 未结 12 1145
闹比i
闹比i 2020-11-22 10:06

I\'m trying to parse through a csv file and extract the data from only specific columns.

Example csv:

ID | N         


        
12条回答
  •  忘掉有多难
    2020-11-22 10:53

    With pandas you can use read_csv with usecols parameter:

    df = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])
    

    Example:

    import pandas as pd
    import io
    
    s = '''
    total_bill,tip,sex,smoker,day,time,size
    16.99,1.01,Female,No,Sun,Dinner,2
    10.34,1.66,Male,No,Sun,Dinner,3
    21.01,3.5,Male,No,Sun,Dinner,3
    '''
    
    df = pd.read_csv(io.StringIO(s), usecols=['total_bill', 'day', 'size'])
    print(df)
    
       total_bill  day  size
    0       16.99  Sun     2
    1       10.34  Sun     3
    2       21.01  Sun     3
    

提交回复
热议问题