gpt4 book ai didi

python - 尽管索引匹配,但 pd.IndexSlice 的 pd.Series 赋值会导致 NaN 值

转载 作者:太空狗 更新时间:2023-10-30 00:08:43 29 4
gpt4 key购买 nike

我有一个多索引系列,如下所示。

> 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

然后是第二个系列,只有 onethree 作为索引:

>>> 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

因此,据我所知,s2s.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

正确的做法是什么?

最佳答案

pandas MultiIndexes 有时会有点问题,这就是其中一种情况。如果您修改 s2.index 以匹配 s.index,则分配有效:

In [155]: s2.index = pd.MultiIndex.from_product([['a'], ['X'], ['u', 'v']], names=['one', 'two', 'three'])

In [156]: s2
Out[156]:
one two three
a X u 3
v -3
Name: four, dtype: int64

In [157]: s
Out[157]:
one two three
a X u 1
v 2
b Y u 4
a Z u 20
Name: four, dtype: int64

In [158]: s.loc[:, 'X', :] = s2

In [159]: s
Out[159]:
one two three
a X u 3
v -3
b Y u 4
a Z u 20
Name: four, dtype: int64

可能值得在 https://github.com/pandas-dev/pandas/issues 中搜索类似问题并将其添加为新的(如果尚不存在)。

与此同时,另一个选择是使用 .unstack() reshape 数据以完成分配:

In [181]: s = s.unstack('two')

In [182]: s['X'].loc[s2.index] = s2

In [183]: s.stack().swaplevel(1,2).sort_index()
Out[183]:
one two three
a X u 3.0
v -3.0
Z u 20.0
b Y u 4.0
dtype: float64

关于python - 尽管索引匹配,但 pd.IndexSlice 的 pd.Series 赋值会导致 NaN 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58015162/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com