我想获取与此类似的csv文件:
'db56603552049bb2d463de456c11cae9b6181eb6ca01a65ca93292a54fa30b731588066f29c4ea20deac65831252c0ee3cb38d098c39edba5b65efe968c59eaa'
我有以下代码:
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
Trys.csv如下所示:
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)
相反,我正在获取以下文件:
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
不是我想要的格式(我希望所有内容都在一行中!)。当我在python中正常尝试时,它可以工作,但是在pythonanywhere中却不是时...任何想法吗?谢谢!
答案 0 :(得分:2)
使用以下代码似乎对我有用
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的'values'参数是一个列表时,它提供了预期的行为。
第5行:将values="ATTEMPTS"
更改为values=["ATTEMPTS"]