Pandas多索引数据框:创建新索引或附加到现有索引

时间:2014-01-21 09:09:00

标签: python pandas multi-index

我有一个Pandas数据框multi_df,它有一个由codecolourtextureshape值组成的多索引,如下所示:

import pandas as pd
import numpy as np
df = pd.DataFrame({'id' : range(1,9),
                    'code' : ['one', 'one', 'two', 'three',
                                'two', 'three', 'one', 'two'],
                    'colour': ['black', 'white','white','white',
                            'black', 'black', 'white', 'white'],
                    'texture': ['soft', 'soft', 'hard','soft','hard',
                                        'hard','hard','hard'],
                    'shape': ['round', 'triangular', 'triangular','triangular','square',
                                        'triangular','round','triangular'],
                    'amount' : np.random.randn(8)},  columns= ['id','code','colour', 'texture', 'shape', 'amount'])
multi_df = df.set_index(['code','colour','texture','shape']).sort_index()['id']
multi_df
code   colour  texture  shape     
one    black   soft     round         1
       white   hard     round         7
               soft     triangular    2
three  black   hard     triangular    6
       white   soft     triangular    4
two    black   hard     square        5
       white   hard     triangular    3
                        triangular    8
Name: id, dtype: int64

我获得了new index - new_id对。如果new_index中已存在multi_df(组合),我想将new_id附加到现有索引。如果new_index不存在,我想创建它并添加id值。例如:

new_id = 15
new_index = ('two','white','hard', 'triangular')
if new_index in multi_df.index:
    # APPEND TO EXISTING: multi_df[('two','white','hard', 'triangular')].append(new_id)
else:
    # CREATE NEW index and put the new_id in.

但是,我无法弄清楚附加(IF)或创建(ELSE)新索引的语法。任何帮助都是最受欢迎的。

P.S:为了追加我可以看到我尝试添加new_id的对象是Series。但是,append()不起作用..

type(multi_df[('two','white','hard', 'triangular')])
<class 'pandas.core.series.Series'>

1 个答案:

答案 0 :(得分:2)

append()每次创建一个新系列,所以如果你需要在for循环中调用它,它会非常慢:

data = pd.Series(15, index=pd.MultiIndex.from_tuples([('two','white','hard', 'triangular')]))
multi_df.append(data)