Last active
March 10, 2022 21:45
-
-
Save tchiavegatti/c914ee8dd068314582425945aab1df15 to your computer and use it in GitHub Desktop.
Reorder one or several columns of a dataframe #pandas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def change_column_order(df, col_position): | |
'''Reorder one or several columns of a dataframe. | |
Based on the function described at https://stackoverflow.com/a/37071454. | |
Parameters | |
---------- | |
df : pandas dataframe | |
col_position : dict | |
{'Column' : index where the column should be} | |
Returns | |
------- | |
df | |
The daframe with columns reordered. | |
''' | |
def reorder(df, col_name, idx): | |
cols = df.columns.tolist() | |
cols.remove(col_name) | |
cols.insert(idx, col_name) | |
return df[cols] | |
for key, value in col_position.items(): | |
col_name = key | |
idx = value | |
df = reorder(df, col_name, idx) | |
return df | |
# Other ways to reorder columns | |
## Reordering Pandas DataFrame Columns | |
df = df[['names','Score','Room','Grade','Teacher','Hobby']] | |
## Leveraging handy Pandas methods | |
### Another standard solution to is to pair the pd.drop() and the pd.insert() methods. The main limitation of this option is that it only works when moving one column at a time to a specific location. | |
mid = df['Hobby'] | |
df.drop(labels=['Hobby'], axis=1, inplace = True) | |
df.insert(1, 'Hobby', mid) | |
## Another function using a reference column to position other columns | |
def movecol(df, cols_to_move=[], ref_col='', place='After'): | |
cols = df.columns.tolist() | |
if place == 'After': | |
seg1 = cols[:list(cols).index(ref_col) + 1] | |
seg2 = cols_to_move | |
if place == 'Before': | |
seg1 = cols[:list(cols).index(ref_col)] | |
seg2 = cols_to_move + [ref_col] | |
seg1 = [i for i in seg1 if i not in seg2] | |
seg3 = [i for i in cols if i not in seg1 + seg2] | |
return(df[seg1 + seg2 + seg3]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment