通过使用新的多索引重复一行来创建 pandas 数据框

Create pandas dataframe by repeating one row with new multiindex

在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

使用 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

使用[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

您可以将 numpy.repeat with numpy.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