Rearrangement of python columns

In practical applications, we often generate a lot of columns. Sometimes we modify the dateframe to add or reduce columns, but in the end it still needs to be spliced ​​together. It is inevitable that the columns can be aligned. If there is a need for rearrangement, the idea is to first Get the column names, sort the column names, and generate new data according to the new column names.

Data instance df2

 

import numpy as np
import pandas as pd
cols=df2.columns
cols2= sorted(cols)
df_reordered = df2[cols2]

 According to this reordering, the data generated in the future can be directly spliced.

In Python, you can use  methods pandas in the library  DataFrame.reindex to reorder rows in a DataFrame.

Here's an example, assuming you have a  df DataFrame called and you want to reindex the rows in a given order:

new_column_order = ['col_b', 'col_c', 'col_a']
df = df.reindex(columns=new_column_order)

This will rearrange the columns in the DataFrame in the given order.

Note that if you want to leave the original DataFrame unchanged and create a new DataFrame, you can use the following code:

This will create a new DataFrame with columns in the given order.

new_column_order = ['col_b', 'col_c', 'col_a']
df_reordered = df[new_column_order]

Guess you like

Origin blog.csdn.net/weixin_42984235/article/details/128457639