简体   繁体   中英

Change delimiter in csv file - Python

I have a csv file in google colab (python) called 'student-mat.csv' when I print it, it looks like this: school;sex;age;address;famsize;Pstatus;Medu;Fedu;Mjob;Fjob;reason;guardian;traveltime;studytime;failures;schoolsup;famsup;paid;activities;nursery;higher;internet;romantic;famrel;freetime;goout;Dalc;Walc;health;absences;G1;G2;G3

The delimiter is wrong and I do not know how to change it, as instead of writing simple code like this:

df = pd.read_csv('student-mat.csv')

I have to write this:

df = pd.read_csv(io.StringIO(uploaded['student-mat.csv',delimiter=';'].decode('utf-8')))
print(df.head())

This is because I uploaded the file differently. And when I type that code it is incorrect because the delimiter is in the wrong spot. It gives a simple SyntaxError: invalid syntax

Why you complicated yourself your life? Simply use

df = pd.read_csv('student-mat.csv', sep=';', encoding='utf-8')

See pandas.read_csv .

The delimiter needs to be placed here:

df = pd.read_csv(io.StringIO(uploaded['student-mat.csv'].decode('utf-8')), delimiter=';')

print(df.head())

This then returns it in a pandas DataFrame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM