Home > Software engineering >  Reorder Pandas Columns
Reorder Pandas Columns

Time:02-10

How can I reorder using pandas, Column 8, Column 9 and Column 10 next to column 2??

For example:

|sku_id|primary_category_code|name_chi|summary_chi|original_price|discount_price|stock_available|primary_category_1|primary_category_2|primary_category_3|
|-|-|-|-|-|-|-|-|-|-|
|row|row|row|row|row|row|row|row|row|row|
|row|row| row|row|row|row|row| row|row|row|

I want result to be:

sku_id primary_category_code primary_category_1 primary_category_2 primary_category_3 name_chi summary_chi original_price discount_price stock_available
row row row row row row row row row row
row row row row row row row row row row

CodePudding user response:

Given some DataFrame that looks like this:

df = pd.DataFrame(columns=range(1, 11))
df

Empty DataFrame
Columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Index: []

You can reorder the DataFrame's columns by index using iloc. I use np.r_ to make selection easy:

df.iloc[:, np.r_[0:2, 7:10, 2:8]]

Empty DataFrame
Columns: [1, 2, 8, 9, 10, 3, 4, 5, 6, 7, 8]
Index: []
  •  Tags:  
  • Related