【问题标题】:Create pandas dataframe by repeating one row with new multiindex通过使用新的多索引重复一行来创建熊猫数据框
【发布时间】:2017-06-21 03:53:54
【问题描述】:

在 Pandas 中,我有一个系列和一个多索引:

s = pd.Series([1,2,3,4], index=['w', 'x', 'y', 'z'])
idx = pd.MultiIndex.from_product([['a', 'b'], ['c', 'd']])

对我来说,创建一个以 idx 作为索引、以 s 作为每一行的值、将 S 中的索引保留为列的 DataFrame 的最佳方法是什么?

df =
       w   x   y   z
a  c   1   2   3   4
   d   1   2   3   4
b  c   1   2   3   4
   d   1   2   3   4

【问题讨论】:

    标签: pandas dataframe creation


    【解决方案1】:

    使用pd.DataFrame 构造函数,后跟assign

    pd.DataFrame(index=idx).assign(**s)
    
         w  x  y  z
    a c  1  2  3  4
      d  1  2  3  4
    b c  1  2  3  4
      d  1  2  3  4
    

    【讨论】:

    • 这是一个非常聪明的解决方案!
    • 这非常有趣。我唯一要注意的是assign 根据其索引对s 的顺序进行了洗牌(请参阅documentation 中的注释部分)。因此,如果索引名称改为['w', 'x', 'y', 'a'],则a 列将跳转到前面。但这对我来说没关系。
    【解决方案2】:

    您可以将numpy.repeatnumpy.ndarray.reshape 一起用于重复数据和最后一个DataFrame 构造函数:

    arr = np.repeat(s.values, len(idx)).reshape(-1, len(idx))
    df = pd.DataFrame(arr, index=idx, columns=s.index)
    print (df)
         w  x  y  z
    a c  1  1  1  1
      d  2  2  2  2
    b c  3  3  3  3
      d  4  4  4  4
    

    时间安排

    np.random.seed(123)
    s = pd.Series(np.random.randint(10, size=1000))
    s.index = s.index.astype(str)
    idx = pd.MultiIndex.from_product([np.random.randint(10, size=250), ['a','b','c', 'd']])
    
    In [32]: %timeit (pd.DataFrame(np.repeat(s.values, len(idx)).reshape(len(idx), -1), index=idx, columns=s.index))
    100 loops, best of 3: 3.94 ms per loop
    
    In [33]: %timeit (pd.DataFrame(index=idx).assign(**s))
    1 loop, best of 3: 332 ms per loop
    
    In [34]: %timeit pd.DataFrame([s]*len(idx),idx,s.index)
    10 loops, best of 3: 82.9 ms per loop
    

    【讨论】:

    • 谢谢!我从您对这个(和其他)问题的回答中学到了很多东西,即 Pandas 中的速度和句法本地化之间存在权衡。我现在明白了,如果我可以更频繁地使用 numpy,我的速度就会提高!
    • 是的,如果性能不重要,所有解决方案都很好,祝你好运!
    【解决方案3】:

    使用[s]*len(s)作为数据,idx作为索引,s.index作为列来重构一个df。

    pd.DataFrame([s]*len(s),idx,s.index)
    Out[56]: 
         w  x  y  z
    a c  1  2  3  4
      d  1  2  3  4
    b c  1  2  3  4
      d  1  2  3  4
    

    【讨论】:

    • 这只是巧合,因为len(s) == len(idx)。尝试s = pd.Series([0,1,2,3,4], index=['v', 'w', 'x', 'y', 'z']) 失败。你想要这个 pd.DataFrame([s]*len(idx),idx,s.index)
    猜你喜欢
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 2015-06-13
    • 2021-08-14
    • 2016-01-13
    • 1970-01-01
    • 2015-02-22
    • 2020-10-31
    相关资源
    最近更新 更多