【问题标题】:pandas : efficiently multiplay row based on conditionpandas:根据条件有效地进行多行播放
【发布时间】:2016-04-21 16:02:34
【问题描述】:

我正在尝试根据条件列在DataFrame 中乘以一行。

例如,当条件列中的值为2时,我想用两个相同的行替换该行并将每个新行中的条件设置为1。

示例数据框:

df = pd.DataFrame({'k': ['K0', 'K1', 'K1', 'K2'],
              'condition': [1, 1, 3, 2],
              's': ['a', 'b', 'c', 'd']})


    condition   k  s
            1  K0  a
            1  K1  b
            3  K1  c
            2  K2  d 

想要的结果:

  condition   k  s
          1  K0  a
          1  K1  b
          1  K1  c
          1  K1  c
          1  K1  c  
          1  K2  d
          1  K2  d  

这个操作能否有效地完成inplace,而不创建一个临时的df

【问题讨论】:

    标签: python-2.7 pandas


    【解决方案1】:

    更快的是使用locnp.repeat

    df = df.loc[np.repeat(df.index.values,df.condition)].reset_index(drop=True)
    df['condition'] = 1
    print df
       condition   k  s
    0          1  K0  a
    1          1  K1  b
    2          1  K1  c
    3          1  K1  c
    4          1  K1  c
    5          1  K2  d
    6          1  K2  d
    

    另一种解决方案是groupbyconcat,最后在condition1 列中设置值,但速度较慢:

    df = df.groupby('condition', as_index=False, sort=False)
            .apply(lambda x: pd.concat([x]*x.condition.values[0], ignore_index=True))
            .reset_index(drop=True)
    df['condition'] = 1
    print df
       condition   k  s
    0          1  K0  a
    1          1  K1  b
    2          1  K1  c
    3          1  K1  c
    4          1  K1  c
    5          1  K2  d
    6          1  K2  d
    

    时间安排

    In [917]: %timeit df.loc[np.repeat(df.index.values,df.condition)].reset_index(drop=True)
    The slowest run took 4.55 times longer than the fastest. This could mean that an intermediate result is being cached 
    1000 loops, best of 3: 1.04 ms per loop
    
    In [918]: %timeit df.groupby('condition', as_index=False, sort=False).apply(lambda x: pd.concat([x]*x.condition.values[0], ignore_index=True)).reset_index(drop=True)
    100 loops, best of 3: 7.78 ms per loop
    

    【讨论】:

    • 谢谢@jezrael,我喜欢你的解决方案。根据第二个变体,我同意你的看法,groupby 看起来更慢
    猜你喜欢
    • 2020-10-27
    • 2022-01-13
    • 1970-01-01
    • 2022-11-15
    • 2016-09-22
    • 2020-08-11
    • 1970-01-01
    • 2021-10-31
    • 2017-08-20
    相关资源
    最近更新 更多