Note
Pandas (45) 본문
728x90
How to change the order of columns of a dataframe?
# Input
df = pd.DataFrame(np.arange(20).reshape(-1, 5), columns=list('abcde'))
# 1
df[list('cbade')]
# 2 - No hard coding
def switch_columns(df, col1=None, col2=None):
colnames = df.columns.tolist()
i1, i2 = colnames.index(col1), colnames.index(col2)
colnames[i2], colnames[i1] = colnames[i1], colnames[i2]
return df[colnames]
df1 = switch_columns(df, 'a', 'c')
# 3
df[sorted(df.columns)]
# or
df.sort_index(axis=1, ascending=False, inplace=True)
'Pandas' 카테고리의 다른 글
Pandas (47) (0) | 2022.09.13 |
---|---|
Pandas (46) (0) | 2022.09.12 |
Pandas (44) (0) | 2022.09.10 |
Pandas (43) (0) | 2022.09.07 |
Pandas (42) (0) | 2022.09.06 |
Comments