2015-11-04 97 views
3

当数据框是多索引时,是否可以在熊猫中创建多个新列?我想在bar2超列下添加两个新列onetwo。是这样的...在多索引熊猫数据框中创建多个新列

import pandas as pd 
import numpy as np 
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo'], 
      ['one', 'two', 'one', 'two', 'one', 'two']] 

index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second']) 
df = pd.DataFrame(np.random.randn(3, 6), index=[1, 2, 3], columns=index) 

df["bar2", ["one", "two"]] = np.random.randn(3, 2) 

我知道我可以使用

df["bar2", "one"] = np.random.randn(3,1) 
df["bar2", "two"] = np.random.randn(3,1) 

有没有同时进行这两项可以更快地创建逐一?

回答

1
In [270]: 
df_to_add = pd.DataFrame(np.random.randn(3,2) , columns=[['bar2' , 'bar2'] , ['one' , 'two']] , index = [1 , 2 , 3]) 
df_to_add 
Out[270]: 
      bar2 
     one two 
1 0.119730 -0.265579 
2 1.777329 -1.178128 
3 -2.700409 0.457430 

In [271]:  
pd.concat([df , df_to_add] , axis = 1) 
+0

这是错综复杂的,但它的工作原理,这是我所需要的。希望他们将来能够做到这一点。 – tlnagy