python - Write a program that can read the file and display the number of students travelling by each mode of transport -


here scenario file “travel.txt” stores data students follows:

first name, surname, programme, means of transport.

sample data is:

john farmer bsccse bus

kevin khan bscmcs taxi

janet zuber bscmis bus

san jacky bscais privatecar

sarah forceps bscis privatecar

i want read file , display number of students traveling each mode of transport in such form:

taxi 1

bus 2

privatecar 2

i've written following code:

f1=open("travel.txt",'r') line=f1.readline() count1=0 count2=0 count3=0 while line!=" ":     data=line.split()     if data[3]=="bus":         count1=count1+1     elif data[3]=="taxi":         count2=count2+1     else:         count3=count3+1     line=f1.readline() print("taxi","\t",count1) print("bus","\t",count2) print("private car","\t",count3) f1.close() 

but not working me

even though might have answer here is method bit simpler , can give other stats well. can read pandas automatically turns dataframe. allows nice stuff data.

assuming data has spaces between them can read file this:

import  pandas pd cols = ['name', 'surname', 'degree', 'transport'] data = pd.read_csv('test.csv', sep='\s', engine='python', header=none, names=cols) 

it give following output:

    name    surname degree  transport 0   john    farmer  bsccse  bus 1   kevin   khan    bscmcs  taxi 2   janet   zuber   bscmis  bus 3   san     jacky   bscais  privatecar 4   sarah   forceps bscis   privatecar 

you can find out how many students use each transport method follows:

data.groupby('transport').count()['name'] 

it give following output:

transport bus           2 privatecar    2 taxi          1 

there other stats methods can invoke such mean. makes code , data more flexible compared when "hard" code method.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -