1
我有熊猫数据帧,multi_df
,其具有由code
,colour
,texture
和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 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'>
谢谢你,是那么可以使用'append()'方法吗? – Rhubarb
你能详细解释一下你想做什么吗?数据来自哪里,你想要什么样的数据处理? – HYRY