greatFritz
greatFritz

Reputation: 201

Python Pandas Drop reordering my dataframe when using drop

I am working with a dataframe where I have to take two columns (quant and sales) add them and then drop them, then capitalize the first letters of my column names. the problem is when I use drop it saves it to another dataframe. From the documentation the problem is from the

inplace=false

import pandas as pd

pie_info_original = pd.DataFrame(
    [("classic", "apple"), ("tangy", "orange"), ("creamy", "banana"),
     ("sour", "raspberry")], 
    columns = ["flavor", "fruit"])
pie_info_original.loc[:,'quant'] = [5,1,8,3]
pie_info_original.loc[:,'sales'] = [2,1,2,3]
pie_info = pie_info_original.drop(['quant', 'sales'], axis=1)
pie_info.rename(index=str, columns={"fruit": "Fruit", "flavor" : "Flavor"})
print(pie_info)

My data went from this

|  |fruit|flavor |quant|sales|
*****************************
| 0|apple|classic|5    | 2   |
| 1|orange|tangy|1    | 1   |
| 2|banana|creamy|8    | 3   |
| 3|raspberry|sour|3    | 3   |

To this

|  flavor | fruit 
*****************
| 0|classic|apple|
| 1|tangy|orange |
| 2|creamy|banana|
| 3|sour|raspberry|

How would I be able to rearrange my columns so they display in the correct order. I tried setting the inplace to true but that prevents a new dataframe from being created.

**I want fruit to come before flavor

Upvotes: 1

Views: 235

Answers (2)

Andy Hayden
Andy Hayden

Reputation: 375377

Rather than rename you could use the str.title method:

In [11]: pie_info.columns.str.title()
Out[11]: Index(['Fruit', 'Flavor'], dtype='object')

In [12]: pie_info.columns = df.columns.str.title()

This won't reorder the columns.

Upvotes: 1

Jeril
Jeril

Reputation: 8521

pie_info_original = pd.DataFrame(
    [("classic", "apple"), ("tangy", "orange"), ("creamy", "banana"),
     ("sour", "raspberry")], 
    columns = ["flavor", "fruit"])
pie_info_original.loc[:,'quant'] = [5,1,8,3]
pie_info_original.loc[:,'sales'] = [2,1,2,3]
pie_info = pie_info_original.drop(['quant', 'sales'], axis=1)
pie_info = pie_info.rename(index=str, columns={"fruit": "Fruit", "flavor" : "Flavor"})
pie_info = pie_info[["Fruit", "Flavor"]]
print(pie_info)

Output

       Fruit   Flavor
0      apple  classic
1     orange    tangy
2     banana   creamy
3  raspberry     sour

Upvotes: 0

Related Questions