I'm trying to drop a column from my dataframe, but the problem is that whenever I drop the column (which works) my columns always get rearranged in different orders. Does anyone know why this might be? This is my code right now:
df=df.drop('column_name', axis=1)
One way to do it is:
df = df[[col1,col2,col4]] #if col3 is what you want to drop
This is useful when you have fewer columns.
I can not reproduce your problem. But I believe the following code can keep the order. It's the same idea as runzhi xiao's answer, but without typing all the remaining columns.
df = pd.DataFrame({
'col1': [1, 2, 3, 4],
'col2': ['a', 'e', 'i', 'o'],
'col3': ['a', 'e', 'i', 'o'],
'col4': [0.1, 0.2, 1, 2],
})
cols_to_drop = ['col2']
new_columns = df.columns.drop(cols_to_drop).to_list()
df[new_columns]
col1 col3 col4
0 1 a 0.1
1 2 e 0.2
2 3 i 1.0
3 4 o 2.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.