Pandas: How do I repeat dataframe for each value in a series?

dataframe, merge, numpy, pandas, python

Solution

Using numpy, lets say you have series and df of diffenent lengths

s= pd.Series(['X', 'Y', 'Z', 'A']) #added a character to s to make it length 4
s_n = len(s)
df_n = len(df)
pd.DataFrame(np.repeat(df.values,s_n, axis = 0), columns = df.columns, index = np.tile(s,df_n)).rename_axis('S').reset_index()

    S   A   B
0   X   1   a
1   Y   1   a
2   Z   1   a
3   A   1   a
4   X   2   b
5   Y   2   b
6   Z   2   b
7   A   2   b
8   X   3   c
9   Y   3   c
10  Z   3   c
11  A   3   c

Problem

I have a dataframe (df) as such: ``` A B 1 a 2 b 3 c ``` And a series: `S = pd.Series(['x','y','z'])` I want to repeat the dataframe df for each value in the series. The expected result is to be like this: result: ``` S A B x 1 a y 1 a z 1 a x 2 b y 2 b z 2 b x 3 c y 3 c z 3 c ``` How do I achieve this kind of output? I'm thinking of merge or join but mergeing is giving me a memory error. I am dealing with a rather large dataframe and series. Thanks!

Original source