Skip to main content
 首页 » 编程设计

python之当我一次拆开多个级别时如何填充 na 值

2024年10月01日19zhengyun_ustc

考虑 pd.Series s 和 pd.MultiIndex mux

lol = [list('aabc'), list('xyyz'), [1, 2, 3, 3]] 
mux = pd.MultiIndex.from_arrays(lol, names='l1 l2 l3'.split()) 
s = pd.Series(range(1001, 1005), mux) 
 
s 
 
l1  l2  l3 
a   x   1     1001 
    y   2     1002 
b   y   3     1003 
c   z   3     1004 
dtype: int64 

根据documentation for unstack

fill_value : replace NaN with this value if the unstack produces missing values

当我unstack

s.unstack() 
 
l3          1       2       3 
l1 l2                         
a  x   1001.0     NaN     NaN 
   y      NaN  1002.0     NaN 
b  y      NaN     NaN  1003.0 
c  z      NaN     NaN  1004.0 

我确实得到了 NaN。
所以我尝试 fill_value=0

s.unstack(fill_value=0) 
 
l3        1     2     3 
l1 l2                   
a  x   1001     0     0 
   y      0  1002     0 
b  y      0     0  1003 
c  z      0     0  1004 

果然,NaN 中填充了 0。

但是,如果我想unstack一次多一层。

s.unstack(['l2', 'l3'], fill_value=0) 
 
l2       x       y               z 
l3       1       2       3       3 
l1                                 
a   1001.0  1002.0     NaN     NaN 
b      NaN     NaN  1003.0     NaN 
c      NaN     NaN     NaN  1004.0 

我的 fill_value 被忽略了。

为什么?什么是解决方法?

请您参考如下方法:

试试这个:

In [3]: s.unstack(['l2', 'l3']).fillna(0) 
Out[3]: 
l2       x       y               z 
l3       1       2       3       3 
l1 
a   1001.0  1002.0     0.0     0.0 
b      0.0     0.0  1003.0     0.0 
c      0.0     0.0     0.0  1004.0