Python 从数据帧的多索引中获取特定索引作为列表
我想用Python 从数据帧的多索引中获取特定索引作为列表,python,pandas,numpy,dataframe,multi-index,Python,Pandas,Numpy,Dataframe,Multi Index,我想用多索引作为列表获取熊猫数据帧的特定索引 举个例子 import pandas as pd; import numpy as np np.random.seed(42) df = pd.DataFrame(np.random.randint(5, size=(5, 4)), columns=list('ABCD')) df.set_index(['A', 'B'], inplace=True) 其中df定义为 C D A B 3 4 2 4 4 1 2 2 2 4 3
多索引
作为列表获取熊猫数据帧的特定索引
举个例子
import pandas as pd; import numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.randint(5, size=(5, 4)), columns=list('ABCD'))
df.set_index(['A', 'B'], inplace=True)
其中df
定义为
C D
A B
3 4 2 4
4 1 2 2
2 4 3 2
4 1 3 1
3 4 0 3
我想提取
[4 1 4 1 4]
它对应于第二个索引
B
。如何做到这一点?此解决方案使用堆叠和切片:
np.stack(df.index.values, axis=0)[:,1]
此解决方案使用堆叠和切片:
np.stack(df.index.values, axis=0)[:,1]
使用
get\u level\u值
df.index.get_level_values(level=1).tolist()
Out[1040]: [4, 1, 4, 1, 4]
或reset\u索引
df.reset_index(level=1).B.tolist()
Out[1041]: [4, 1, 4, 1, 4]
使用
get\u level\u值
df.index.get_level_values(level=1).tolist()
Out[1040]: [4, 1, 4, 1, 4]
或reset\u索引
df.reset_index(level=1).B.tolist()
Out[1041]: [4, 1, 4, 1, 4]