Pandas: 获取多索引级别作为系列
Pandas: get multiindex level as series
我有一个多层次的数据框,例如:
idx = pd.MultiIndex.from_product((['foo', 'bar'], ['one', 'five', 'three' 'four']),
names=['first', 'second'])
df = pd.DataFrame({'A': [np.nan, 12, np.nan, 11, 16, 12, 11, np.nan]}, index=idx).dropna().astype(int)
A
first second
foo five 12
four 11
bar one 16
five 12
three 11
我想使用标题为 second
的索引级别创建一个新列,以便我得到
A B
first second
foo five 12 five
four 11 four
bar one 16 one
five 12 five
three 11 three
我可以通过重置索引、复制列,然后 re-applying 来做到这一点,但这似乎更 round-about。
我试过 df.index.levels[1]
,但这会创建一个排序列表,它不会保留顺序。
如果它是单个索引,我会使用 df.index
但在创建一列元组的多索引中。
如果在其他地方解决了这个问题,请分享,因为我在搜索 Whosebug 档案时没有任何运气。
df['B'] = idx.to_series().str[1]
df['B'] = df.index.get_level_values(level=1) # Zero based indexing.
# df['B'] = df.index.get_level_values(level='second') # This also works.
>>> df
A B
first second
foo one 12 one
two 11 two
bar one 16 one
two 12 two
three 11 three
如果您想使用索引名称(而不是数字索引)获取索引列值,我可以借用@AlbertoGarcia-Raboso 的回答。
请注意,这为您提供了一个仍然包含索引列的输出,它是一个系列,正如问题所要求的那样。这乍一看像是重复的专栏。
df.index.to_frame()['second']
(然后例如用 df.index.to_frame()['second'][8]
询问第 9 个系列项目)
我有一个多层次的数据框,例如:
idx = pd.MultiIndex.from_product((['foo', 'bar'], ['one', 'five', 'three' 'four']),
names=['first', 'second'])
df = pd.DataFrame({'A': [np.nan, 12, np.nan, 11, 16, 12, 11, np.nan]}, index=idx).dropna().astype(int)
A
first second
foo five 12
four 11
bar one 16
five 12
three 11
我想使用标题为 second
的索引级别创建一个新列,以便我得到
A B
first second
foo five 12 five
four 11 four
bar one 16 one
five 12 five
three 11 three
我可以通过重置索引、复制列,然后 re-applying 来做到这一点,但这似乎更 round-about。
我试过 df.index.levels[1]
,但这会创建一个排序列表,它不会保留顺序。
如果它是单个索引,我会使用 df.index
但在创建一列元组的多索引中。
如果在其他地方解决了这个问题,请分享,因为我在搜索 Whosebug 档案时没有任何运气。
df['B'] = idx.to_series().str[1]
df['B'] = df.index.get_level_values(level=1) # Zero based indexing.
# df['B'] = df.index.get_level_values(level='second') # This also works.
>>> df
A B
first second
foo one 12 one
two 11 two
bar one 16 one
two 12 two
three 11 three
如果您想使用索引名称(而不是数字索引)获取索引列值,我可以借用@AlbertoGarcia-Raboso 的回答。
请注意,这为您提供了一个仍然包含索引列的输出,它是一个系列,正如问题所要求的那样。这乍一看像是重复的专栏。
df.index.to_frame()['second']
(然后例如用 df.index.to_frame()['second'][8]
询问第 9 个系列项目)