【问题标题】:Pandas combinations of Dataframe and series数据框和系列的熊猫组合
【发布时间】:2018-07-23 01:35:36
【问题描述】:

我有一个数据框:

df = pd.DataFrame({
    'A': [1,2,3,4],
    'B': [12,23,34,45]
})

看起来像

----------------------------
index         A        B
0             1       12
1             2       23
2             3       34
3             4       45
-----------------------------

我有很多时间,[0,1,2]。我想让df每次都复制A行和B行:

------------------------------------
index         A        B     time
              1       12       0
              1       12       1
              1       12       2
              2       23       0
              2       23       1
              2       23       2
              3       34       0
              3       34       1
              3       34       2
              4       45       0
              4       45       1
              4       45       2
-------------------------------------

我不想使用 MultiIndex 或 Stack(因为我希望它尽可能平坦)。结合没有帮助。我没有加入,因为我正在尝试进行组合,所以合并/连接似乎没有帮助。

【问题讨论】:

    标签: python pandas combinations


    【解决方案1】:

    也许使用pd.concatreindex 稍快

    pd.concat([df]*len([0,1,2])).sort_index().assign(time=[0,1,2]*len(df))
    Out[275]: 
       A   B  time
    0  1  12     0
    0  1  12     1
    0  1  12     2
    1  2  23     0
    1  2  23     1
    1  2  23     2
    2  3  34     0
    2  3  34     1
    2  3  34     2
    3  4  45     0
    3  4  45     1
    3  4  45     2
    

    【讨论】:

    • @RafaelC 感谢您分享时间 :-) 投票给你 :-)
    【解决方案2】:

    IIUC,使用reindex +repeat

    o = df.shape[0]
    df = df.reindex(df.index.repeat(len(times))).reset_index(drop=True)
    df['time'] = times*o
    
        A   B   time
    0   1   12  0
    1   1   12  1
    2   1   12  2
    3   2   23  0
    4   2   23  1
    5   2   23  2
    6   3   34  0
    7   3   34  1
    8   3   34  2
    9   4   45  0
    10  4   45  1
    11  4   45  2
    

    性能检查:

    %timeit df.reindex(df.index.repeat(len(times))).reset_index(drop=True).assign(time=times*df.shape[0])
    675 µs ± 12.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    %timeit pd.concat([df]*len([0,1,2])).sort_index().assign(time=[0,1,2]*len(df))
    812 µs ± 6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    对于小的dfs,和

    %timeit df.reindex(df.index.repeat(len(times))).reset_index(drop=True).assign(time=times*df.shape[0])
    237 ms ± 3.68 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
    %timeit pd.concat([df]*len([0,1,2])).sort_index().assign(time=[0,1,2]*len(df))
    5.78 ms ± 27 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    对于大 dfs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 2016-10-03
      • 2017-07-08
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多