Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas, read CSV ignoring extra commas

Tags:

python

pandas

I am reading a CSV file with 8 columns into Pandas data frame. The final column contains an error message, some of which contain commas. This causes the file read to fail with the error ParserError: Error tokenizing data. C error: Expected 8 fields in line 21922, saw 9

Is there a way to ignore all commas after the 8th field, rather than having to go through the file and remove excess commas?

Code to read file:

import pandas as pd
df = pd.read_csv('C:\\somepath\\output.csv')

Line that works:

061AE,Active,001,2017_02_24 15_18_01,00006,1,00013,some message

Line that fails:

061AE,Active,001,2017_02_24 15_18_01,00006,1,00013,longer message, with commas
like image 480
MikeS159 Avatar asked Feb 07 '18 15:02

MikeS159


2 Answers

You can use the parameter usecols in the read_csv function to limit what columns you read in. For example:

import pandas as pd
pd.read_csv(path, usecols=range(8))

if you only want to read the first 8 columns.

like image 67
Blazina Avatar answered Oct 12 '22 04:10

Blazina


You can use re.sub to replace the first few commas with, say, the '|', save the intermediate results in a StringIO then process that.

import pandas as pd
from io import StringIO
import re

for_pd = StringIO()
with open('MikeS159.csv') as mike:
    for line in mike:
        new_line = re.sub(r',', '|', line.rstrip(), count=7)
        print (new_line, file=for_pd)

for_pd.seek(0)

df = pd.read_csv(for_pd, sep='|', header=None)
print (df)

I put the two lines from your question into a file to get this output.

       0       1  2                    3  4  5   6  \
0  061AE  Active  1  2017_02_24 15_18_01  6  1  13   
1  061AE  Active  1  2017_02_24 15_18_01  6  1  13   

                             7  
0                 some message  
1  longer message, with commas  
like image 37
Bill Bell Avatar answered Oct 12 '22 04:10

Bill Bell