'How to sort column index python
In python, I am trying to sort my column
Index(['id', 'Q1', 'Q10', 'Q11', 'Q12', 'Q13', 'Q14', 'Q15', 'Q2', 'Q3', 'Q4',
'Q5', 'Q6', 'Q7', 'Q8', 'Q9'],
dtype='object')
using
**test.sort_index(axis=1,key=lambda x: x.str[1:])**
but I am getting results as
Q1 Q10 Q11 Q12 Q13 Q14 Q15 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 id
whereas output should look like:
id,'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10', 'Q11', 'Q12', 'Q13', 'Q14', 'Q15'
Solution 1:[1]
Remove Q by str.replace and convert values to numeric by to_numeric with converting to NaN if non numeric column like id and also add na_position='first' for first non Q columns:
test = pd.DataFrame(columns=['id', 'Q1', 'Q10', 'Q11', 'Q12', 'Q13',
'Q14', 'Q15', 'Q2', 'Q3', 'Q4','Q5', 'Q6', 'Q7', 'Q8', 'Q9'],)
df = test.sort_index(axis=1,
key=lambda x: pd.to_numeric(x.str.replace('Q','',regex=True),errors='coerce'),
na_position='first')
print (df)
Empty DataFrame
Columns: [id, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15]
Index: []
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
