Skip to content
Advertisement

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:

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()

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement