如何将多个索引列与一个独立的列合并在一起

时间:2019-12-10 19:47:49

标签: python pandas

我正在尝试将两个独立列添加到多索引数据帧中。我为一栏做了: df = dataframe.join(pd.DataFrame(np.random.rand(5, 1), columns = pd.MultiIndex.from_product([['New']], index = dataframe.index))

但是我不知道这是否正确。如果正确,我可以添加另一行相同的代码吗?还是有一种蟒蛇般的方式

in the left it's what I was tried and the righ the original dataset

1 个答案:

答案 0 :(得分:0)

我认为您需要为任何条目(即也为新列)指定多级索引的所有级别。然后,您可以简单地编写:

df[('New','')] = [1,2,3,4,5]

示例:

df = pd.DataFrame(np.random.rand(5, 1), columns=pd.MultiIndex.from_tuples([('A',1)]))
df[('New1','')] = range(5)
df[('New2','')] = range(10,15)
print(df)
#          A New1 New2
#          1          
#0  0.963898    0   10
#1  0.305885    1   11
#2  0.400290    2   12
#3  0.753151    3   13
#4  0.474556    4   14