Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有NaN的两个多指标序列的和_Python_Pandas - Fatal编程技术网

Python 具有NaN的两个多指标序列的和

Python 具有NaN的两个多指标序列的和,python,pandas,Python,Pandas,我想添加两个具有多个索引的系列,其中一个可以包含NaN值。仅仅将两者相加(a+b)是行不通的,因为a中的某些索引项可能不在b中,反之亦然 这是我当前的方法,对于索引(b,50),它失败了,因为这个值应该是NaN In [41]: a = pd.Series([1, 2, 3, np.nan, np.nan], index=pd.MultiIndex.from_tuples([('a', '1'), ('a', 2), ('b', 1), ('b', 50), ('b', 5)], names=[

我想添加两个具有多个索引的系列,其中一个可以包含NaN值。仅仅将两者相加(a+b)是行不通的,因为
a
中的某些索引项可能不在
b
中,反之亦然

这是我当前的方法,对于索引
(b,50)
,它失败了,因为这个值应该是NaN

In [41]: a = pd.Series([1, 2, 3, np.nan, np.nan], index=pd.MultiIndex.from_tuples([('a', '1'), ('a', 2), ('b', 1), ('b', 50), ('b', 5)], names=['x', 'y']))
In [42]: b = pd.Series([4, 5, 6], index=pd.MultiIndex.from_tuples([('a', '1'), ('a', 3), ('b', 5)], names=['x', 'y']))
In [43]: c = pd.Series(0, index=a.index.union(b.index))
In [44]: c[a[a.notnull()].index] = a[a.notnull()]
In [45]: c
Out[45]: 
x  y 
a  2     2.0
   3     0.0
   1     1.0
b  1     3.0
   5     0.0
   50    0.0
dtype: float64

In [46]: c[b.index] += b

In [47]: c
Out[47]: 
x  y 
a  2     2.0
   3     5.0
   1     5.0
b  1     3.0
   5     6.0
   50    0.0
dtype: float64

In [48]: c[a.isnull() & b.isnull()] = np.NaN

In [49]: c
Out[49]: 
x  y 
a  2     2.0
   3     5.0
   1     5.0
b  1     3.0
   5     6.0
   50    0.0
dtype: float64

IIUC,这是你需要的吗

a.add(b,fill_value=0)
Out[398]: 
x  y 
a  1     5.0
   2     2.0
b  1     3.0
   50    NaN
   5     6.0
a  3     5.0
dtype: float64

IIUC,这是你需要的吗

a.add(b,fill_value=0)
Out[398]: 
x  y 
a  1     5.0
   2     2.0
b  1     3.0
   50    NaN
   5     6.0
a  3     5.0
dtype: float64

可以先对齐两个系列

s1, s2 = a.align(b)
s = s1.fillna(0) + s2.fillna(0) 
s[s1.isna() & s2.isna()] = np.nan

# output of s
x  y 
a  1     5.0
   2     2.0
b  1     3.0
   50    NaN
   5     6.0
a  3     5.0
dtype: float64

可以先对齐两个系列

s1, s2 = a.align(b)
s = s1.fillna(0) + s2.fillna(0) 
s[s1.isna() & s2.isna()] = np.nan

# output of s
x  y 
a  1     5.0
   2     2.0
b  1     3.0
   50    NaN
   5     6.0
a  3     5.0
dtype: float64
太容易了;-)谢谢。@orange yw~:-)快乐编码太容易了;-)谢谢。@orange yw~:-)编码愉快