effective_pandas_book icon indicating copy to clipboard operation
effective_pandas_book copied to clipboard

reordering columns

Open dlasusa opened this issue 2 years ago • 0 comments

Hi!

So I'm using the "recipe style" of working on a dataframe and assigning some new new columns as part of that process (which works great).

Once of the last steps I'd like to do is put all the columns in a specific order. In this case, by "all" I mean some of the original columns as well as some of the newly created columns.

I understand (or at least think I understand) that since I want access to the new columns, which are in the intermediate df, I'll need to use a lambda.

Looking through Effective Pandas (p.229) Matt does a column rename:

.rename(columns=lambda c: c.replace('.', '_')

But this is doing the same thing to all the columns so I couldn't figure out how to apply this concept to a simple reorder. If I was doing this outside of the recipe, I can simply do:

df[cols in my order] # cols include old and new columns

But using the following inside the function/recipe

[cols in my order] # cols include old and new columns

Naturally fails since the new cols don't exist here.

It's not a huge deal to simply do the ordering after the recipe function is called, just wondering if it's something I can do as part of the recipe?

Thanks! Dan

dlasusa avatar Nov 29 '22 20:11 dlasusa