【问题标题】:Get non sorted column levels in pandas dataframe with multiIndex使用 multiIndex 在 pandas 数据框中获取未排序的列级别
【发布时间】:2020-11-05 19:32:51
【问题描述】:

背景:

我有一个带有 MultiIndex 的 pandas 数据框。

我想得到未排序的 columns.levels。​​

df.column.levels 将它们提供给我,但已排序。

示例:

worms=['worm1', 'worm2', 'worm3']
bodyparts=['head', 'vulva', 'tail']
coords=['x', 'y']
arrays=pd.MultiIndex.from_product([worms, bodyparts, coords],

                           names=['worms', 'bodyparts', 'coords'])


idx = pd.Index(np.arange(0,5000),name='frames')
df=pd.DataFrame(index=idx, columns=arrays)

看起来像这样:

worms   worm1   worm2   worm3
bodyparts   head    vulva   tail    head    vulva   tail    head    vulva   tail
coords  x   y   x   y   x   y   x   y   x   y   x   y   x   y   x   y   x   y
frames                                                                      
0   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
1   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN

现在如果我这样做:

df.columns.levels[1]

我明白了:

Index(['head', 'tail', 'vulva'], dtype='object', name='bodyparts')

我想要什么:

Index(['head', 'vulva', 'tail'], dtype='object', name='bodyparts')

有什么选择吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这会按出现顺序为您提供它们:

    pd.unique(df.columns.to_frame()['bodyparts'])
    

    输出:['head' 'vulva' 'tail']

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 2016-03-05
      • 2020-02-15
      • 1970-01-01
      • 2020-02-14
      • 2018-11-18
      • 2018-02-20
      • 2018-06-24
      相关资源
      最近更新 更多