【发布时间】:2020-01-20 17:35:34
【问题描述】:
我有一个多索引系列如下。
> data = [['a', 'X', 'u', 1], ['a', 'X', 'v', 2], ['b', 'Y', 'u', 4], ['a', 'Z', 'u', 20]]
> s = pd.DataFrame(data, columns='one two three four'.split()).set_index('one two three'.split()).four
> s
one two three
a X u 1
v 2
b Y u 4
a Z u 20
Name: four, dtype: int64
然后是第二个系列,只有 one 和 three 作为索引:
>>> data2 = [['a', 'u', 3], ['a', 'v', -3]]
>>> s2 = pd.DataFrame(data2, columns='one three four'.split()).set_index('one three'.split()).four
>>> s2
one three
a u 3
v -3
Name: four, dtype: int64
所以,据我所知,s2 和 s.loc[pd.IndexSlice[:, 'X', :]] 的索引相同。
因此,我希望能够做到:
>>> s.loc[pd.IndexSlice[:, 'X', :]] = s2
但这样做会产生NaN 值:
>>> s
one two three
a X u NaN
v NaN
b Y u 4.0
a Z u 20.0
Name: four, dtype: float64
这样做的正确方法是什么?
【问题讨论】:
-
为什么评论者删除了 s2.values 评论?
-
@ScottBoston 索引对齐。
-
@QuangHoang 真...真的。
-
索引对齐可以通过
sort_index解决。但我想这不是问题的重点。
标签: python pandas multi-index