创建一个空的MultiIndex

dmv*_*nna 21 python multi-index pandas

我想在为其分配行之前使用MultiIndex创建一个空的 DataFrame.我已经发现空DataFrames不喜欢动态分配MultiIndexes,所以我在创建过程中设置MultiIndex 名称.但是,我不想分配级别,因为这将在以后完成.这是我到目前为止最好的代码:

def empty_multiindex(names):
    """
    Creates empty MultiIndex from a list of level names.
    """
    return MultiIndex.from_tuples(tuples=[(None,) * len(names)], names=names)
Run Code Online (Sandbox Code Playgroud)

哪能给我

In [2]:

empty_multiindex(['one','two', 'three'])

Out[2]:

MultiIndex(levels=[[], [], []],
           labels=[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]],
           names=[u'one', u'two', u'three'])
Run Code Online (Sandbox Code Playgroud)

In [3]:
DataFrame(index=empty_multiindex(['one','two', 'three']))

Out[3]:
one two three
NaN NaN NaN
Run Code Online (Sandbox Code Playgroud)

好吧,我对这些NaN毫无用处.我可以在以后轻松放弃它们,但这显然是一个hackish解决方案.谁有更好的?

RoG*_*RoG 29

解决方案是省略标签.这对我来说很好:

>>> my_index = pd.MultiIndex(levels=[[],[],[]],
                             labels=[[],[],[]],
                             names=[u'one', u'two', u'three'])
>>> my_index
MultiIndex(levels=[[], [], []],
           labels=[[], [], []],
           names=[u'one', u'two', u'three'])
>>> my_columns = [u'alpha', u'beta']
>>> df = pd.DataFrame(index=my_index, columns=my_columns)
>>> df
Empty DataFrame
Columns: [alpha, beta]
Index: []
>>> df.loc[('apple','banana','cherry'),:] = [0.1, 0.2]
>>> df
                    alpha beta
one   two    three            
apple banana cherry   0.1  0.2
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!

  • @buechel 在 0.25.1 中关键字 `labels` 已被替换为 `codes` (7认同)
  • 如果需要,`[[],[],[]]` 可以替换为 `[[]]*3`。 (3认同)

Jea*_*aul 16

另一个可能更简单的解决方案是使用该功能set_index:

>>> import pandas as pd
>>> df = pd.DataFrame(columns=['one', 'two', 'three', 'alpha', 'beta'])
>>> df = df.set_index(['one', 'two', 'three'])
>>> df
Empty DataFrame
Columns: [alpha, beta]
Index: []
>>> df.loc[('apple','banana','cherry'),:] = [0.1, 0.2]
>>> df
                    alpha beta
one   two    three            
apple banana cherry   0.1  0.2
Run Code Online (Sandbox Code Playgroud)


ron*_*kov 15

使用 pd.MultiIndex.from_tuples 可能更简单。

import pandas as pd
ind = pd.MultiIndex.from_tuples([], names=(u'one', u'two', u'three'))
df = pd.DataFrame(columns=['alpha', 'beta'], index=ind)
df.loc[('apple','banana','cherry'), :] = [4, 3]
df

                      alpha beta
one     two     three       
apple   banana  cherry    4    3
Run Code Online (Sandbox Code Playgroud)