如何在pandas中使用fillna函数?

How to use fillna function in pandas?

我有一个包含三个电池充电和放电顺序的数据框:

        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

负数表示充电,正数表示放电。所以我添加了所有数字行然后尝试充电和放电顺序。

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)

预期输出:

     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

但是不知何故这个 fillna 没有填充 0 值并给出这个输出:

     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

在这里换车道reindex

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

这是使用剪辑的方法

df.assign((bess = df.sum(axis=1),
           charging = df.sum(axis=1).clip(upper = 0),
           discharging = df.sum(axis=1).clip(0)))