2
我与多指数大熊猫系列如下:追加一个级别(具有固定值)到大熊猫系列/数据帧
import pandas as pd
import numpy as np
idx = pd.MultiIndex.from_product([['A','C'],range(5)], names=['category_1','number'])
np.random.seed(0)
s = pd.Series(index=idx, data = np.random.randn(len(idx)))
I:
category_1 number
A 0 1.764052
1 0.400157
2 0.978738
3 2.240893
4 1.867558
C 0 -0.977278
1 0.950088
2 -0.151357
3 -0.103219
4 0.410599
它是从这个代码生成想添加另一个级别,称为category_2
以具有固定值的索引(即D
)得到以下结果:
category_1 category_2 number
A D 0 1.764052
1 0.400157
2 0.978738
3 2.240893
4 1.867558
C D 0 -0.977278
1 0.950088
2 -0.151357
3 -0.103219
4 0.410599
我一直用这个哈克的方式做到这一点:
df =s.to_frame('dummy')
df['category_2'] = 'D'
df.set_index('category_2', append = True, inplace = True)
df = df.reorder_levels([0,2,1])
res = df['dummy']
有没有更好的(更简洁/ Python化)的方式来增加固定值来对大熊猫系列/数据框中现有水平的水平?
谢谢,另一种方法是使用from_product:s.index = pd.MultiIndex.from_product([s.inde x.levels [0],'D',s.index.levels [1]],names = ['c1','c2','number']) – motam79
不错,对我来说's.index = pd。 MultiIndex.from_product([s.index.levels [0],['D'],s.index.levels [1]],names = ['c1','c2','number'])' – jezrael