2014-01-21 66 views
1

我有熊猫数据帧,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。然而,追加()不工作..

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

回答

2

append()创建一个新的系列中的每一次,所以它的速度很慢,如果你需要在调用这个for循环:

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

谢谢你,是那么可以使用'append()'方法吗? – Rhubarb

+0

你能详细解释一下你想做什么吗?数据来自哪里,你想要什么样的数据处理? – HYRY