Transpose Dataframe Pandas And Add A New Column
Trying to learn more about DataFrames with practical example I am working on. I got a table of two columns like that: Grades Count Grade1 55 Grade2 42 Grade3 65 Grade4
Solution 1:
If need transpose and processing index with columns names convert column Grades
to index, select column by [[]]
to one column Dataframe
, transpose by DataFrame.T
, rename
index and set column name by DataFrame.rename_axis
:
d = {'Count':'Myschool'}
df1 = df.set_index('Grades')[['Count']].T.rename(d).rename_axis('School', axis=1)
If only 2 column DataFrame
is possible omit selecting column:
df1 = df.set_index('Grades').T.rename({'Count':'Myschool'}).rename_axis('School', axis=1)
print (df1)
School Grade1 Grade2 Grade3 Grade4
Myschool 55426570
Another idea:
df1 = df.set_index('Grades')['Count'].to_frame('Myschool').T.rename_axis('School', axis=1)
Post a Comment for "Transpose Dataframe Pandas And Add A New Column"