0

I'm having issues attempting to use inplace = True so that I don't have to constantly make a new variable to hold the changes to the Dataframes. does is work on sum functions and not others? where else can I use it? Should I just store the change in the DataFrame with a new variable and not use inplace?

sp500["Close"].str.replace("$", " ").astype(float)

sp500["Close"].str.replace({"$", " "}, inplace = True).astype({float}, inplace =True)

These worked with no problem

sp500.dropna(inplace = True)

sp500.sort_index(ascending = True, inplace =True)

Sample of the Data frame

Date
2012-10-01    1444.49
2012-10-02    1445.75
2012-10-03    1450.99
2012-10-04    1461.40
2012-10-05    1460.93
               ...   
2019-04-16    2907.06
2019-04-17    2900.45
2019-04-18    2905.03
2019-04-22    2907.97
2019-04-23    2933.68
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • For most functions, if you past `inplace = True`, it returns `None` and you can't chain any longer. So, don't use `inplace`, see [this question](https://stackoverflow.com/questions/45570984/in-pandas-is-inplace-true-considered-harmful-or-not) as well. – Quang Hoang Jun 17 '22 at 17:05

1 Answers1

0

You don't need to use any new variables in this case:

sp500.Close = sp500.Close.str.replace("$", " ").astype(float)

You can access columns as attributes as long as your column names are "legal," making it terser and clearer to read. If you're performing operations on views of your data, make sure to do replacements using .loc or .iloc; otherwise, you will get warnings about returning a copy vs returning a view.

Generally, it is best to avoid using inplace=True as it makes the code harder to follow and can lead to unintended consequences and strange behaviour. It also eliminates your ability to use method chaining effectively. Look at the following as an example:

df = df.some_method(*args).another_method(*args)
# vs
df.some_method(*args, inplace=True)
df.another_method(*args, inplace=True)
Philip Ciunkiewicz
  • 2,652
  • 3
  • 12
  • 24