我有一个熊猫数据框:
a=[1,1,1,2,2,2,3,3,3]
dic={'A':a}
df=pd.DataFrame(dic)
我对此df应用了多索引:
index=[(1,'a'),(1,'b'),(1,'c'),(2,'a'),(2,'b'), (2, 'c'),(3,'a'),(3,'b'), (3,'c')]
df.index=pd.MultiIndex.from_tuples(index, names=['X','Y'])
我添加了一个新列:
df['B']='-'
现在我有一个df:
A B
X Y
1 a 1 -
b 1 -
c 1 -
2 a 2 -
b 2 -
c 2 -
3 a 3 -
b 3 -
c 3 -
本质上,我想循环遍历多索引的level ='X',将一个级别添加到另一级别,然后将值分配给column ='B'
这是我正在考虑的方法:
dex=[]
for idx, select_df in df.groupby(level=0):
dex.append(idx)
#gives me a list of level='X' keys
dex_iter=iter(dex)
#creates an iterator from that list
last=next(dex_iter)
#gives me the first value of that list of keys, and moves the iterator to the next value
for i in dex_iter:
df.loc[i,'B']=df.loc[i,'A']+df.loc[last,'A']
last=i
我的期望结果是:
A B
X Y
1 a 1 -
b 1 -
c 1 -
2 a 2 3
b 2 3
c 2 3
3 a 3 5
b 3 5
c 3 5
相反,我得到的是:
A B
X Y
1 a 1 -
b 1 -
c 1 -
2 a 2 NaN
b 2 NaN
c 2 NaN
3 a 3 NaN
b 3 NaN
c 3 NaN
这显然是由于将值分配给多索引有些特殊性。但是我找不到解决此问题的方法。
答案 0 :(得分:1)
让我们尝试groupby
,first
和shift
:
df.groupby(level=0)['A'].first().shift()
X
1 NaN
2 1.0
3 2.0
Name: A, dtype: float64
tmp = df.index.get_level_values(0).map(df.groupby(level=0)['A'].first().shift())
print (tmp)
# Float64Index([
# nan, nan, nan, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0], dtype='float64', name='X')
这将为您提供添加到“ A”以获得“ B”所需的值:
df['B'] = df['A'] + tmp
df
A B
X Y
1 a 1 NaN
b 1 NaN
c 1 NaN
2 a 2 3.0
b 2 3.0
c 2 3.0
3 a 3 5.0
b 3 5.0
c 3 5.0