ASH
ASH

Reputation: 20342

How to parse a CSV file as with commas or pipes and read into a data frame?

I am trying to loop through multiple CSV files in a folder and parse each file into a data frame then get the data type for each field. Before I can even get to the loop, I'm trying to parse a single CSV file, and I'm encountering some issues. This is what I'm working with now.

import pandas as pd
# CSV file
csv_file = 'C:\\path\\ARMINDEX.CSV'
# read cvs with pandas read_csv
df = pd.read_csv(csv_file)
df.dtypes

Upvotes: 1

Views: 1518

Answers (1)

Karn Kumar
Karn Kumar

Reputation: 8826

you have pipe"|" delimited fields, which you can try like below with a regex separator sep="|", However you can use altogether skipinitialspace=True to Skip spaces after delimiter.

import pandas as pd
# CSV file
csv_file = 'C:\\path\\ARMINDEX.CSV'
# read cvs with pandas read_csv
df = pd.read_csv(csv_file, sep="|", skipinitialspace=True, header=None)

If you need to assign names to the delimited Feilds to get them a Name, you can try..

df = pd.read_csv(csv_file, sep="|", skipinitialspace=True, index_col=False, newCols=['Col1', 'Col2', 'Col3', 'Col4'])

Upvotes: 2

Related Questions