How to read a file with a semi colon separator in pandas

I a importing a .csv file in python with pandas.

Here is the file format from the .csv :

a1;b1;c1;d1;e1;...
a2;b2;c2;d2;e2;...   
.....

here is how get it :

from pandas import *
csv_path = "C:...."
data = read_csv(csv_path)

Now when I print the file I get that :

0  a1;b1;c1;d1;e1;...
1  a2;b2;c2;d2;e2;...

And so on… So I need help to read the file and split the values in columns, with the semi color character ;.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

read_csv takes a sep param, in your case just pass sep=';' like so:

data = read_csv(csv_path, sep=';')

The reason it failed in your case is that the default value is ',' so it scrunched up all the columns as a single column entry.

Method 2

In response to Morris’ question above:
“Is there a way to programatically tell if a CSV is separated by , or ; ?”

This will tell you:

import pandas as pd

df_comma = pd.read_csv(your_csv_file_path, nrows=1,sep=",")
df_semi = pd.read_csv(your_csv_file_path, nrows=1, sep=";")
if df_comma.shape[1]>df_semi.shape[1]:
    print("comma delimited")
else:
    print("semicolon delimited")


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x