【问题标题】:Keystroke-efficient way to create new columns in pandas在 Pandas 中创建新列的高效击键方式
【发布时间】:2017-01-21 20:40:20
【问题描述】:

有没有比初始化为零的pandas数据框df中创建多个新列更有效的方法:

for col in add_cols:
   df.loc[:, col] = 0

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    更新:使用@jeff's method,但动态执行:

    In [208]: add_cols = list('xyz')
    
    In [209]: df.assign(**{i:0 for i in add_cols})
    Out[209]:
       a  b  c  x  y  z
    0  4  8  6  0  0  0
    1  3  7  0  0  0  0
    2  4  0  1  0  0  0
    3  5  4  5  0  0  0
    4  1  3  0  0  0  0
    

    旧答案:

    另一种方法:

    df[add_cols] = pd.DataFrame(0, index=df.index, columns=add_cols)
    

    演示:

    In [343]: df = pd.DataFrame(np.random.randint(0, 10, (5,3)), columns=list('abc'))
    
    In [344]: add_cols = list('xyz')
    
    In [345]: add_cols
    Out[345]: ['x', 'y', 'z']
    
    In [346]: df
    Out[346]:
       a  b  c
    0  4  9  0
    1  1  1  1
    2  8  8  1
    3  0  1  4
    4  8  5  6
    
    In [347]: df[add_cols] = pd.DataFrame(0, index=df.index, columns=add_cols)
    
    In [348]: df
    Out[348]:
       a  b  c  x  y  z
    0  4  9  0  0  0  0
    1  1  1  1  0  0  0
    2  8  8  1  0  0  0
    3  0  1  4  0  0  0
    4  8  5  6  0  0  0
    

    【讨论】:

    • 啊,我认为这是最接近我想要的。它仍然可以说不是很好的语法。
    【解决方案2】:
    In [13]: df = pd.DataFrame(np.random.randint(0, 10, (5,3)), columns=list('abc'))
    
    In [14]: df
    Out[14]: 
       a  b  c
    0  7  2  3
    1  7  0  7
    2  5  1  5
    3  9  1  4
    4  2  1  4
    
    In [15]: df.assign(x=0, y=0, z=0)
    Out[15]: 
       a  b  c  x  y  z
    0  7  2  3  0  0  0
    1  7  0  7  0  0  0
    2  5  1  5  0  0  0
    3  9  1  4  0  0  0
    4  2  1  4  0  0  0
    

    【讨论】:

      【解决方案3】:

      这是一个技巧:

      [df.insert(0, col, 0) for col in add_cols]
      

      【讨论】:

        【解决方案4】:

        您可以使用类似 dict 的语法来处理 DataFrame:

        for col in add_cols:
            df[col] = 0
        

        【讨论】:

          猜你喜欢
          • 2022-01-23
          • 1970-01-01
          • 1970-01-01
          • 2016-05-24
          • 1970-01-01
          • 2023-02-23
          • 2018-01-23
          • 2021-09-11
          • 1970-01-01
          相关资源
          最近更新 更多