Home > Blockchain >  Different ways to get unique get_level_values()
Different ways to get unique get_level_values()

Time:10-29

Consider the following DataFrame df:

df=
kind        A              B
names          a1      a2      b1      b2      b3
Time
0.0        0.7804  0.5294  0.1895  0.9195  0.0508
0.1        0.1703  0.7095  0.8704  0.8566  0.5513
0.2        0.8147  0.9055  0.0506  0.4212  0.2464
0.3        0.3985  0.4515  0.7118  0.6146  0.2682
0.4        0.2505  0.2752  0.4097  0.3347  0.1296

When I issue the command levs = df.columns.get_level_values("kind"), I get that levs is equal to

Index(['A', 'A', 'A', 'B', 'B'], dtype='object', name='kind')

whereas I would like to have that levs is equal to Index(['A', 'B'], dtype='object', name='kind').

One way to achieve such an objective could be to run levs=list(set(levs)), but I am wondering if there are any other simple methods.

CodePudding user response:

I think you can use levels:

out = df.columns.levels[0]
print (out)
Index(['A', 'B'], dtype='object')

EDIT: One idea with lookup by names of MultiIndex:

d = {v: k  for k, v in enumerate(df.columns.names)}
print (d)
{'kind': 0, 'names': 1}

out = df.columns.levels[d['kind']]
print (out)
Index(['A', 'B'], dtype='object', name='kind')
  • Related