Reputation: 379
I want to get a csv file similar to this:
index,Basic Mechanics,Basic Thermodynamics,Calculus I,Calculus II,Chemistry I,Chemistry II,Engineering Drawing,Fundamentals of Informatics,Geometry,Linear Algebra
ATTEMPTS,1.416,1.404,1.421,1.347,1.305,1.246,1.261,1.456,1.325,1.385
I have the following code:
attempts=pd.read_csv("attempts.csv",sep=',', delimiter=None, header='infer')
a2=attempts[(attempts["HSCHOOL"]=="hs1")]
df=a2[["Subject","ATTEMPTS"]]
def subjects_hs(df):
df=df.pivot_table(columns="Subject",values="ATTEMPTS")
df=df.reset_index()
df=df.round(decimals=3)
df.to_csv("attempts_hs.csv",index=False)
Where attempts.csv looks like this:
AC_YEAR,HSCHOOL,Subject,ATTEMPTS
2010,hs1,Linear Algebra,2
2010,hs1,Calculus I,1
2010,hs1,Basic Mechanics,2
2010,hs1,Chemistry I,2
2010,hs3,Fundamentals of Informatics,2
2010,hs2,Calculus II,1
2010,hs1,Basic Thermodynamics,1
2010,hs3,Linear Algebra,1
2010,hs3,Calculus I,1
2010,hs2,Basic Mechanics,1
2010,hs2,Chemistry I,1
2010,hs2,Fundamentals of Informatics,1
And instead, I am getting the following file:
Subject,ATTEMPTS
Basic Mechanics,1.545
Basic Thermodynamics,1.667
Calculus I,1.545
Calculus II,1.545
Chemistry I,1.667
Chemistry II,1.4
Engineering Drawing,1.692
Fundamentals of Informatics,2.0
Geometry,1.583
Linear Algebra,1.5
Which is not the format I am looking for (I want everything in one line!). When I try it in python normally, it works but when in pythonanywhere is not... Any idea? Thanks!
Upvotes: 2
Views: 65
Reputation: 1428
It seems to work for me with the following code
attempts=pd.read_csv("attempts.csv",sep=',', delimiter=None, header='infer')
a2=attempts[(attempts["HSCHOOL"]=="hs1")]
df=a2[["Subject","ATTEMPTS"]]
def subjects_hs(df):
df=df.pivot_table(columns="Subject",values=["ATTEMPTS"])
df=df.reset_index()
df=df.round(decimals=3)
df.to_csv("attempts_hs.csv",index=False)
pivot_table provides the expected behavior when its 'values' argument is a list.
line 5 : change values="ATTEMPTS"
with values=["ATTEMPTS"]
Upvotes: 2