I have a Pandas DataFrame that looks like this:
df = pd.DataFrame({'col1': [1, 2, 3],
'col2': [4, 5, 6],
'col3': [7, 8, 9]})
df
col1 col2 col3
0 1 4 7
1 2 5 8
2 3 6 9
I would like to create a Pandas DataFrame like this:
df_new
col1 col2 col3
0 1 4 7
1 1 5 8
2 1 6 9
3 2 4 7
4 2 5 8
5 2 6 9
6 3 4 7
7 3 5 8
8 3 6 9
Is there built-in or combination of built-in Pandas methods that can achieve this?
Even if there are duplicates in df
, I would like the output to be the same format. In other words:
df
col1 col2 col3
0 1 4 7
1 2 5 8
2 2 6 8
df_new
col1 col2 col3
0 1 4 7
1 1 5 8
2 1 6 8
3 2 4 7
4 2 5 8
5 2 6 8
6 2 4 7
7 2 5 8
8 2 6 8
df[['col1']].merge(df[['col2', 'col3']], how='cross').reset_index(drop=True)
Is this correct or do you actually just need to scale your DataFrame a fixed number of times based on column values or otherwise?how='cross'
! It could also beto_tile=['col1']; df[to_tile].merge(df[df.columns.difference(to_tile)], how='cross').reset_index(drop=True)