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()
CodePudding user response:
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
CodePudding user response:
You can sort the index if you cast it to str dtype with a list comprehension.
df = pd.DataFrame({'0': {0: 'a', 1: 'b', 2: 'c'},
'1': {0: 1091, 1: 208, 2: 0},
'2': {0: 347, 1: 284, 2: 8126},
'3': {0: 2164, 1: 27647, 2: 22}})
df = df.T
df=df.set_index(0)
df.index = [str(x) for x in df.index]
df.sort_index(ascending=True)
Output df:
1 2
1091 208 0
2164 27647 22
347 284 8126
a b c
CodePudding user response:
i would prefer to sort by specific column. sort_index sorts by first column afaik.
df.sort_values('column name')