How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

后端 未结 13 1643
无人共我
无人共我 2020-11-22 01:37

I have a Pandas Dataframe as below:

      itm Date                  Amount 
67    420 2012-09-30 00:00:00   65211
68    421 2012-09-09 00:00:00   29424
69             


        
13条回答
  •  余生分开走
    2020-11-22 01:54

    I just wanted to provide a bit of an update/special case since it looks like people still come here. If you're using a multi-index or otherwise using an index-slicer the inplace=True option may not be enough to update the slice you've chosen. For example in a 2x2 level multi-index this will not change any values (as of pandas 0.15):

    idx = pd.IndexSlice
    df.loc[idx[:,mask_1],idx[mask_2,:]].fillna(value=0,inplace=True)
    

    The "problem" is that the chaining breaks the fillna ability to update the original dataframe. I put "problem" in quotes because there are good reasons for the design decisions that led to not interpreting through these chains in certain situations. Also, this is a complex example (though I really ran into it), but the same may apply to fewer levels of indexes depending on how you slice.

    The solution is DataFrame.update:

    df.update(df.loc[idx[:,mask_1],idx[[mask_2],:]].fillna(value=0))
    

    It's one line, reads reasonably well (sort of) and eliminates any unnecessary messing with intermediate variables or loops while allowing you to apply fillna to any multi-level slice you like!

    If anybody can find places this doesn't work please post in the comments, I've been messing with it and looking at the source and it seems to solve at least my multi-index slice problems.

提交回复
热议问题