python - Pandas 多索引数据帧 : creating new index or appending to existing index

标签 python pandas multi-index

我有一个 Pandas 数据框 multi_df,它具有由 codecolourtexture< 组成的多重索引shape 值如下:

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_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'>

最佳答案

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

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

关于python - Pandas 多索引数据帧 : creating new index or appending to existing index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21253580/

相关文章:

python - Haystack Whoosh 拼写建议太贪婪

python - 如何使用 Pandas 加速加载数据?

python - pandas - 根据变量将值添加到带标题的列中到 multiindex (标题)中

python - Jaccard 文本行之间的相似度 Apache Spark

python - 默认的 django 日志记录设置在哪里?

python - 无法解析 Yahoo Finance API JSON 数据?包含代码(Python Flask)

python - pandas 基于索引 vs ix 丢弃行

python - 从嵌套字典中的值构造数据框

python - 多索引 Pandas 数据框到字典

python - Pandas Multiindex 数据框删除行