florvdl
florvdl

Reputation: 61

'NoneType' error after applying .copy() to a panda dataframe

I am using the Titanic dataset for a project. I first created a dataframe with

titanic_df = pd.read_csv("titanic_data.csv")

and applied a few changes (fillna and so on).

Now I'd like to drop a few columns in that dataframe, but to avoid affecting my previous work I want to create a copy of this first. So I do

titanic_ml = titanic_df.copy().drop(['PassengerId','Name'],axis=1,inplace=True)

and then when I try to display the info

titanic_ml.info()

I get this error message: AttributeError: 'NoneType' object has no attribute 'info'

If I apply .info() to my original titanic_df I have no issues.

Can someone please tell me what I am doing wrong here? Thanks!

Upvotes: 2

Views: 2212

Answers (1)

piRSquared
piRSquared

Reputation: 294468

when you used inplace=True you made the change to the return value of copy() in place and returned None.

Also note that drop returns a copy and therefore, the copy method is unnecessary.

To fix your problem, don't use inplace=True

titanic_ml = titanic_df.drop(['PassengerId','Name'], axis=1)

further explanation

titantic_df.copy() returns a dataframe that is passed to drop. drop subsequently returns a copy of the dataframe without the items requested to be dropped. If you pass inplace=True it performs the operation to the object and returns None instead. It is that None that you assigned to the variable titanic_ml and that is why you got the error AttributeError: 'NoneType' object has no attribute 'info'.

Upvotes: 2

Related Questions