Python 多级柱和;规则列
创建具有多级列的数据帧非常简单,如下所示:Python 多级柱和;规则列,python,pandas,Python,Pandas,创建具有多级列的数据帧非常简单,如下所示: import numpy as np import pandas as pd dat = np.random.randn(5, 4) header = pd.MultiIndex.from_product([['Truck','Car'], ['Speed','Position']], names=['',
import numpy as np
import pandas as pd
dat = np.random.randn(5, 4)
header = pd.MultiIndex.from_product([['Truck','Car'],
['Speed','Position']],
names=['',''])
df2 = pd.DataFrame(dat, columns=header)
得到
但是,我需要一个如下表(添加年龄列)。使用熊猫可以吗
始终需要
多索引
,对于某些级别,可以使用空字符串,例如:
df2[('', 'Age')] = np.random.randn(5)
print (df2)
Truck Car
Speed Position Speed Position Age
0 1.224236 -0.545658 0.906748 -0.982617 -0.654448
1 -0.633162 0.825520 -1.284497 -0.347309 -0.672104
2 -1.077761 0.972575 0.412191 -0.132086 0.870368
3 -0.673351 1.222222 -0.926413 1.424994 1.003245
4 -0.124790 0.705492 0.719548 0.141464 -0.366450
print (df2.columns)
MultiIndex([('Truck', 'Speed'),
('Truck', 'Position'),
( 'Car', 'Speed'),
( 'Car', 'Position'),
( '', 'Age')],
)
如果在最新版本中传递单列,请将第二级转换为空字符串:
df2['Age'] = np.random.randn(5)
print (df2)
Truck Car Age
Speed Position Speed Position
0 1.128052 0.792584 -1.750842 -0.808869 -1.330033
1 -1.412602 -0.803010 0.798280 1.755996 1.261033
2 -0.075504 0.420177 0.156556 -0.056861 -0.648126
3 -0.538234 0.901387 0.224944 1.277788 2.245300
4 0.629269 0.361891 3.638726 -1.201221 -1.012394
print (df2.columns)
MultiIndex([('Truck', 'Speed'),
('Truck', 'Position'),
( 'Car', 'Speed'),
( 'Car', 'Position'),
( 'Age', '')],
)