0

I have many dataframes and I store them in a list.

Now I'd like to do simple fillna(0) to each dataframe, so I do the following, but it didn't work:

df_list = [df_1,df_2,df_3,df_4]

for df in df_list:
    df = df.fillna(0)
    df.index = df.index.strftime('%Y-%m-%d')

I think df on the left hand side inside the loop is not the same as original dataframe, how to do it?

smci
  • 32,567
  • 20
  • 113
  • 146
roudan
  • 3,082
  • 5
  • 31
  • 72
  • This is a duplicate. Better dupe target: [pandas fillna not working](https://stackoverflow.com/questions/25147707/pandas-fillna-not-working) – smci Jan 08 '22 at 07:33

1 Answers1

1

In your first line of the loop you are defining a new dataframe and doing nothing with it.

Instead you can just use inplace = True to do the work on the dataframe without creating a new one.

for df in df_list:
    df.fillna(0, inplace = True)
    df.index=df.index.strftime('%Y-%m-%d')
Pepsi-Joe
  • 447
  • 1
  • 10
  • 1
    Thank you Pepsi-joe – roudan Jan 08 '22 at 07:06
  • 1
    Some further reading for you: https://stackoverflow.com/questions/43893457/understanding-inplace-true – Pepsi-Joe Jan 08 '22 at 07:09
  • Thank you Pepsi-joe, if we use dictionary like this, for (key,df) in df_dict.items(): # not just items, use iterms() df_dict[key]=df.fillna(0), why original df don't change, but returned df using df_dict[key] change? – roudan Jan 08 '22 at 07:11