Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting values after transpose of dataframe

My dataframe is:

0 1 2 3
a 1091 347 2164
b 208 284 27647
c 0 8126 22

After transposing

0 a b c
1 1.091 208 0
2 347 284 8126
3 2161 27647 22
df=df.set_index(0)
print(df)
df = df.T
print(df)
df = df.sort_values(by=df.index, ascending=True)
print(df)

But I am getting an error like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

KeyError: Int64Index([1, 2, 3, 4], dtype='int64')

I am trying to plot index values to a column but it should be in ascending order because index 3 refers new value but index 1 is an old value in the time range.

fig = px.line(df, x=df.index, y=df['a'])
fig.show()

>Solution :

Instead of df.sort_values(by=df.index), use df.sort_index:

df = df.sort_index(ascending=True)

Output:

>>> df
      1     2      3
a  1091   347   2164
b   208   284  27647
c     0  8126     22
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading