Skip to content

Instantly share code, notes, and snippets.

@janpipek
Last active August 3, 2016 14:25
Show Gist options
  • Save janpipek/e14c6b8121607e59a60a803df6adeb1e to your computer and use it in GitHub Desktop.
Save janpipek/e14c6b8121607e59a60a803df6adeb1e to your computer and use it in GitHub Desktop.
Make multiple copies of each row
import numpy as np
def multiply_rows(df, n, group=True):
"""Make multiple copies of each row in pandas.
:param df: the dataframe
:param n: how many copies
:param group: whether to group copies next to each other (AABB) or not (ABAB)
"""
new_df = pd.DataFrame()
for col in df:
series = df[col]
if group:
new_df[col] = np.broadcast_to(series, (n,) + series.shape).T.flatten()
else:
new_df[col] = np.broadcast_to(series, (n,) + series.shape).flatten()
return new_df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment