【问题标题】:Creating multiple new columns in a multiindexed pandas dataframe在多索引熊猫数据框中创建多个新列
【发布时间】:2016-02-05 11:15:17
【问题描述】:

当数据框被多索引时,是否可以在 Pandas 中创建多个新列?我想在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)

有没有更快的方法同时做这两件事?

【问题讨论】:

    标签: python pandas dataframe multi-index


    【解决方案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)
    

    【讨论】:

    • 这很复杂,但它确实有效,这正是我所需要的。希望他们在未来让这一切变得更简单。
    猜你喜欢
    • 2016-06-16
    • 2020-11-21
    • 2016-01-13
    • 2015-03-22
    • 2017-05-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多