如何设置二级多指标系列的所有值?
How to set all values of second level multi-index series?
我有一个带有 2 级多索引的 pandas 系列,我想为一个新的 2 级索引创建条目,所有索引的值都相同。让我举例说明:
import pandas as pd
import numpy as np
arrays = [
np.array(["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"]),
np.array(["one", "two", "one", "two", "one", "two", "one", "two"]),
]
s = pd.Series(np.random.randn(8), index=arrays)
print(s)
产生:
bar one 0.636008
two 0.092757
baz one 0.536576
two -0.135340
foo one 0.095891
two -0.470991
qux one -1.766848
two -1.707228
dtype: float64
我现在如何继续使用二级索引创建一个新条目 three
并将它们全部设置为 0
而无需遍历一级索引。
s.loc[(slice(None), 'three')] = 0
是我的第一次尝试,但没有成功。
a, b = s.index.levels
output = s.reindex(pd.MultiIndex.from_product([a, [*b, 'three']]))
>>> output
bar one -0.398786
two -0.827197
three NaN
baz one -0.415745
two -0.524512
three NaN
foo one 0.813101
two -0.229251
three NaN
qux one 2.161717
two -0.956931
three NaN
一行:
output = s.reindex(pd.MultiIndex.from_product([s.index.levels[0], [*s.index.levels[1], "three"]]))
我们可以 unstack
将系列重塑为数据框,然后 assign
列和 stack
返回以创建多索引系列
s.unstack().assign(three=0).stack()
bar one -0.124601
two 0.239437
three 0.000000
baz one -1.876396
two -0.155882
three 0.000000
foo one -0.134201
two 0.959334
three 0.000000
qux one 0.730565
two 0.119879
three 0.000000
dtype: float64
我有一个带有 2 级多索引的 pandas 系列,我想为一个新的 2 级索引创建条目,所有索引的值都相同。让我举例说明:
import pandas as pd
import numpy as np
arrays = [
np.array(["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"]),
np.array(["one", "two", "one", "two", "one", "two", "one", "two"]),
]
s = pd.Series(np.random.randn(8), index=arrays)
print(s)
产生:
bar one 0.636008
two 0.092757
baz one 0.536576
two -0.135340
foo one 0.095891
two -0.470991
qux one -1.766848
two -1.707228
dtype: float64
我现在如何继续使用二级索引创建一个新条目 three
并将它们全部设置为 0
而无需遍历一级索引。
s.loc[(slice(None), 'three')] = 0
是我的第一次尝试,但没有成功。
a, b = s.index.levels
output = s.reindex(pd.MultiIndex.from_product([a, [*b, 'three']]))
>>> output
bar one -0.398786
two -0.827197
three NaN
baz one -0.415745
two -0.524512
three NaN
foo one 0.813101
two -0.229251
three NaN
qux one 2.161717
two -0.956931
three NaN
一行:
output = s.reindex(pd.MultiIndex.from_product([s.index.levels[0], [*s.index.levels[1], "three"]]))
我们可以 unstack
将系列重塑为数据框,然后 assign
列和 stack
返回以创建多索引系列
s.unstack().assign(three=0).stack()
bar one -0.124601
two 0.239437
three 0.000000
baz one -1.876396
two -0.155882
three 0.000000
foo one -0.134201
two 0.959334
three 0.000000
qux one 0.730565
two 0.119879
three 0.000000
dtype: float64