Search code examples
pythonpandasfillna

How to use fillna function in pandas?


I have a dataframe which has three Battery's charging and discharging sequence:

        Battery 1  Battery 2  Battery 3
0          32          3         -1
1          21         11        -31
2          23         27         63
3          12        -22        -22
4         -21         22         44
5         -66          6         66
6         -12         32        -52
7         -45        -45         -4
8          45        -55        -77
9          66         66         96
10         99        -39        -69
11         88         99         48

if the number is negative then it will be charging and if it is positive then it will discharging. So what I added all the numbers rows and then try to the charging and discharging sequence.

import pandas as pd
dic1 = {
    'Battery 1': [32,21,23,12,-21,-66,-12,-45,45,66,99,88],
    'Battery 2': [3,11,27,-22,22,6,32,-45,-55,66,-39,99],
    'Battery 3': [-1,-31,63,-22,44,66,-52,-4,-77,96,-69,48]
}
df = pd.DataFrame(dic1)
bess = df.filter(like='Battery').sum(axis=1) # Adding all batteries
charging = bess[bess<=0].fillna(0) #Charging
discharging = bess[bess>0].fillna(0) #Discharging
bess['charging'] = charging #creating new column for charging
bess['discharging'] = discharging #creating new column for discharging
print(bess)

Excpected output:

     bess  charging  discharging
0     34       0.0         34.0
1      1       0.0          1.0
2    113       0.0        113.0
3    -32     -32.0          0.0
4     45       0.0         45.0
5      6       0.0          6.0
6    -32     -32.0          0.0
7    -94     -94.0          0.0
8    -87     -87.0          0.0
9    228       0.0        228.0
10    -9      -9.0          0.0
11   235       0.0        235.0

but instead somehow this fillna is not filling 0 values and giving this output:

     bess   charging discharging
0     34                   34
1      1                    1
2    113                  113
3    -32      -32            
4     45                   45
5      6                    6
6    -32      -32            
7    -94      -94            
8    -87      -87            
9    228                  228
10    -9       -9            
11   235                  235

Solution

  • Change the lane here with reindex

    charging = bess[bess<=0].reindex(df.index,fill_value=0) #Charging
    discharging = bess[bess>0].reindex(df.index,fill_value=0) #Discharging