Is there an easy way to reformat the columns from
JavaScript
x
4
1
2000-01-03 Location1 A1 B1 C1 A2 B2 C2 A3 B3 C3
2
2000-01-04 Location2 A1 B1 C1 A2 B2 C2 A3 B3 C3
3
2000-01-05 Location3 A1 B1 C1 A2 B2 C2 A3 B3 C3
4
to
JavaScript
1
4
1
2000-01-03 Location1 A1 A2 A3 B1 B2 B3 C1 C2 C3
2
2000-01-04 Location2 A1 A2 A3 B1 B2 B3 C1 C2 C3
3
2000-01-05 Location3 A1 A2 A3 B1 B2 B3 C1 C2 C3
4
Thanks
Advertisement
Answer
To reorder columns dynamically based on value, here is a way to do it:
JavaScript
1
2
1
df.sort_values(df.index[0], axis=1)
2
This returns a dataframe with columns (axis=1) ordered based on sorted value of first row.
Here is a full example using your data sample:
JavaScript
1
17
17
1
import pandas as pd
2
from io import StringIO
3
4
sample=StringIO('''date location x1 y1 z1 x2 y2 z2 x3 y3 z3
5
2000-01-03 Location1 A1 B1 C1 A2 B2 C2 A3 B3 C3
6
2000-01-04 Location2 A1 B1 C1 A2 B2 C2 A3 B3 C3
7
2000-01-05 Location3 A1 B1 C1 A2 B2 C2 A3 B3 C3''')
8
9
df = pd.read_csv(sample, sep=' ')
10
print(df)
11
12
df2 = df.sort_values(df.index[0], axis=1)
13
initialCols = ['date','location']
14
restCols = [col for col in df2.columns if col not in initialCols]
15
dfFinal = df2[initialCols + restCols]
16
dfFinal
17