0

I want to implement something like pivot in SQL, pivot_table in dataframe looks like different from pivot in SQL as after pivot_table, each column is a pair instead of a single str.

df = pd.DataFrame({"col1":["grade1","grade2","grade3"],"score":[70,80,90],"name":["n1","n2","n3"]})
print(df)
r=pd.pivot_table(df,columns=["col1"],values=["score"],index=["name"]).reset_index()
print(r.columns)
print(r)

And the result of r is enter image description here.

I don't need socre and col1 show in the result, just want to have a table with 4 columns:grade1/2/3 and score. How to do it in dataframe?

Daniel Wu
  • 5,853
  • 12
  • 42
  • 93

1 Answers1

0
df.pivot(index='name', columns='col1', values='score').reset_index().drop("name", axis=1)

Or the same code, but replace pivot with pivot_table

Mark
  • 7,785
  • 2
  • 14
  • 34