首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pandas多索引数据帧:创建新索引或附加到现有索引

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

Stack Overflow用户
提问于 2014-01-21 17:09:00
回答 1查看 3.1K关注 0票数 1

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

代码语言:javascript
复制
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情侣。如果multi_df中已经存在new_index (组合),我想将new_id附加到现有索引。如果new_index不存在,我想创建它并添加id值。例如:

代码语言:javascript
复制
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)的语法。任何帮助都是非常受欢迎的。

附注:对于追加,我可以看到我试图添加new_id的对象是一个Series。但是,append()不起作用。

代码语言:javascript
复制
type(multi_df[('two','white','hard', 'triangular')])
<class 'pandas.core.series.Series'>
EN

回答 1

Stack Overflow用户

发布于 2014-01-21 19:41:44

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

代码语言:javascript
复制
data = pd.Series(15, index=pd.MultiIndex.from_tuples([('two','white','hard', 'triangular')]))
multi_df.append(data)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21253580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档